{
"cells": [
{
"cell_type": "markdown",
"id": "76c5cc8e",
"metadata": {
"id": "76c5cc8e"
},
"source": [
"# Balanced arithmetic expression dataset generator\n",
"\n",
"We create a synthetic dataset of nested arithmetic expressions with exact step-level balance across `train`, `validation`, and `test`. Expressions use:\n",
"\n",
"- parentheses: `()`\n",
"- square brackets: `[]`\n",
"- curly braces: `{}`\n",
"\n",
"Operators: `+`, `-`, `*`.\n",
"\n",
"Each sample contains:\n",
"\n",
"- `expression` \u2014 the arithmetic expression\n",
"- `prompt` \u2014 the model input\n",
"- `completion` \u2014 the target reasoning trace and final answer\n",
"- `answer` \u2014 the final numeric result\n",
"- `steps` \u2014 the number of reduction steps\n",
"- `text` \u2014 the full formatted training sample\n",
"\n",
"The dataset is generated deterministically."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f9898057",
"metadata": {
"id": "f9898057"
},
"outputs": [],
"source": [
"!pip install -U datasets huggingface_hub pandas matplotlib tqdm"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "46fca299",
"metadata": {
"id": "46fca299",
"outputId": "c42804a0-03ca-4cd6-f12d-d8de689c202b",
"colab": {
"base_uri": "https://localhost:8080/"
}
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"repo_id=pymlex/calculator\n",
"push_to_hub=True\n",
"replace_remote=False\n",
"output_dir=/content/calculator_dataset_build/exports\n"
]
}
],
"source": [
"from __future__ import annotations\n",
"\n",
"import json\n",
"import os\n",
"import random\n",
"from dataclasses import dataclass\n",
"from pathlib import Path\n",
"from typing import List, Tuple\n",
"\n",
"import matplotlib.pyplot as plt\n",
"import pandas as pd\n",
"from datasets import Dataset, DatasetDict\n",
"from huggingface_hub import HfApi, login, upload_folder\n",
"from tqdm.auto import tqdm\n",
"\n",
"os.environ[\"TOKENIZERS_PARALLELISM\"] = \"false\"\n",
"\n",
"SEED = 1234\n",
"REPO_ID = os.environ.get(\"HF_REPO_ID\", \"pymlex/calculator\")\n",
"HF_TOKEN = os.environ.get(\"HF_TOKEN\", \"\")\n",
"PUSH_TO_HUB = os.environ.get(\"PUSH_TO_HUB\", \"1\") == \"1\"\n",
"REPLACE_REMOTE = os.environ.get(\"REPLACE_REMOTE\", \"0\") == \"1\"\n",
"\n",
"NUM_STEPS = list(range(1, 16))\n",
"TARGET_COUNTS = {\n",
" \"train\": 1000,\n",
" \"validation\": 50,\n",
" \"test\": 200,\n",
"}\n",
"\n",
"BRACKETS = [(\"(\", \")\"), (\"[\", \"]\"), (\"{\", \"}\")]\n",
"OPS = {\"+\": 1, \"-\": 1, \"*\": 2}\n",
"BRACKET_CLOSE_TO_OPEN = {close: open_ for open_, close in BRACKETS}\n",
"\n",
"run_dir = Path(\"./calculator_dataset_build\")\n",
"out_dir = run_dir / \"exports\"\n",
"out_dir.mkdir(parents=True, exist_ok=True)\n",
"\n",
"print(f\"repo_id={REPO_ID}\")\n",
"print(f\"push_to_hub={PUSH_TO_HUB}\")\n",
"print(f\"replace_remote={REPLACE_REMOTE}\")\n",
"print(f\"output_dir={out_dir.resolve()}\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "1c393124",
"metadata": {
"id": "1c393124",
"outputId": "0672005a-f7fd-4d0b-bed1-bffad899d88f",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 368,
"referenced_widgets": [
"ab6c02b19a41491fb1e31abdf53a4ea0",
"abd5779a1efe458dad7954bff434777d",
"5c88f129bf2f444c8571000b0393a145",
"8659605380424b7483de2acf8a8ab75e",
"ec0fb945a46f413eb38605951387f16f",
"77b9280f8a3545a6aea194b8343db991",
"ef55c571cdad4ac88700304c08bcf44d",
"86ebeb71be0d4ab086422de6a0b26014",
"dd87db9eebf54979aca8eb9b2ba5f81f",
"b14ddb992fd6440ca38ffb705d5ebe3a",
"371d6184a5574ea4801b2350649eb02a",
"3cf9655677e34c9682dbb7655ea8dcc8",
"6ce248b26b8b441d814fc06c139e0e4b",
"de854fd2c6394c289e24d2b3ff4d6689",
"f9a658064e3241eeb0d5ae478cff163e",
"6eb340fb39174e79b95f489b912439eb",
"d18a8f8d27fb4b9281ae94194774f23e",
"b3b81c87a8c643b7aa1aa958004bfb32",
"ffc12fd17af04793896dbb63b71a8217",
"5ad44b688b254ff2b4e93599ce8b3087",
"330566aef83543f9adf5bc57e723e427",
"272ef197eb6440448d0586c3b8cdb98b",
"cc478252fc424389ae43b76403c54aba",
"781a2ceb962e44f6a0a7511f189c7e8f",
"092d356036f64754b2d0ffc53546c370",
"4560507e1dd24a84ad08d9714195a3ae",
"fb8bb5940bdd46bca62683370155e7de",
"e51f1c94267f4c39886e022ce8a48a55",
"7372ff055a834612bb77709e34c37acf",
"88dcd0aaa199433992994a9960968cf1",
"e43cb60d1d7d41269287dbf08d388776",
"d5ec3d0e33b1436a8acd449dd91853ac",
"b8407ff89f19465db4c090c1b7ba30cf"
]
}
},
"outputs": [
{
"output_type": "display_data",
"data": {
"text/plain": [
"building train: 0%| | 0/15 [00:00, ?it/s]"
],
"application/vnd.jupyter.widget-view+json": {
"version_major": 2,
"version_minor": 0,
"model_id": "ab6c02b19a41491fb1e31abdf53a4ea0"
}
},
"metadata": {}
},
{
"output_type": "display_data",
"data": {
"text/plain": [
"building validation: 0%| | 0/15 [00:00, ?it/s]"
],
"application/vnd.jupyter.widget-view+json": {
"version_major": 2,
"version_minor": 0,
"model_id": "3cf9655677e34c9682dbb7655ea8dcc8"
}
},
"metadata": {}
},
{
"output_type": "display_data",
"data": {
"text/plain": [
"building test: 0%| | 0/15 [00:00, ?it/s]"
],
"application/vnd.jupyter.widget-view+json": {
"version_major": 2,
"version_minor": 0,
"model_id": "cc478252fc424389ae43b76403c54aba"
}
},
"metadata": {}
},
{
"output_type": "execute_result",
"data": {
"text/plain": [
"DatasetDict({\n",
" train: Dataset({\n",
" features: ['prompt', 'completion', 'answer', 'expression', 'steps', 'text'],\n",
" num_rows: 15000\n",
" })\n",
" validation: Dataset({\n",
" features: ['prompt', 'completion', 'answer', 'expression', 'steps', 'text'],\n",
" num_rows: 750\n",
" })\n",
" test: Dataset({\n",
" features: ['prompt', 'completion', 'answer', 'expression', 'steps', 'text'],\n",
" num_rows: 3000\n",
" })\n",
"})"
]
},
"metadata": {},
"execution_count": 2
}
],
"source": [
"@dataclass(frozen=True)\n",
"class Node:\n",
" kind: str\n",
" value: int | None = None\n",
" op: str | None = None\n",
" left: \"Node | None\" = None\n",
" right: \"Node | None\" = None\n",
" open_br: str | None = None\n",
" close_br: str | None = None\n",
"\n",
"\n",
"def leaf(value: int) -> Node:\n",
" return Node(kind=\"num\", value=value)\n",
"\n",
"\n",
"def branch(left: Node, op: str, right: Node, open_br: str, close_br: str) -> Node:\n",
" return Node(\n",
" kind=\"binop\",\n",
" op=op,\n",
" left=left,\n",
" right=right,\n",
" open_br=open_br,\n",
" close_br=close_br,\n",
" )\n",
"\n",
"\n",
"def render(node: Node) -> str:\n",
" if node.kind == \"num\":\n",
" return str(node.value)\n",
" left = render(node.left)\n",
" right = render(node.right)\n",
" return f\"{node.open_br}{left} {node.op} {right}{node.close_br}\"\n",
"\n",
"\n",
"def eval_node(node: Node) -> int:\n",
" if node.kind == \"num\":\n",
" return int(node.value)\n",
" a = eval_node(node.left)\n",
" b = eval_node(node.right)\n",
" if node.op == \"+\":\n",
" return a + b\n",
" if node.op == \"-\":\n",
" return a - b\n",
" return a * b\n",
"\n",
"\n",
"def build_exact_tree(rng: random.Random, internal_nodes: int) -> Node:\n",
" if internal_nodes == 0:\n",
" return leaf(rng.randint(0, 99))\n",
"\n",
" left_internal = rng.randint(0, internal_nodes - 1)\n",
" right_internal = internal_nodes - 1 - left_internal\n",
"\n",
" left = build_exact_tree(rng, left_internal)\n",
" right = build_exact_tree(rng, right_internal)\n",
" op = rng.choice(list(OPS))\n",
" open_br, close_br = rng.choice(BRACKETS)\n",
" return branch(left, op, right, open_br, close_br)\n",
"\n",
"\n",
"def tokenize(expr: str) -> List[str]:\n",
" tokens: List[str] = []\n",
" i = 0\n",
" while i < len(expr):\n",
" ch = expr[i]\n",
" if ch.isspace():\n",
" i += 1\n",
" continue\n",
" if ch.isdigit():\n",
" j = i + 1\n",
" while j < len(expr) and expr[j].isdigit():\n",
" j += 1\n",
" tokens.append(expr[i:j])\n",
" i = j\n",
" continue\n",
" tokens.append(ch)\n",
" i += 1\n",
" return tokens\n",
"\n",
"\n",
"def apply_op(values: List[int], exprs: List[str], ops: List[str], trace: List[str], step_id: int) -> int:\n",
" right = values.pop()\n",
" left = values.pop()\n",
"\n",
" right_expr = exprs.pop()\n",
" left_expr = exprs.pop()\n",
" op = ops.pop()\n",
"\n",
" if op == \"+\":\n",
" result = left + right\n",
" elif op == \"-\":\n",
" result = left - right\n",
" else:\n",
" result = left * right\n",
"\n",
" values.append(result)\n",
" exprs.append(str(result))\n",
" trace.append(f\"{step_id}. ({left_expr} {op} {right_expr}) = {result}\")\n",
" return step_id + 1\n",
"\n",
"\n",
"def evaluate_with_trace(expr: str) -> Tuple[int, str]:\n",
" tokens = tokenize(expr)\n",
"\n",
" values: List[int] = []\n",
" exprs: List[str] = []\n",
" ops: List[str] = []\n",
"\n",
" trace: List[str] = [f\"Start: {expr}\"]\n",
" step_id = 1\n",
"\n",
" for tok in tokens:\n",
" if tok.isdigit():\n",
" values.append(int(tok))\n",
" exprs.append(tok)\n",
" continue\n",
"\n",
" if tok in OPS:\n",
" while ops and ops[-1] in OPS and OPS[ops[-1]] >= OPS[tok]:\n",
" step_id = apply_op(values, exprs, ops, trace, step_id)\n",
" ops.append(tok)\n",
" continue\n",
"\n",
" if tok in {\"(\", \"[\", \"{\"}:\n",
" ops.append(tok)\n",
" continue\n",
"\n",
" if tok in {\")\", \"]\", \"}\"}:\n",
" open_br = BRACKET_CLOSE_TO_OPEN[tok]\n",
" while ops and ops[-1] != open_br:\n",
" step_id = apply_op(values, exprs, ops, trace, step_id)\n",
" ops.pop()\n",
" continue\n",
"\n",
" raise ValueError(f\"Unexpected token: {tok}\")\n",
"\n",
" while ops:\n",
" step_id = apply_op(values, exprs, ops, trace, step_id)\n",
"\n",
" return values[0], \"\\n\".join(trace)\n",
"\n",
"\n",
"def make_example(rng: random.Random, steps: int) -> dict:\n",
" tree = build_exact_tree(rng, steps)\n",
" expr = render(tree)\n",
" answer = eval_node(tree)\n",
" trace_answer, trace = evaluate_with_trace(expr)\n",
" assert answer == trace_answer\n",
"\n",
" prompt = f\"Calculate: {expr}\"\n",
" completion = f\"
| \n", " | train | \n", "validation | \n", "test | \n", "
|---|---|---|---|
| 1 | \n", "1000 | \n", "50 | \n", "200 | \n", "
| 2 | \n", "1000 | \n", "50 | \n", "200 | \n", "
| 3 | \n", "1000 | \n", "50 | \n", "200 | \n", "
| 4 | \n", "1000 | \n", "50 | \n", "200 | \n", "
| 5 | \n", "1000 | \n", "50 | \n", "200 | \n", "
| 6 | \n", "1000 | \n", "50 | \n", "200 | \n", "
| 7 | \n", "1000 | \n", "50 | \n", "200 | \n", "
| 8 | \n", "1000 | \n", "50 | \n", "200 | \n", "
| 9 | \n", "1000 | \n", "50 | \n", "200 | \n", "
| 10 | \n", "1000 | \n", "50 | \n", "200 | \n", "
| 11 | \n", "1000 | \n", "50 | \n", "200 | \n", "
| 12 | \n", "1000 | \n", "50 | \n", "200 | \n", "
| 13 | \n", "1000 | \n", "50 | \n", "200 | \n", "
| 14 | \n", "1000 | \n", "50 | \n", "200 | \n", "
| 15 | \n", "1000 | \n", "50 | \n", "200 | \n", "