Datasets:

Modalities:
Tabular
Text
Formats:
parquet
Languages:
English
Size:
< 1K
ArXiv:
License:
File size: 18,138 Bytes
90cf45f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d0b84e
 
90cf45f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
"""Build HuggingFaceSwarms/smallmath-matharena-empty-answers from pinned inputs.

Inputs (all pinned):
  - MathArena/smallmath_outputs @ 065cbde6cf4691ef5d887db8021d12cf0001a1a1 (MathArena's attempts)
  - MathArena/smallmath @ 13ef9727659718de8bcba221cfe8f8a65bf88a99 (benchmark: problems, answers, levels)
  - HuggingFaceSwarms/SmallMath @ 57dbf3f7e83aa8c5c980387a2216d7bb87e4e7cc (our Harbor tasks and grader)
  - source/legion_pi_per_task.jsonl in this repo (our Legion Pi run, written by scripts/extract_legion_run.py)

Outputs: data/empty_answers.parquet, data/per_problem.parquet, figures/scores_by_level.{png,csv} and
figures/summary.json (every number quoted in README.md).

Usage: python scripts/build.py   (needs pyarrow, numpy, matplotlib, huggingface_hub; about 250 MB download)
"""
import collections
import hashlib
import json
import sys
from pathlib import Path

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pyarrow as pa
import pyarrow.parquet as pq
from huggingface_hub import hf_hub_download, snapshot_download

ROOT = Path(__file__).resolve().parent.parent
OUTPUTS = ("MathArena/smallmath_outputs", "065cbde6cf4691ef5d887db8021d12cf0001a1a1")
BENCH = ("MathArena/smallmath", "13ef9727659718de8bcba221cfe8f8a65bf88a99")
TASKS = ("HuggingFaceSwarms/SmallMath", "57dbf3f7e83aa8c5c980387a2216d7bb87e4e7cc")
CONFIG = "qwen/qwen3.8-27b-low-openrouter"
OUT_FILES = ("data/train-00000-of-00002.parquet", "data/train-00001-of-00002.parquet")
TAIL = 500
# Reasoning that stops on one of these (after trailing whitespace) might have ended at a sentence or expression
# boundary, so the mid-text flag is conservative: it is set only when the last character is none of them.
BOUNDARY = set(".!?✓✗$)]}")
B, SEED = 10_000, 0
LEVELS = range(1, 7)


