"""SFT trace sets: hard long-form warm-up traces (PLAN step 3.1) and Python-tool traces (step 3.4). python -m pocket_math.traces build --out data_out/sft [--warmup 20000] [--tool 10000] Writes warmup.jsonl, tool.jsonl and manifest.json. Rows have the shape sft_data.sft_rows reads: {"uid": "/", "problem", "response", "source", "meta"}. Every response is "\\n{reasoning}\\n\\n\\n{solution}", the layout VibeThinker writes (its published scores come from rllm's grader, which rejects answers without ). A tool call is "\\n{code}\\n" followed by "\\n```output\\n{stdout}\\n```\\n", which is what generate.py's tool loop produces, so sft_data.response_mask gives tool output loss 0. Tool rows carry evaluate.TOOL_NOTE after the problem, as phases.prompt_ids adds it in tool-mode evaluation. Datasets are read as whole Parquet row groups at the commit recorded in the manifest: a file is picked at random (seeded), then an unread row group in it, until a source has enough traces that pass the per-trace filters. Streaming from the head would see one subset only, because Nemotron-SFT-Math-v4 is sorted by subset and source. """ from __future__ import annotations import argparse import ast import builtins import datetime import hashlib import json import math import os import queue import random import re import threading import time import warnings from collections import Counter, defaultdict from collections.abc import Callable, Iterator from dataclasses import dataclass, field from pathlib import Path from typing import Any, TypeVar from pocket_math import data from pocket_math.config import profile from pocket_math.decontam import ngram_candidates from pocket_math.evaluate import TOOL_NOTE from pocket_math.generate import TOOL_CLOSE, TOOL_OPEN from pocket_math.grading import grade_many from pocket_math.io import sha256_file, write_json, write_jsonl from pocket_math.sft_data import OUTPUT_BLOCK from pocket_math.types import Problem TOKENIZER_REPO = "WeiboAI/VibeThinker-1.5B" TOKENIZER_REVISION = "9614bcb0264f03f18f2fa2406c4a9754635f51de" TOKENIZER_FILES = ["tokenizer.json", "tokenizer_config.json", "vocab.json", "merges.txt", "special_tokens_map.json", "added_tokens.json", "chat_template.jinja"] PROFILE = "vibethinker-1.5b" MAX_SEQ_LEN = 16384 WARMUP_TOKENS = (1000, 14000) TOOL_MAX_TOKENS = 14000 MAX_CALLS = 8 # sandbox.run_python keeps at most this many characters of output; a longer recorded output # shows the model text it would never see. MAX_OUTPUT_CHARS = 4000 THINK_OPEN, THINK_CLOSE = "", "" HARD_FLOOR = 0.25 KINDS = ("warmup", "tool") FILES = {"warmup": "warmup.jsonl", "tool": "tool.jsonl"} SKIPPED = { "Alibaba-Apsara/Superior-Reasoning-SFT-gpt-oss-120b": { "license": "cc-by-4.0", "reason": "No reference answer: rows have only uuid, input, output, domain and meta, so no trace can be " "verified against an expected answer (filter 2). Its problems come from AM-DeepSeek-R1-Distilled " "and AceReason-1.1-SFT, whose answers are not in any set this build reads. Its teacher " "(gpt-oss-120b, high reasoning) is also the teacher of nvidia/Nemotron-Math-v2, which is used.", }, } DIFFERENCES_FROM_PLAN = [ "nvidia/Nemotron-SFT-Math-v4 has one split (train); the tool traces are the rows with subset == 'tir' " "(shards 7-11) and the plain traces the rows with subset == 'cot'. Its solutions come from DeepSeek-V4-Pro.", "Many Nemotron-SFT-Math-v4 'tir' rows make no tool call (82% of one sampled row group). Tool rows without a " "call are dropped while parsing (reason 'no tool call'), before the costly answer check, instead of at the " "tool-format filter.", "nvidia/Nemotron-Math-v2 has splits high_part00-02, medium and low (no 'train'); only the high-reasoning " "splits are read, and only rows without a tool definition or tool messages.", "Both tool sources ran code in a stateful Jupyter kernel; our sandbox runs each call as a fresh script that " "shows only stdout. Cells that use names defined elsewhere are dropped (needs_state), and a bare final " "expression whose value the kernel displayed is wrapped in print().", "nvidia/OpenMathReasoning TIR solutions interleave ```system blocks (remaining code executions); they are " "removed because our harness never writes them.", ] class Skip(Exception): """A row that cannot become a trace; the message is the reason recorded in the manifest.""" @dataclass class Trace: uid: str source: str problem: str response: str final: str answer: str | None meta: dict[str, Any] = field(default_factory=dict) pass_rate: float | None = None calls: int = 0 issues: list[str] = field(default_factory=list) def prompt_text(self, kind: str) -> str: return f"{self.problem}\n\n{TOOL_NOTE}" if kind == "tool" else self.problem def row(self, kind: str) -> dict[str, Any]: meta = dict(self.meta) if kind == "tool": meta["problem"] = self.problem return {"uid": self.uid, "problem": self.prompt_text(kind), "response": self.response, "source": self.source, "meta": meta} def think_response(reasoning: str, final: str) -> str: return f"{THINK_OPEN}\n{reasoning.strip()}\n{THINK_CLOSE}\n\n{final.strip()}" def split_think(text: str) -> tuple[str, str]: """(reasoning, solution) of "...solution", with exactly one of each tag.""" text = text.strip() if not text.startswith(THINK_OPEN) or text.count(THINK_OPEN) != 1 or text.count(THINK_CLOSE) != 1: raise Skip("no single think block") reasoning, final = text[len(THINK_OPEN):].split(THINK_CLOSE) return reasoning, final def tool_block(code: str, output: str) -> str: """One call and its result, byte for byte what generate.generate_samples produces (output rstripped like sandbox.format_tool_output).""" return f"{TOOL_OPEN}\n{code.strip()}\n{TOOL_CLOSE}\n```output\n{output.rstrip()}\n```\n" _BUILTINS = set(dir(builtins)) | {"__name__", "__file__", "__doc__", "__builtins__"} _ERROR = re.compile(r"Traceback \(most recent call last\)|^\s*[A-Za-z_][\w.]*(?:Error|Exception)\b", re.M) _NONE_METHODS = {"show", "savefig", "close", "append", "extend", "sort", "update", "clear", "add", "remove", "insert", "write", "seed", "reverse", "shuffle"} _FENCED = re.compile(r"^\s*```(?:python|py)?\n(.*?)```\s*$", re.S) def free_names(tree: ast.AST) -> set[str]: """Names a cell reads but never binds and Python does not provide; empty when it star-imports.""" loaded: set[str] = set() bound: set[str] = set() for n in ast.walk(tree): if isinstance(n, ast.Name): (loaded if isinstance(n.ctx, ast.Load) else bound).add(n.id) elif isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): bound.add(n.name) elif isinstance(n, ast.arg): bound.add(n.arg) elif isinstance(n, ast.alias): if n.name == "*": return set() bound.add(n.asname or n.name.split(".")[0]) elif isinstance(n, ast.ExceptHandler) and n.name: bound.add(n.name) elif isinstance(n, (ast.Global, ast.Nonlocal)): bound.update(n.names) elif isinstance(n, (ast.MatchAs, ast.MatchStar)) and n.name: bound.add(n.name) elif isinstance(n, ast.MatchMapping) and n.rest: bound.add(n.rest) return loaded - bound - _BUILTINS def _displays_value(expr: ast.expr) -> bool: if isinstance(expr, ast.Constant) and expr.value is None: return False if isinstance(expr, ast.Call): f = expr.func if isinstance(f, ast.Name) and f.id in {"print", "exec"}: return False if isinstance(f, ast.Attribute) and f.attr in _NONE_METHODS: return False return True def print_last_expression(code: str, tree: ast.Module) -> str: """Wrap a trailing bare expression in print(), which is what a notebook shows and a script does not.""" last = tree.body[-1] if tree.body else None if not isinstance(last, ast.Expr) or not _displays_value(last.value): return code raw = code.encode("utf-8") lines = raw.splitlines(keepends=True) starts = [0] for line in lines: starts.append(starts[-1] + len(line)) # ast offsets are UTF-8 byte columns. a = starts[last.lineno - 1] + last.col_offset b = starts[last.end_lineno - 1] + last.end_col_offset if raw[b:].lstrip().startswith(b";"): return code return (raw[:a] + b"print(" + raw[a:b] + b")" + raw[b:]).decode("utf-8") def prepare_cell(code: str, output: str) -> tuple[str, list[str]]: """The cell's code as it must be written for our stateless script sandbox, and what makes it unusable.""" fenced = _FENCED.match(code) if fenced: code = fenced.group(1) issues = [] if "```" in output: issues.append("fence_in_output") if len(output) > MAX_OUTPUT_CHARS: issues.append("long_output") try: with warnings.catch_warnings(): warnings.simplefilter("ignore", SyntaxWarning) tree = ast.parse(code) except (SyntaxError, ValueError): return code, [*issues, "syntax_error"] if free_names(tree): issues.append("needs_state") if output.strip(): code = print_last_expression(code, tree) return code, issues def is_error(output: str) -> bool: return bool(_ERROR.search(output)) def render_cell(code: str, output: str | None) -> tuple[str, list[str]]: """One call as a tool block, and its issues; output None means the source has none for the call.""" code, issues = prepare_cell(code, output or "") return tool_block(code, output or ""), (["missing_output"] if output is None else []) + issues def call_issues(outputs: list[str | None]) -> list[str]: """Issues of a trace's calls taken together.""" issues = ["too_many_calls"] if len(outputs) > MAX_CALLS else [] if sum(is_error(o or "") for o in outputs) * 2 > len(outputs): issues.append("mostly_errors") return issues def check_markup(response: str, calls: int) -> list[str]: """Issues when the converted text would not mask as intended: every call needs exactly one output block, and nothing else may look like one.""" issues = [] if response.count(TOOL_OPEN) != calls or response.count(TOOL_CLOSE) != calls: issues.append("stray_tool_tag") if len(OUTPUT_BLOCK.findall(response)) != calls or response.count("```output") != calls: issues.append("stray_output_block") return issues def _content_key(*parts: str) -> str: return hashlib.sha1("\x00".join(parts).encode("utf-8")).hexdigest()[:16] def _problem(row: dict[str, Any]) -> str: text = data.normalize_whitespace(row.get("problem") or "") if not text: raise Skip("empty problem") return text _DELIMITERS = (("\\(", "\\)"), ("\\[", "\\]"), ("$$", "$$"), ("$", "$")) def clean_answer(value: Any) -> str | None: """A reference answer without one pair of math delimiters around all of it, or None when empty.""" text = str(value).strip() if value is not None else "" for left, right in _DELIMITERS: inner = text[len(left): len(text) - len(right)] if (len(text) >= len(left) + len(right) and text.startswith(left) and text.endswith(right) and left not in inner and right not in inner): text = inner.strip() break return text or None def _plain(response: str, final: str) -> None: if TOOL_OPEN in response or TOOL_CLOSE in response or "```output" in response: raise Skip("tool markup in a plain trace") if not final.strip(): raise Skip("empty solution") def _pass_rate_v2(metadata: dict[str, Any] | None) -> float | None: cells = [v for v in (metadata or {}).values() if isinstance(v, dict) and v.get("count")] total = sum(v["count"] for v in cells) return sum(v["pass"] for v in cells) / total if total else None def _pass_rate_omr(value: Any) -> float | None: try: return float(value) except (TypeError, ValueError): return None def _nemotron_messages(row: dict[str, Any]) -> tuple[list[dict], list[dict]]: msgs = row.get("messages") or [] if not msgs or msgs[0]["role"] != "user": raise Skip("unexpected message layout") turns = msgs[1:] assistants = [m for m in turns if m["role"] == "assistant"] if not assistants or turns[-1]["role"] != "assistant": raise Skip("unexpected message layout") return turns, assistants def parse_nemotron_plain(name: str, row: dict[str, Any]) -> Trace: """Nemotron-SFT-Math-v4 'cot' and Nemotron-Math-v2: [user, assistant] with reasoning_content and content.""" if row.get("tools") or any(m["role"] == "tool" or m.get("tool_calls") for m in row.get("messages") or []): raise Skip("tool trace") turns, assistants = _nemotron_messages(row) if len(turns) != 1: raise Skip("unexpected message layout") reasoning, final = assistants[0].get("reasoning_content") or "", assistants[0].get("content") or "" if not reasoning.strip(): raise Skip("no reasoning") response = think_response(reasoning, final) _plain(response, final) split_think(response) problem = _problem(row) return _nemotron_trace(name, row, problem, response, final) def parse_nemotron_tool(name: str, row: dict[str, Any]) -> Trace: """Nemotron-SFT-Math-v4 'tir': assistant turns carry reasoning_content and one tool_call each (arguments is a JSON string {"code": ...}); each is answered by a tool message with the same tool_call_id. The last assistant turn has the final solution in content.""" turns, assistants = _nemotron_messages(row) *calling, last = assistants if last.get("tool_calls") or not (last.get("content") or "").strip(): raise Skip("unexpected message layout") if not calling: raise Skip("no tool call") outputs = {m.get("tool_call_id"): m.get("content") or "" for m in turns if m["role"] == "tool"} text, results, issues = "", [], [] for m in calling: calls = m.get("tool_calls") or [] if len(calls) != 1 or (m.get("content") or "").strip(): raise Skip("unexpected message layout") try: code = json.loads(calls[0]["function"]["arguments"])["code"] except (json.JSONDecodeError, KeyError, TypeError): raise Skip("unreadable tool call") from None output = outputs.get(calls[0]["id"]) block, cell_issues = render_cell(code, output) reasoning = (m.get("reasoning_content") or "").strip() text += (reasoning + "\n\n" if reasoning else "") + block results.append(output) issues += cell_issues text += last.get("reasoning_content") or "" response = think_response(text, last["content"]) split_think(response) trace = _nemotron_trace(name, row, _problem(row), response, last["content"]) trace.calls = len(results) trace.issues = issues + call_issues(results) + check_markup(response, len(results)) return trace def _nemotron_trace(name: str, row: dict[str, Any], problem: str, response: str, final: str) -> Trace: meta: dict[str, Any] = {"expected_answer": row.get("expected_answer")} if "changed_answer_to_majority" in row: # Nemotron-Math-v2: the reference is a majority vote unless a forum answer survived checking. extracted = bool(row.get("original_expected_answer")) and not row.get("changed_answer_to_majority") answer = row.get("expected_answer") if extracted else None meta |= {"teacher": "gpt-oss-120b (high)", "origin": row.get("data_source"), "answer_extracted": extracted} key = _content_key(problem, response) pass_rate = _pass_rate_v2(row.get("metadata")) else: answer = row.get("expected_answer") meta |= {"teacher": "DeepSeek-V4-Pro (high)", "origin": row.get("source"), "source_uuid": row.get("uuid")} key = row.get("uuid") or _content_key(problem, response) pass_rate = None meta |= {k: row[k] for k in ("license", "url", "username", "user_name", "user_url") if row.get(k)} if pass_rate is not None: meta["pass_rate"] = round(pass_rate, 4) return Trace(uid=f"{name}/{key}", source=name, problem=problem, response=response, final=final, answer=clean_answer(answer), meta=meta, pass_rate=pass_rate) _SYSTEM_BLOCK = re.compile(r"```system\n.*?```\n?", re.S) _INLINE_CALL = re.compile(re.escape(TOOL_OPEN) + r"\n?(.*?)" + re.escape(TOOL_CLOSE), re.S) _OUTPUT_AFTER = re.compile(r"[ \t]*\n?```output\n(.*?)```\n?", re.S) def convert_inline_calls(text: str) -> tuple[str, list[str | None], list[str]]: """Text whose calls are written code followed by a ```output block, re-rendered with tool_block. Returns the text, each call's output and the cells' issues.""" parts, results, issues, pos = [], [], [], 0 for m in _INLINE_CALL.finditer(text): follow = _OUTPUT_AFTER.match(text, m.end()) output = follow.group(1) if follow else None block, cell_issues = render_cell(m.group(1), output) parts += [text[pos:m.start()], block] results.append(output) issues += cell_issues pos = follow.end() if follow else m.end() parts.append(text[pos:]) return "".join(parts), results, issues def _omr_trace(name: str, row: dict[str, Any], response: str, final: str) -> Trace: problem = _problem(row) extracted = row.get("problem_type") == "has_answer_extracted" answer = clean_answer(row.get("expected_answer")) if extracted else None pass_rate = _pass_rate_omr(row.get("pass_rate_72b_tir")) meta = {"expected_answer": row.get("expected_answer"), "teacher": row.get("generation_model"), "origin": row.get("problem_source"), "problem_type": row.get("problem_type"), "answer_extracted": extracted, "license": "cc-by-4.0"} if pass_rate is not None: meta["pass_rate"] = pass_rate return Trace(uid=f"{name}/{_content_key(problem, response)}", source=name, problem=problem, response=response, final=final, answer=answer, meta=meta, pass_rate=pass_rate) def parse_omr_plain(name: str, row: dict[str, Any]) -> Trace: """OpenMathReasoning 'cot': generated_solution is "reasoningsolution".""" reasoning, final = split_think(row.get("generated_solution") or "") response = think_response(reasoning, final) _plain(response, final) return _omr_trace(name, row, response, final) def parse_omr_tool(name: str, row: dict[str, Any]) -> Trace: """OpenMathReasoning 'tir': "...solution" where each call is \\ncode\\n (code unfenced) followed by ```output and a ```system block counting the executions left.""" solution = _SYSTEM_BLOCK.sub("", row.get("generated_solution") or "") unclosed = solution.count(TOOL_OPEN) != solution.count(TOOL_CLOSE) converted, results, issues = convert_inline_calls(solution) if not results: raise Skip("no tool call") reasoning, final = split_think(converted) response = think_response(reasoning, final) trace = _omr_trace(name, row, response, final) trace.calls = len(results) trace.issues = [*(["unclosed_call"] if unclosed else []), *issues, *call_issues(results), *check_markup(response, len(results))] return trace @dataclass(frozen=True) class TraceSource: name: str hf_id: str pattern: str kind: str parse: Callable[[str, dict[str, Any]], Trace] columns: tuple[str, ...] license: str subset: tuple[str, str] | None = None note: str = "" _NEMOTRON_COLS = ("uuid", "problem", "expected_answer", "messages", "tools", "source", "license", "url", "username") _V2_COLS = ("expected_answer", "problem", "original_expected_answer", "changed_answer_to_majority", "data_source", "messages", "metadata", "license", "tools", "url", "user_name") _OMR_COLS = ("expected_answer", "problem_type", "problem_source", "generation_model", "pass_rate_72b_tir", "problem", "generated_solution") # Earlier sources win when two traces share a problem. SOURCES = [ TraceSource("nemotron_sft_math_v4_cot", "nvidia/Nemotron-SFT-Math-v4", "data/train-*.parquet", "warmup", parse_nemotron_plain, (*_NEMOTRON_COLS, "subset"), "cc-by-4.0 (AoPS) / cc-by-sa-4.0 (StackExchange)", subset=("subset", "cot"), note="no difficulty metadata"), TraceSource("nemotron_math_v2_high", "nvidia/Nemotron-Math-v2", "data/high_part0*.parquet", "warmup", parse_nemotron_plain, _V2_COLS, "cc-by-4.0 (AoPS) / cc-by-sa-4.0 (StackExchange)", note="pass_rate = gpt-oss-120b passes / samples over all six reasoning-mode x tool settings"), TraceSource("openmathreasoning_cot", "nvidia/OpenMathReasoning", "data/cot-*.parquet", "warmup", parse_omr_plain, _OMR_COLS, "cc-by-4.0", note="pass_rate = pass_rate_72b_tir (Qwen2.5-Math-72B-Instruct TIR, out of 32)"), TraceSource("nemotron_sft_math_v4_tir", "nvidia/Nemotron-SFT-Math-v4", "data/train-*.parquet", "tool", parse_nemotron_tool, (*_NEMOTRON_COLS, "subset"), "cc-by-4.0 (AoPS) / cc-by-sa-4.0 (StackExchange)", subset=("subset", "tir"), note="no difficulty metadata"), TraceSource("openmathreasoning_tir", "nvidia/OpenMathReasoning", "data/tir-*.parquet", "tool", parse_omr_tool, _OMR_COLS, "cc-by-4.0", note="pass_rate = pass_rate_72b_tir (Qwen2.5-Math-72B-Instruct TIR, out of 32)"), ] def _excluded(stats, value: str) -> bool: if stats is None or not stats.has_min_max: return False lo, hi = (s.decode() if isinstance(s, bytes) else s for s in (stats.min, stats.max)) return value < lo or value > hi def _read_group(pf, group: int, columns: list[str], attempts: int = 4) -> list[dict[str, Any]]: for attempt in range(attempts): try: return pf.read_row_group(group, columns=columns).to_pylist() except OSError: if attempt == attempts - 1: raise time.sleep(10 * (attempt + 1)) raise AssertionError("unreachable") def read_row_groups(src: TraceSource, revision: str, seed: int) -> Iterator[tuple[str, int, list[dict[str, Any]]]]: """(file, row group, rows) of src in seeded random order. Row groups whose Parquet statistics rule out src.subset are skipped unread.""" import pyarrow.parquet as pq from huggingface_hub import HfFileSystem fs = HfFileSystem() files = sorted(fs.glob(f"datasets/{src.hf_id}@{revision}/{src.pattern}")) if not files: raise FileNotFoundError(f"{src.hf_id}@{revision}: no files match {src.pattern}") rng = random.Random(f"{seed}/{src.name}") remaining: dict[str, list[int]] = {} handles: dict[str, Any] = {} raw: list[Any] = [] try: while files: path = rng.choice(files) if path not in handles: raw.append(fs.open(path, "rb", block_size=8 << 20)) handles[path] = pq.ParquetFile(raw[-1]) md = handles[path].metadata groups = list(range(md.num_row_groups)) if src.subset: col = [md.schema.column(i).path for i in range(md.num_columns)].index(src.subset[0]) groups = [g for g in groups if not _excluded(md.row_group(g).column(col).statistics, src.subset[1])] rng.shuffle(groups) remaining[path] = groups if not remaining[path]: files.remove(path) continue group = remaining[path].pop() rows = _read_group(handles[path], group, list(src.columns)) if src.subset: rows = [r for r in rows if r.get(src.subset[0]) == src.subset[1]] yield path.rsplit("/", 1)[-1], group, rows finally: for f in raw: f.close() T = TypeVar("T") def prefetch(items: Iterator[T]) -> Iterator[T]: """Yield from items while a background thread fetches the next one, so downloads overlap grading.""" q: queue.Queue = queue.Queue(maxsize=1) done, stop = object(), threading.Event() def run() -> None: try: for x in items: if stop.is_set(): return q.put(x) q.put(done) except BaseException as e: q.put(e) finally: getattr(items, "close", lambda: None)() worker = threading.Thread(target=run, daemon=True) worker.start() try: while (x := q.get()) is not done: if isinstance(x, BaseException): raise x yield x finally: stop.set() while worker.is_alive(): try: q.get(timeout=0.1) except queue.Empty: pass def load_tokenizer(): from huggingface_hub import snapshot_download from transformers import AutoTokenizer path = snapshot_download(TOKENIZER_REPO, revision=TOKENIZER_REVISION, allow_patterns=TOKENIZER_FILES) return AutoTokenizer.from_pretrained(path) def pool_hashes() -> set[str]: """text_hash of every problem in the RL pool sources (configs/datasets.yaml, role pool).""" return {data.text_hash(data.normalize_whitespace(p.problem)) for name in data.sources("pool") for p in data.load_source(name)} def verify(traces: list[Trace], workers: int) -> tuple[list[Trace], Counter]: """Keep traces whose solution's last \\boxed{} grades correct against the extracted reference answer. References longer than data.MAX_ANSWER_CHARS are not graded, as for the RL pool (D-021).""" reasons: Counter = Counter() answered = [] for t in traces: if t.answer is None: reasons["no_extracted_answer"] += 1 elif len(t.answer) > data.MAX_ANSWER_CHARS: reasons["reference_over_64_chars"] += 1 else: answered.append(t) verdicts = grade_many([(t.final, t.answer) for t in answered], workers=workers) kept = [t for t, ok in zip(answered, verdicts, strict=True) if ok] reasons["wrong_or_no_boxed_answer"] += len(answered) - len(kept) return kept, reasons def length_filter(traces: list[Trace], kind: str, tokenizer, prof: dict[str, Any]) -> tuple[list[Trace], Counter]: """Response tokens within the kind's range, and prompt + response + end token within MAX_SEQ_LEN, counted the way sft_data.sft_rows counts them.""" reasons: Counter = Counter() if not traces: return [], reasons prompts = [] for t in traces: messages = [{"role": "user", "content": prof["user_template"].format(problem=t.prompt_text(kind))}] if prof.get("system"): messages.insert(0, {"role": "system", "content": prof["system"]}) prompts.append(tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)) prompt_lens = [len(x) for x in tokenizer(prompts, add_special_tokens=False)["input_ids"]] resp_lens = [len(x) for x in tokenizer([t.response for t in traces], add_special_tokens=False)["input_ids"]] lo, hi = WARMUP_TOKENS if kind == "warmup" else (1, TOOL_MAX_TOKENS) kept = [] for t, p, r in zip(traces, prompt_lens, resp_lens, strict=True): if r < lo: reasons["too_short"] += 1 elif r > hi: reasons["too_long"] += 1 elif p + r + 1 > MAX_SEQ_LEN: reasons["over_max_seq_len"] += 1 else: t.meta["response_tokens"] = r kept.append(t) return kept, reasons ISSUE_ORDER = ["too_many_calls", "unclosed_call", "missing_output", "stray_tool_tag", "stray_output_block", "fence_in_output", "long_output", "syntax_error", "needs_state", "mostly_errors"] def tool_filter(traces: list[Trace]) -> tuple[list[Trace], Counter]: """Drop tool traces with any format issue; each is counted once, under its first issue in ISSUE_ORDER.""" reasons: Counter = Counter() kept = [] for t in traces: if t.issues: reasons[min(t.issues, key=ISSUE_ORDER.index)] += 1 else: t.meta["tool_calls"] = t.calls kept.append(t) return kept, reasons def dedup_traces(traces: list[Trace]) -> list[Trace]: """First trace of each problem (data.text_hash); callers order traces by source priority.""" seen: set[str] = set() kept = [] for t in traces: h = data.text_hash(t.problem) if h not in seen: seen.add(h) kept.append(t) return kept def decontaminate_traces(traces: list[Trace], dev: list[Problem]) -> tuple[list[Trace], list[dict]]: """Drop every trace whose problem has an n-gram hit on a dev problem (decontam.ngram_candidates).""" rows = ngram_candidates([Problem(uid=t.uid, source=t.source, problem=t.problem, answer=t.answer or "") for t in traces], dev) hit = {r["pool_uid"] for r in rows} return [t for t in traces if t.uid not in hit], rows def quotas(available: dict[str, int], n: int) -> dict[str, int]: """Split n as evenly as possible across sources; a source's unused share goes to the others.""" q = dict.fromkeys(available, 0) remaining = min(n, sum(available.values())) open_ = sorted(s for s in available if available[s] > 0) while remaining > 0 and open_: share, extra = divmod(remaining, len(open_)) for i, s in enumerate(open_): take = min(available[s] - q[s], share + (i < extra)) q[s] += take remaining -= take open_ = [s for s in open_ if q[s] < available[s]] return q def hardness_weight(t: Trace) -> float: return HARD_FLOOR + 1.0 - (t.pass_rate if t.pass_rate is not None else 0.5) def weighted_sample(traces: list[Trace], k: int, seed: int) -> list[Trace]: """k traces without replacement, each drawn with probability proportional to hardness_weight (Efraimidis-Spirakis keys), so unsolved problems are 5x likelier than always-solved ones but not taken wholesale: references of never-solved problems are wrong more often.""" rng = random.Random(seed) ordered = sorted(traces, key=lambda t: t.uid) keyed = [(rng.random() ** (1.0 / hardness_weight(t)), t.uid, t) for t in ordered] keyed.sort(key=lambda x: (-x[0], x[1])) return [t for _, _, t in keyed[:k]] def select(traces: list[Trace], n: int, seed: int) -> list[Trace]: """n traces balanced across sources (quotas), hard problems preferred within each source.""" by_source: dict[str, list[Trace]] = defaultdict(list) for t in traces: by_source[t.source].append(t) q = quotas({s: len(ts) for s, ts in by_source.items()}, n) chosen = [t for s in sorted(by_source) for t in weighted_sample(by_source[s], q[s], seed)] return sorted(chosen, key=lambda t: t.uid) STAGES = {"warmup": ["parsed", "verified", "length", "unique", "not_in_rl_pool", "decontaminated", "selected"], "tool": ["parsed", "verified", "length", "tool_format", "unique", "not_in_rl_pool", "decontaminated", "selected"]} @dataclass class Collected: traces: list[Trace] stages: dict[str, int] reasons: dict[str, dict[str, int]] rows_read: int row_groups: list[list[Any]] new_problems: int def collect(src: TraceSource, revision: str, goal: int, max_rows: int, tokenizer, prof: dict[str, Any], seed: int, workers: int, log: Callable[[str], None], covered: set[str] | None = None) -> Collected: """Read row groups of one source until `goal` traces pass the per-trace filters (parse, answer, length, tool format) with a problem whose text_hash is not in `covered`, or until `max_rows` rows have been read. `covered` holds earlier sources' problems and the RL pool, and is updated in place, so the goal counts traces that survive dedup.""" covered = set() if covered is None else covered stage_names = STAGES[src.kind][: 4 if src.kind == "tool" else 3] stages: Counter = Counter() reasons: dict[str, Counter] = defaultdict(Counter) kept: list[Trace] = [] seen: set[str] = set() new_problems = 0 rows_read = 0 groups: list[list[Any]] = [] for fname, group, rows in prefetch(read_row_groups(src, revision, seed)): rows_read += len(rows) groups.append([fname, group]) batch = [] for row in rows: try: t = src.parse(src.name, row) except Skip as e: reasons["parsed"][str(e)] += 1 continue if t.uid in seen: reasons["parsed"]["duplicate row"] += 1 continue seen.add(t.uid) batch.append(t) stages["parsed"] += len(batch) steps = [("verified", lambda b: verify(b, workers)), ("length", lambda b: length_filter(b, src.kind, tokenizer, prof))] if src.kind == "tool": steps.append(("tool_format", tool_filter)) for stage, step in steps: batch, why = step(batch) stages[stage] += len(batch) reasons[stage].update(why) kept += batch for t in batch: h = data.text_hash(t.problem) if h not in covered: covered.add(h) new_problems += 1 log(f" {src.name}: {fname} rg {group}: {len(rows)} rows, {len(batch)} kept " f"({new_problems}/{goal} new problems, {rows_read} rows read)") if new_problems >= goal or rows_read >= max_rows: break return Collected(kept, {s: stages[s] for s in stage_names}, {s: dict(reasons[s]) for s in stage_names if reasons[s]}, rows_read, groups, new_problems) def _by_source(traces: list[Trace]) -> dict[str, int]: return dict(Counter(t.source for t in traces)) def build(out: Path, warmup: int = 20000, tool: int = 10000, seed: int = 0, oversample: float = 1.5, max_rows: int = 200_000, drop_pool: bool = True, workers: int = 4, log: Callable[[str], None] = print) -> dict[str, Any]: targets = {"warmup": warmup, "tool": tool} prof = profile(PROFILE) tokenizer = load_tokenizer() log("loading the dev set") dev = data.build_dev() pool = pool_hashes() if drop_pool else set() log(f"dev: {len(dev)} problems; RL pool: {len(pool)} problem hashes") revisions = {src.hf_id: data.revision(src.hf_id) for src in SOURCES} source_info: dict[str, Any] = {} stages: dict[str, dict[str, dict[str, int]]] = {k: defaultdict(dict) for k in KINDS} reasons: dict[str, dict[str, dict[str, Any]]] = {k: defaultdict(dict) for k in KINDS} files: dict[str, Any] = {} decontam_rows: dict[str, list[dict]] = {} for kind in KINDS: srcs = [s for s in SOURCES if s.kind == kind] traces: list[Trace] = [] covered = set(pool) remaining = float(targets[kind]) for i, src in enumerate(srcs): # A source that runs out of rows passes the rest of its share to the sources after it. share = remaining / (len(srcs) - i) goal = math.ceil(oversample * share) log(f"{kind}: reading {src.name} ({src.hf_id}@{revisions[src.hf_id][:10]}), goal {goal}") got = collect(src, revisions[src.hf_id], goal, max_rows, tokenizer, prof, seed, workers, log, covered) remaining -= min(got.new_problems, share) traces += got.traces for stage, n in got.stages.items(): stages[kind][stage][src.name] = n for stage, why in got.reasons.items(): reasons[kind][stage][src.name] = why source_info[src.name] = {"hf_id": src.hf_id, "revision": revisions[src.hf_id], "files": src.pattern, "subset": dict([src.subset]) if src.subset else None, "kind": kind, "license": src.license, "note": src.note, "goal_new_problems": goal, "rows_read": got.rows_read, "row_groups_read": got.row_groups} unique = dedup_traces(traces) fresh = [t for t in unique if data.text_hash(t.problem) not in pool] clean, rows = decontaminate_traces(fresh, dev) chosen = select(clean, targets[kind], seed) for stage, ts in (("unique", unique), ("not_in_rl_pool", fresh), ("decontaminated", clean), ("selected", chosen)): stages[kind][stage] = _by_source(ts) decontam_rows[kind] = rows name = FILES[kind] write_jsonl(out / name, (t.row(kind) for t in chosen)) files[name] = {"rows": len(chosen), "sha256": sha256_file(out / name), "rows_by_source": _by_source(chosen), "target": targets[kind]} log(f"{kind}: wrote {len(chosen)} rows to {out / name}") manifest = { "built_at": datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds"), "seed": seed, "tokenizer": {"hub": TOKENIZER_REPO, "revision": TOKENIZER_REVISION, "files": TOKENIZER_FILES}, "format": {"response": "\\n{reasoning}\\n\\n\\n{solution}", "tool_call": "\\n{code}\\n\\n```output\\n{stdout}\\n```\\n", "tool_prompt": "problem + '\\n\\n' + evaluate.TOOL_NOTE (meta.problem keeps the bare problem)", "tool_note": TOOL_NOTE}, "sources": source_info, "skipped_sources": {hf_id: info | {"revision": data.revision(hf_id)} for hf_id, info in SKIPPED.items()}, "differences_from_plan": DIFFERENCES_FROM_PLAN, "filters": { "1_parse": "problem, response and reference answer from each source's own layout; rows that do not fit " "it are counted under parsed reasons", "2_verified": "the solution's last \\boxed{} grades correct (grading.grade_many) against the reference " "answer. Only extracted references count: Nemotron-Math-v2 rows with " "changed_answer_to_majority or no original_expected_answer, and OpenMathReasoning rows " "whose problem_type is not has_answer_extracted, have none and are dropped.", "3_length": {"tokenizer": f"{TOKENIZER_REPO}@{TOKENIZER_REVISION}", "warmup_response_tokens": WARMUP_TOKENS, "tool_response_tokens": [1, TOOL_MAX_TOKENS], "max_seq_len": MAX_SEQ_LEN, "counted": "prompt via the chat template (with TOOL_NOTE for tool rows) + response + <|im_end|>"}, "4_tool_format": {"calls": [1, MAX_CALLS], "max_output_chars": MAX_OUTPUT_CHARS, "mostly_errors": "more than half the outputs show a traceback or an Error line", "issues": ISSUE_ORDER}, "5_dedup": "data.text_hash of the problem, first source in SOURCES order wins; then problems whose " "text_hash is in the RL pool sources (configs/datasets.yaml role pool) are dropped" if drop_pool else "data.text_hash of the problem, first source in SOURCES order wins", "6_decontam": "decontam.ngram_candidates (13-grams) against data.build_dev(); every hit dropped. " "No embedding pass was run.", "7_select": f"quotas split evenly across sources (unused shares go to the others); within a source, " f"weighted sampling without replacement with weight {HARD_FLOOR} + 1 - pass_rate " f"(0.5 when unknown), seed {seed}", "reading": f"each source is read until {oversample} x its share of the target passes filters 1-4 with a " "problem not already covered by an earlier source or the RL pool, or until max_rows rows; " "a source that stops short passes the rest of its share to the next", "oversample": oversample, "max_rows_per_source": max_rows, }, "stages": {k: {s: stages[k][s] for s in STAGES[k]} for k in KINDS}, "drop_reasons": {k: dict(reasons[k]) for k in KINDS}, "decontam": {"evals": "dev", "dev_problems": len(dev), "hits": decontam_rows, "rl_pool_hashes": len(pool) if drop_pool else None}, "files": files, } write_json(out / "manifest.json", manifest) return manifest def main(argv: list[str] | None = None) -> None: parser = argparse.ArgumentParser(prog="python -m pocket_math.traces") sub = parser.add_subparsers(dest="command", required=True) b = sub.add_parser("build", help="sample, filter and write the warm-up and tool trace sets") b.add_argument("--out", type=Path, default=Path("data_out/sft")) b.add_argument("--warmup", type=int, default=20000, help="warm-up traces to write") b.add_argument("--tool", type=int, default=10000, help="tool traces to write") b.add_argument("--seed", type=int, default=0) b.add_argument("--oversample", type=float, default=1.5, help="read each source until this many times its share passes the per-trace filters") b.add_argument("--max-rows", type=int, default=200_000, help="stop reading a source after this many rows") b.add_argument("--keep-pool-problems", action="store_true", help="do not drop problems that are in the RL pool") b.add_argument("--workers", type=int, default=min(8, os.cpu_count() or 1), help="grading processes") args = parser.parse_args(argv) manifest = build(args.out, args.warmup, args.tool, args.seed, args.oversample, args.max_rows, not args.keep_pool_problems, args.workers, log=lambda s: print(s, flush=True)) for name, info in manifest["files"].items(): print(f"{name:14} {info['rows']:>6} {info['sha256']}") if __name__ == "__main__": main()