def plot(summary):
    """Draw figures/scores_by_level.png from summary.json's numbers alone."""
    PALETTE = ["#00A5A6", "#E03D90", "#FC744C", "#1968DF", "#B893F5", "#E1C700"]
    BASELINE, INK, SLATE, MUTED = "#8B9999", "#090C0C", "#3A4848", "#5C737B"
    STYLE = {
        "figure.facecolor": "white", "axes.facecolor": "white", "savefig.facecolor": "white",
        "savefig.dpi": 200, "savefig.bbox": "tight", "savefig.pad_inches": 0.3, "font.family": "sans-serif",
        "font.sans-serif": ["Inter", "Helvetica Neue", "Helvetica", "Arial", "Liberation Sans", "DejaVu Sans"],
        "font.size": 11, "text.color": INK, "axes.labelcolor": SLATE,
        "axes.spines.top": False, "axes.spines.right": False, "axes.spines.left": False,
        "axes.edgecolor": BASELINE, "axes.linewidth": 0.8,
        "axes.grid": True, "axes.grid.axis": "y", "axes.axisbelow": True, "grid.color": "#E2EEEE", "grid.linewidth": 0.8,
        "xtick.color": BASELINE, "ytick.color": BASELINE, "xtick.labelcolor": SLATE, "ytick.labelcolor": SLATE,
        "xtick.labelsize": 10, "ytick.labelsize": 10, "xtick.major.size": 0, "ytick.major.size": 4, "legend.frameon": False,
    }
    plotted = [("matharena_published", "MathArena as published (empty = wrong)", BASELINE),
               ("matharena_answered_only", "MathArena, answered attempts only", PALETTE[1]),
               ("legion_pi", "Legion Pi run (1 attempt)", PALETTE[0])]
    G = summary["groups"]
    n_empty = summary["empty_attempts"]["total"]
    gnames = list(G)
    val = {n: G["All"][n]["value"] for n, _, _ in plotted}
    title = (f"MathArena's Qwen3.8-27B (low) scores {val['matharena_published']:.1f}% on SmallMath as published, "
             f"{val['matharena_answered_only']:.1f}%\non answered attempts only; our Legion Pi run scores {val['legion_pi']:.1f}%")
    subtitle = (f"Qwen3.8-27B, effort low, on all 600 SmallMath problems (100 per level). MathArena: 2 attempts per problem, "
                f"{n_empty} of 1,200 with an empty answer.\nPi: 1 attempt per problem with bash/Python tools. "
                f"Error bars: 95% bootstrap CI over problems ({summary['bootstrap']['resamples']:,} resamples; stratified by level for All).")
    footer = (f"MathArena/smallmath_outputs @ {OUTPUTS[1][:8]} (config {CONFIG}) · MathArena/smallmath @ {BENCH[1][:8]} · "
              f"HuggingFaceSwarms/SmallMath @ {TASKS[1][:8]} · Legion main d722a96\n"
              "'Answered only' = correct / answered attempts, a conditional statistic: the empty attempts are concentrated "
              "on L4–L6, so it is strongly selected by level. Script: scripts/build.py")
    with mpl.rc_context(STYLE):
        fig, ax = plt.subplots(figsize=(11, 5.2))
        x = np.arange(len(gnames)) * 1.0
        x[1:] += 0.35  # gap after "All"
        w = 0.26
        for j, (n, label, col) in enumerate(plotted):
            xs = x + (j - 1) * w
            v = np.array([G[g][n]["value"] for g in gnames])
            lo = np.array([G[g][n]["ci"][0] for g in gnames])
            hi = np.array([G[g][n]["ci"][1] for g in gnames])
            ax.bar(xs, v, width=w * 0.92, color=col, label=label, zorder=2)
            ax.errorbar(xs, v, yerr=[v - lo, hi - v], fmt="none", ecolor=INK, elinewidth=0.8, capsize=0, zorder=3, alpha=0.7)
            for xi, vi, hii in zip(xs, v, hi):
                ax.annotate(f"{vi:.1f}" if vi < 99.95 else "100", (xi, max(hii, vi)), xytext=(0, 2),
                            textcoords="offset points", ha="center", va="bottom", size=7.5, color=SLATE)
        ticks = []
        for g in gnames:
            a_ok = G[g]["matharena_answered_only"]["denominator"]
            ticks.append(f"{g} (n={G[g]['problems']})\n{a_ok}/{2 * G[g]['problems']}\nanswered")
        ax.set_xticks(x, ticks)
        for lab in ax.get_xticklabels()[:1]:
            lab.set_fontweight("bold")
        ax.set_ylim(0, 108)
        ax.set_yticks(range(0, 101, 20), [f"{t}%" for t in range(0, 101, 20)])
        ax.margins(x=0.01)
        pt = dict(xy=(0, 1), xycoords="axes fraction", textcoords="offset points", ha="left")
        ax.annotate(title, xytext=(0, 84), size=15, weight="bold", color=INK, va="bottom", **pt)
        ax.annotate(subtitle, xytext=(0, 46), size=9.5, color=SLATE, va="bottom", **pt)
        ax.annotate("Accuracy (%)", xytext=(0, 12), size=10, weight="bold", color=INK, va="bottom", **pt)
        ax.legend(loc="lower left", bbox_to_anchor=(0.16, 1.0), ncol=3, fontsize=9.5, handlelength=1, handleheight=1,
                  borderaxespad=0.6, columnspacing=1.6)
        ax.annotate(footer, (0, 0), xycoords="axes fraction", xytext=(0, -62), textcoords="offset points",
                    va="top", size=7.5, color=MUTED)
        fig.savefig(ROOT / "figures" / "scores_by_level.png")
        plt.close(fig)


if "--plot-only" in sys.argv:
    plot(json.loads((ROOT / "figures" / "summary.json").read_text()))
    sys.exit(0)


def dl(repo, rev, filename):
    return hf_hub_download(repo, filename, repo_type="dataset", revision=rev)


# ---------------------------------------------------------------- inputs
bench = {int(r["problem_idx"]): r for r in pq.read_table(dl(*BENCH, "data/train-00000-of-00001.parquet")).to_pylist()}
assert len(bench) == 600

snap = Path(snapshot_download(TASKS[0], repo_type="dataset", revision=TASKS[1], allow_patterns=[
    "tasks/manifest.json", "tasks/*/instruction.md", "tasks/*/tests/reference.json", "tasks/smallmath-0015/tests/*"]))
manifest = json.loads((snap / "tasks" / "manifest.json").read_text())
tasks = {t["task"]: t for t in manifest["tasks"]}
assert len(tasks) == 600 == manifest["task_count"], len(tasks)

# Every MathArena row of the Qwen3.8-27B (low) config, with its location in the outputs dataset.
ma, offset = [], 0
for f in OUT_FILES:
    t = pq.read_table(dl(*OUTPUTS, f))
    keep = [i for i, c in enumerate(t.column("model_config").to_pylist()) if c == CONFIG]
    sub = t.take(pa.array(keep, type=pa.int64())).to_pylist()
    for i, r in zip(keep, sub):
        r.update(_file=f, _file_row=i, _split_row=offset + i)
    ma += sub
    offset += t.num_rows
assert len(ma) == 1200, len(ma)
by_key = {(r["problem_idx"], r["idx_answer"]): r for r in ma}
assert len(by_key) == 1200

legion = {json.loads(x)["task"]: json.loads(x) for x in (ROOT / "source" / "legion_pi_per_task.jsonl").read_text().splitlines()}
assert len(legion) == 600

# ---------------------------------------------------------------- task <-> MathArena mapping (re-derived)
checks = collections.Counter()
task_of = {}
for name, t in sorted(tasks.items()):
    pid = int(t["problem_id"])
    b = bench[pid]
    instr = (snap / "tasks" / name / "instruction.md").read_text()
    ref = json.loads((snap / "tasks" / name / "tests" / "reference.json").read_text())["answer"]
    assert instr.rstrip("\n").endswith(b["problem"].rstrip("\n")), name
    assert "Problem:\n\n" + b["problem"].strip() in instr, name
    assert ref == b["answer"] and t["level"] == b["level"] and t["stable_id"] == b["stable_id"], name
    for k in (0, 1):
        r = by_key[(str(pid), k)]
        assert r["problem"] == b["problem"] and r["gold_answer"] == b["answer"] and r["level"] == b["level"], (name, k)
    checks["tasks matched (text, answer, level, stable_id; both MathArena attempts)"] += 1
    task_of[str(pid)] = name
assert len(task_of) == 600 and set(task_of) == {r["problem_idx"] for r in ma}

# ---------------------------------------------------------------- our grader reproduces MathArena's verdicts
tests = snap / "tasks" / "smallmath-0015" / "tests"
assert hashlib.sha256((tests / "grader.py").read_bytes()).hexdigest() == manifest["grader_sha256"]
sys.path.insert(0, str(tests))
import grade_task  # noqa: E402  (SmallMath's verifier; unpacks its pinned sympy/mpmath wheels)

grader = grade_task.load_grader(str(tests))
disagree = []
for r in ma:
    p = r["parsed_answer"]
    ours = bool(p and p != "None" and p.strip()) and grader.grade_safe(r["gold_answer"], p, timeout=60)[0]
    if bool(ours) != bool(r["correct"]):
        disagree.append((r["problem_idx"], r["idx_answer"], p, r["gold_answer"], r["correct"]))
assert not disagree, disagree
checks["MathArena verdicts reproduced by our grader on their parsed answers"] = len(ma)


# ---------------------------------------------------------------- per attempt
def reasoning(r):
    msgs = json.loads(r["all_messages"])
    cot = [m["content"] for m in msgs if m.get("type") == "cot"]
    assert len(cot) == 1, (r["problem_idx"], r["idx_answer"])
    return cot[0]


def is_empty(r):
    return r["answer"] is None or r["answer"].strip() == ""


att = {}
for r in ma:
    c = reasoning(r)
    att[(r["problem_idx"], r["idx_answer"])] = dict(
        empty=is_empty(r), correct=bool(r["correct"]), out=r["output_tokens"], cot=c,
        nl=c.endswith("\n"), mid=(not c.endswith("\n")) and c.rstrip()[-1:] not in BOUNDARY)
answered = [a for a in att.values() if not a["empty"]]
empties = {k: a for k, a in att.items() if a["empty"]}
assert all(a["nl"] for a in answered), "an answered attempt's reasoning lacks a trailing newline"
assert not any(a["correct"] for a in empties.values())

# ---------------------------------------------------------------- rows: MathArena empty, ours submitted
rows = []
for (pid, k), a in sorted(empties.items(), key=lambda kv: (task_of[kv[0][0]], kv[0][1])):
    r, name = by_key[(pid, k)], task_of[pid]
    lg = legion[name]
    if not lg["submission"]:
        continue
    other = att[(pid, 1 - k)]
    rows.append({
        "matharena_problem_idx": pid,
        "matharena_idx_answer": k,
        "matharena_model_config": CONFIG,
        "matharena_file": r["_file"],
        "matharena_file_row": r["_file_row"],
        "matharena_split_row": r["_split_row"],
        "task_id": name,
        "level": r["level"],
        "stable_id": tasks[name]["stable_id"],
        "problem": r["problem"],
        "gold_answer": r["gold_answer"],
        "legion_submission": lg["submission"],
        "legion_correct": lg["correct"],
        "matharena_output_tokens": r["output_tokens"],
        "matharena_reasoning_chars": len(a["cot"]),
        "matharena_reasoning_ends_with_newline": a["nl"],
        "matharena_reasoning_ends_mid_text": a["mid"],
        "matharena_reasoning_tail": a["cot"][-TAIL:],
        "matharena_other_attempt_empty": other["empty"],
        "matharena_other_attempt_correct": other["correct"],
        "legion_output_tokens": lg["output_tokens"],
        "legion_tool_calls": lg["tool_calls"],
        "legion_llm_calls": lg["llm_calls"],
    })

per_problem = []
for pid, name in sorted(task_of.items(), key=lambda kv: kv[1]):
    a0, a1, lg = att[(pid, 0)], att[(pid, 1)], legion[name]
    per_problem.append({
        "task_id": name, "matharena_problem_idx": pid, "level": bench[int(pid)]["level"],
        "stable_id": tasks[name]["stable_id"],
        "matharena_correct_0": a0["correct"], "matharena_correct_1": a1["correct"],
        "matharena_empty_0": a0["empty"], "matharena_empty_1": a1["empty"],
        "matharena_output_tokens_0": a0["out"], "matharena_output_tokens_1": a1["out"],
        "matharena_split_row_0": by_key[(pid, 0)]["_split_row"], "matharena_split_row_1": by_key[(pid, 1)]["_split_row"],
        "legion_submitted": bool(lg["submission"]), "legion_reward": int(lg["correct"]),
    })

(ROOT / "data").mkdir(exist_ok=True)
pq.write_table(pa.Table.from_pylist(rows), ROOT / "data" / "empty_answers.parquet")
pq.write_table(pa.Table.from_pylist(per_problem), ROOT / "data" / "per_problem.parquet")

# ---------------------------------------------------------------- scores, from per_problem only
pp = per_problem
lv = np.array([p["level"] for p in pp])
c = np.array([[p["matharena_correct_0"], p["matharena_correct_1"]] for p in pp], float)
e = np.array([[p["matharena_empty_0"], p["matharena_empty_1"]] for p in pp], bool)
ok = (~e).astype(float)
leg = np.array([p["legion_reward"] for p in pp], float)
both_empty = e.all(1)


def series(idx):
    """Point estimates on the problems idx: published, answered-only (attempt-level), per-problem variant, Legion."""
    return np.array([
        c[idx].sum() / (2 * len(idx)),
        (c[idx] * ok[idx]).sum() / ok[idx].sum(),
        np.mean([(c[i] * ok[i]).sum() / ok[i].sum() for i in idx if not both_empty[i]]),
        leg[idx].mean(),
    ]) * 100


rng = np.random.default_rng(SEED)
groups = {"All": np.arange(600), **{f"L{L}": np.where(lv == L)[0] for L in LEVELS}}
boots = {g: [] for g in groups}
for _ in range(B):
    draw = {f"L{L}": rng.choice(groups[f"L{L}"], size=len(groups[f"L{L}"]), replace=True) for L in LEVELS}
    draw["All"] = np.concatenate([draw[f"L{L}"] for L in LEVELS])  # stratified by level
    for g, idx in draw.items():
        boots[g].append(series(idx))
names = ["matharena_published", "matharena_answered_only", "matharena_answered_per_problem", "legion_pi"]
summary = {"groups": {}, "checks": dict(checks), "bootstrap": {"resamples": B, "seed": SEED, "ci": "95% percentile"}}
csv = ["group,series,value,ci_low,ci_high,numerator,denominator"]
for g, idx in groups.items():
    pt, bs = series(idx), np.array(boots[g])
    lo, hi = np.percentile(bs, 2.5, axis=0), np.percentile(bs, 97.5, axis=0)
    num = [c[idx].sum(), (c[idx] * ok[idx]).sum(), None, leg[idx].sum()]
    den = [2 * len(idx), ok[idx].sum(), int((~both_empty[idx]).sum()), len(idx)]
    summary["groups"][g] = {
        "problems": len(idx), "attempts_empty": int(e[idx].sum()), "problems_both_empty": int(both_empty[idx].sum()),
        "problems_one_empty": int((e[idx].sum(1) == 1).sum()),
        **{n: {"value": round(float(pt[j]), 2), "ci": [round(float(lo[j]), 2), round(float(hi[j]), 2)],
               "numerator": None if num[j] is None else int(num[j]), "denominator": int(den[j])}
           for j, n in enumerate(names)}}
    for j, n in enumerate(names):
        csv.append(f"{g},{n},{pt[j]:.4f},{lo[j]:.4f},{hi[j]:.4f},{'' if num[j] is None else int(num[j])},{int(den[j])}")
by_lv = collections.Counter(r["level"] for r in rows)
summary["rows"] = {"total": len(rows), "problems": len({r["task_id"] for r in rows}),
                   "by_level": {f"L{L}": by_lv.get(L, 0) for L in LEVELS},
                   "legion_correct": sum(r["legion_correct"] for r in rows),
                   "legion_incorrect_by_level": dict(collections.Counter(f"L{r['level']}" for r in rows if not r["legion_correct"])),
                   "ends_mid_text": sum(r["matharena_reasoning_ends_mid_text"] for r in rows)}
eo = sorted(a["out"] for a in empties.values())
mids = sorted(a["out"] for a in empties.values() if a["mid"])
summary["empty_attempts"] = {
    "total": len(empties), "answer_exactly_empty_string": sum(by_key[k]["answer"] == "" for k in empties),
    "by_level": {f"L{L}": sum(by_key[k]["level"] == L for k in empties) for L in LEVELS},
    "excluded_because_legion_missing": sum(1 for k in empties if not legion[task_of[k[0]]]["submission"]),
    "output_tokens": {"min": eo[0], "median": float(np.median(eo)), "max": eo[-1]},
    "at_65536_output_tokens": sum(o == 65536 for o in eo),
    "reasoning_without_trailing_newline": sum(not a["nl"] for a in empties.values()),
    "ends_mid_text": len(mids),
    "ends_mid_text_output_tokens": {"min": mids[0], "median": float(np.median(mids)), "max": mids[-1]},
    "ends_mid_text_by_level": {f"L{L}": sum(by_key[k]["level"] == L and a["mid"] for k, a in empties.items()) for L in LEVELS},
    "ends_without_sentence_punctuation": sum(a["cot"].rstrip()[-1:] not in ".!?" for a in empties.values()),
}
summary["answered_attempts"] = {"total": len(answered), "correct": sum(a["correct"] for a in answered),
                                "max_output_tokens": max(a["out"] for a in answered),
                                "reasoning_with_trailing_newline": sum(a["nl"] for a in answered)}
(ROOT / "figures").mkdir(exist_ok=True)
(ROOT / "figures" / "scores_by_level.csv").write_text("\n".join(csv) + "\n")
(ROOT / "figures" / "summary.json").write_text(json.dumps(summary, indent=1) + "\n")

plot(summary)
print(json.dumps({k: v for k, v in summary.items() if k != "groups"}, indent=1))
for g in groups:
    print(g, {n: (G[g][n]["value"], G[g][n]["ci"], G[g][n]["numerator"], G[g][n]["denominator"]) for n in names},
          "both_empty", G[g]["problems_both_empty"])