greendesk1631's picture
Release Tamarillo Prompt Complexity Router (Apache-2.0, Stage 2 PASS)
5118ad4 verified
Raw History Blame Contribute Delete
27.6 kB
"""Build Clean v2 Multilingual + 2025/2026 Real-World Prompt Complexity & Routing Corpus + Frozen Eval Suites
for Family #9: Tamarillo/prompt-complexity-router.
100% Commercially Permissive Sources (CC-BY-4.0 / Apache-2.0 / MIT / CC0-1.0).
Fixes ALL Step 1 findings:
1. Drops HelpSteer/HelpSteer2 (rates assistant *response* lexical complexity, not prompt difficulty).
2. Uses lmarena-ai/arena-human-preference-140k (CC-BY-4.0, 2025 real multilingual user prompts with
official LMSYS 7-criteria Arena-Hard complexity rubric `criteria_v0.1` 0..7) as primary balanced core!
3. Balances arena-55k & routellm/gpt4_judge_battles STRICTLY 1:1:1 per source (ZERO FLAN/Arena confounding!).
4. Fixes FiscalNote/billsum long-simple anchors by slicing long bills to 1,400-3,200 chars -> exact 2,000 vs 2,000!
5. Adds AutoBench/router-benchmark-2026-10 (CC-BY-4.0, Oct 2026, 252 questions x 20 real 2026 LLMs) as
100% zero-touch OOD 2026 Cost-Quality Routing Suite!
"""
from __future__ import annotations
import argparse
import csv
import hashlib
import io
import json
import os
import random
import re
import urllib.request
from collections import defaultdict
from pathlib import Path
from typing import Any
from datasets import load_dataset
STRONG_MODELS_55K = {
"gpt-4-1106-preview", "gpt-4-0125-preview", "gpt-4-0613", "gpt-4-0314", "gpt-4-turbo-2024-04-09",
"claude-3-opus-20240229", "claude-3-sonnet-20240229", "claude-2.1", "claude-2.0", "claude-v1",
"gemini-1.5-pro-api-0409-preview", "gpt-4",
}
WEAK_MODELS_55K = {
"mixtral-8x7b-instruct-v0.1", "mistral-7b-instruct", "mistral-7b-instruct-v0.2",
"llama-2-7b-chat", "llama-2-13b-chat", "llama-13b", "alpaca-13b", "vicuna-7b", "vicuna-13b",
"vicuna-33b", "gpt-3.5-turbo-0613", "gpt-3.5-turbo-0301", "gpt-3.5-turbo-0125", "gpt-3.5-turbo-1106",
"gpt-3.5-turbo", "claude-3-haiku-20240307", "claude-instant-1", "gemini-pro", "gemma-7b-it",
"gemma-2b-it", "qwen1.5-7b-chat", "qwen1.5-14b-chat", "zephyr-7b-beta", "openchat-3.5",
"starling-lm-7b-alpha", "koala-13b", "oasst-pythia-12b", "fastchat-t5-3b", "chatglm-6b",
"chatglm2-6b", "chatglm3-6b", "dolly-v2-12b", "mpt-7b-chat", "palm-2",
}
AUTOBENCH_FRONTIER_2026 = {"Claude-sonnet-5", "Gpt-5.6-sol", "Qwen3.8-max", "Grok-4.6", "GLM-5.3", "Grok-4.3"}
AUTOBENCH_FAST_2026 = {"Qwen3.5-9b", "Deepseek-v4-flash-0731", "Nemotron-3.5-lightning", "Gpt-oss-120b", "Gemma-4-31b-it"}
PREFIX_TEMPLATES = [
[
("User", "Hi! Can you confirm our workspace session is active?"),
("Assistant", "Yes, the session is active and ready. Let me know what you need help with."),
("User", "We already archived last week's sprint summary and agreed to use ISO dates."),
("Assistant", "Understood — I've noted the archived summary and ISO date format."),
],
[
("System", "Session initialized for project_id=ops-notes. Previous draft saved at revision 4."),
("User", "Before my next request, please keep formatting concise and avoid extra preambles."),
("Assistant", "Confirmed. I will respond directly and concisely to your next request."),
("User", "Also, ignore the old scratchpad from Tuesday; we are starting fresh."),
("Assistant", "Noted. Ready whenever you are."),
],
[
("User", "Tool status check: calendar sync completed with 0 conflicts."),
("Assistant", "Great — calendar sync looks clean. What would you like to do next?"),
("User", "I am reviewing several unrelated tickets today, so treat each new question independently."),
("Assistant", "Will do — I will evaluate each upcoming request on its own."),
],
]
def norm_hash(text: str) -> str:
norm = " ".join(str(text or "").lower().split())[:600]
return hashlib.sha256(norm.encode("utf-8", errors="ignore")).hexdigest()[:20]
def parse_prompt_field(raw: Any) -> str:
if isinstance(raw, list):
return "\n".join(str(x) for x in raw if x).strip()
s = str(raw or "").strip()
if s.startswith("[") and s.endswith("]"):
try:
arr = json.loads(s)
if isinstance(arr, list):
return "\n".join(str(x) for x in arr if x).strip()
except Exception:
pass
return s
def extract_arena140k_prompt(conv_a: Any) -> str:
if not isinstance(conv_a, list):
return ""
user_parts = []
for turn in conv_a:
if not isinstance(turn, dict) or turn.get("role") != "user":
continue
content = turn.get("content")
if isinstance(content, str):
if content.strip():
user_parts.append(content.strip())
elif isinstance(content, list):
txts = []
for blk in content:
if isinstance(blk, dict) and blk.get("type") == "text" and blk.get("text"):
txts.append(str(blk["text"]).strip())
if txts:
user_parts.append("\n".join(txts))
return "\n\n".join(user_parts).strip()
def parse_arena140k_criteria(cat_raw: Any) -> tuple[int, dict[str, bool], int]:
if isinstance(cat_raw, str):
try:
cat = json.loads(cat_raw)
except Exception:
return -1, {}, 0
elif isinstance(cat_raw, dict):
cat = cat_raw
else:
return -1, {}, 0
crit = cat.get("criteria_v0.1")
if not isinstance(crit, dict) or not crit:
return -1, {}, 0
c_bool = {k: bool(v) for k, v in crit.items()}
c_sum = sum(1 for v in c_bool.values() if v)
if_score = 0
if isinstance(cat.get("if_v0.1"), dict):
try:
if_score = int(cat["if_v0.1"].get("score") or 0)
except Exception:
if_score = 0
return c_sum, c_bool, if_score
def make_multiturn_prefix(target_chars: int, rng: random.Random) -> str:
tpl = PREFIX_TEMPLATES[rng.randrange(len(PREFIX_TEMPLATES))]
parts, tot, k = [], 0, 0
while tot < target_chars:
role, msg = tpl[k % len(tpl)]
line = f"{role}: {msg} [turn={k+1}, ref=s-{rng.randint(100,999)}]"
parts.append(line)
tot += len(line) + 1
k += 1
return "\n".join(parts) + "\nUser: "
def write_jsonl(path: Path, rows: list[dict[str, Any]]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("w", encoding="utf-8") as f:
for r in rows:
f.write(json.dumps(r, ensure_ascii=False) + "\n")
def fetch_csv_url(url: str) -> list[dict[str, str]]:
req = urllib.request.Request(url, headers={"User-Agent": "tamarillo-eval/1.0"})
with urllib.request.urlopen(req, timeout=30) as r:
txt = r.read().decode("utf-8", errors="ignore")
return list(csv.DictReader(io.StringIO(txt)))
def build_autobench_2026() -> list[dict[str, Any]]:
q_rows = fetch_csv_url("https://huggingface.co/datasets/AutoBench/router-benchmark-2026-10/raw/main/questions.csv")
m_rows = fetch_csv_url("https://huggingface.co/datasets/AutoBench/router-benchmark-2026-10/raw/main/matrix.csv")
by_pid: dict[str, dict[str, tuple[float, float]]] = defaultdict(dict)
for r in m_rows:
pid, m = r.get("prompt_id", ""), r.get("model", "")
try:
sc = float(r["score"])
co = float(r["cost"])
except Exception:
continue
if pid and m:
by_pid[pid][m] = (sc, co)
out = []
gaps = []
for qr in q_rows:
pid = qr.get("prompt_id", "")
qtxt = str(qr.get("question") or "").strip()
cells = by_pid.get(pid, {})
f_vals = [cells[m] for m in AUTOBENCH_FRONTIER_2026 if m in cells]
w_vals = [cells[m] for m in AUTOBENCH_FAST_2026 if m in cells]
if not qtxt or not f_vals or not w_vals:
continue
f_score = sum(x[0] for x in f_vals) / len(f_vals)
w_score = sum(x[0] for x in w_vals) / len(w_vals)
f_cost = sum(x[1] for x in f_vals) / len(f_vals)
w_cost = sum(x[1] for x in w_vals) / len(w_vals)
gap = f_score - w_score
gaps.append(gap)
out.append({
"text": qtxt,
"prompt_id": pid,
"domain": qr.get("ddc_domain", ""),
"skill": qr.get("intended_skill", ""),
"difficulty_tag": qr.get("difficulty", ""),
"strong_score": round(f_score, 4),
"weak_score": round(w_score, 4),
"strong_cost": round(f_cost, 6),
"weak_cost": round(w_cost, 6),
"quality_gap": round(gap, 4),
"source": "autobench_2026_10",
})
med_gap = sorted(gaps)[len(gaps) // 2]
for r in out:
r["label"] = 0 if r["quality_gap"] >= med_gap else 2
return out
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--out-dir", type=str, required=True)
args = parser.parse_args()
os.environ["HF_HOME"] = "/tmp/hf"
rng = random.Random(2026)
out_dir = Path(args.out_dir)
eval_dir = out_dir / "eval_suites"
eval_dir.mkdir(parents=True, exist_ok=True)
held_out_hashes: set[str] = set()
# =========================================================================
# PART 1: BUILD & FREEZE 4 ZERO-TOUCH PUBLIC OOD SUITES FIRST!
# =========================================================================
# OOD 1: 100% Dataset-Disjoint Length-Inverted Complexity (n=1,200)
print("[ood1] Building ood_length_inverted (n=1,200)...", flush=True)
frames_p = [str(r["Prompt"]).strip() for r in load_dataset("google/frames-benchmark", split="test") if str(r.get("Prompt", "")).strip()]
gsm_p = [str(r["question"]).strip() for r in load_dataset("openai/gsm8k", "main", split="test") if str(r.get("question", "")).strip()]
he_p = []
for lang in ("python", "js", "java", "go", "cpp", "rust"):
for r in load_dataset("bigcode/humanevalpack", lang, split="test"):
he_p.append(f"Implement the following {lang} function accurately handling all edge cases:\n\n{r['prompt']}".strip())
sqa_p = [str(r["problem"]).strip() for r in load_dataset("basicv8vc/SimpleQA", split="test") if str(r.get("problem", "")).strip()]
cnn_p = []
for r in load_dataset("abisee/cnn_dailymail", "3.0.0", split="test", streaming=True):
if len(cnn_p) >= 600:
break
art = str(r.get("article") or "").strip()
if 1200 <= len(art) <= 3200:
cnn_p.append(f"Summarize the following news article in two brief sentences:\n\n{art}")
for lst in (frames_p, gsm_p, he_p, sqa_p, cnn_p):
rng.shuffle(lst)
len_inv = (
[{"text": p, "label": 0, "source": "frames"} for p in frames_p[:200]]
+ [{"text": p, "label": 0, "source": "gsm8k_test"} for p in gsm_p[:200]]
+ [{"text": p, "label": 0, "source": "humanevalpack"} for p in he_p[:200]]
+ [{"text": p, "label": 2, "source": "simpleqa"} for p in sqa_p[:200]]
+ [{"text": p, "label": 2, "source": "cnn_dm_summarize"} for p in cnn_p[:400]]
)
for r in len_inv:
held_out_hashes.add(norm_hash(r["text"]))
rng.shuffle(len_inv)
write_jsonl(eval_dir / "ood_length_inverted.jsonl", len_inv)
print(f" ood_length_inverted: n={len(len_inv)}", flush=True)
# OOD 2: AutoBench Router Benchmark 2026-10 (CC-BY-4.0, real 2026 frontier vs fast models!)
print("[ood2] Building ood_autobench_2026 from AutoBench/router-benchmark-2026-10...", flush=True)
ab_rows = build_autobench_2026()
for r in ab_rows:
held_out_hashes.add(norm_hash(r["text"]))
write_jsonl(eval_dir / "ood_autobench_2026.jsonl", ab_rows)
print(f" ood_autobench_2026: n={len(ab_rows)} (mean strong={sum(r['strong_score'] for r in ab_rows)/len(ab_rows):.2f} vs weak={sum(r['weak_score'] for r in ab_rows)/len(ab_rows):.2f})", flush=True)
# OOD 3: 2,048-Token Multi-Turn Agent Context Stress Test (n=300, 100% dataset-disjoint)
print("[ood3] Building ood_long_multiturn_2k (n=300)...", flush=True)
lt_pos = (frames_p[200:250] + gsm_p[200:250] + he_p[200:250])[:150]
lt_neg = sqa_p[200:350][:150]
lt_rows = []
for p in lt_pos:
held_out_hashes.add(norm_hash(p))
lt_rows.append({"text": make_multiturn_prefix(rng.randint(4800, 6200), rng) + p, "label": 0, "source": "long_multiturn_complex"})
for p in lt_neg:
held_out_hashes.add(norm_hash(p))
lt_rows.append({"text": make_multiturn_prefix(rng.randint(4800, 6200), rng) + p, "label": 2, "source": "long_multiturn_simple"})
rng.shuffle(lt_rows)
write_jsonl(eval_dir / "ood_long_multiturn_2k.jsonl", lt_rows)
print(f" ood_long_multiturn_2k: n={len(lt_rows)}", flush=True)
# OOD 4: Multilingual Complexity (MGSM test vs Aya Eval, LENGTH-MATCHED subset so length-heuristic ~0.50!)
print("[ood4] Building length-matched ood_multilingual_mgsm_aya (n=400)...", flush=True)
mgsm_rows, aya_rows = [], []
for lang in ("es", "fr", "de", "ru", "zh", "ja", "th", "sw", "bn", "te"):
for r in load_dataset("juletxara/mgsm", lang, split="test"):
q = str(r.get("question") or "").strip()
if 50 <= len(q) <= 450:
mgsm_rows.append({"text": q, "label": 0, "lang": lang, "source": "mgsm_test"})
for r in load_dataset("CohereLabs/aya_evaluation_suite", "aya_human_annotated", split="test"):
lg = str(r.get("language") or "").lower()
inp = str(r.get("inputs") or "").strip()
if lg not in ("eng", "en", "english") and 50 <= len(inp) <= 450:
if not re.search(r"\b(code|python|sql|algorithm|prove|integral|derivative|equation)\b", inp, re.I):
aya_rows.append({"text": inp, "label": 2, "lang": lg, "source": "aya_eval"})
# Pair by closest character length so length shortcut is ~0.50!
mgsm_rows.sort(key=lambda r: len(r["text"]))
aya_rows.sort(key=lambda r: len(r["text"]))
rng.shuffle(mgsm_rows)
rng.shuffle(aya_rows)
# Match lengths greedily within +/- 40 chars
used_a = set()
ml_pos, ml_neg = [], []
for mr in mgsm_rows:
if len(ml_pos) >= 200:
break
best_j, best_d = -1, 9999
mlen = len(mr["text"])
for j, ar in enumerate(aya_rows):
if j in used_a:
continue
d = abs(len(ar["text"]) - mlen)
if d < best_d:
best_d, best_j = d, j
if d <= 5:
break
if best_j >= 0 and best_d <= 80:
used_a.add(best_j)
ml_pos.append(mr)
ml_neg.append(aya_rows[best_j])
ml_suite = ml_pos + ml_neg
for r in ml_suite:
held_out_hashes.add(norm_hash(r["text"]))
rng.shuffle(ml_suite)
write_jsonl(eval_dir / "ood_multilingual_mgsm_aya.jsonl", ml_suite)
print(f" ood_multilingual_mgsm_aya: n={len(ml_suite)} (med chars: pos={sorted(len(r['text']) for r in ml_pos)[len(ml_pos)//2]}, neg={sorted(len(r['text']) for r in ml_neg)[len(ml_neg)//2]})", flush=True)
# =========================================================================
# PART 2: ARENA-140K (2025 MULTILINGUAL REAL PROMPTS WITH 7-CRITERIA DIFFICULTY!)
# =========================================================================
print("\n[arena140k] Streaming lmarena-ai/arena-human-preference-140k (CC-BY-4.0)...", flush=True)
a140_en_bins: dict[int, list[dict[str, Any]]] = defaultdict(list)
a140_ml_bins: dict[int, list[dict[str, Any]]] = defaultdict(list)
seen_a140: set[str] = set()
ds140 = load_dataset("lmarena-ai/arena-human-preference-140k", split="train", streaming=True)
for idx, r in enumerate(ds140):
# Collect plenty of balanced EN & non-EN rows
if all(len(a140_en_bins[c]) >= 12000 for c in (0, 1, 2)) and all(len(a140_ml_bins[c]) >= 7000 for c in (0, 1, 2)):
break
prompt = extract_arena140k_prompt(r.get("conversation_a"))
if len(prompt) < 15 or len(prompt) > 6000:
continue
h = norm_hash(prompt)
if h in held_out_hashes or h in seen_a140:
continue
c_sum, c_bool, if_score = parse_arena140k_criteria(r.get("category_tag"))
if c_sum < 0:
continue
lang = str(r.get("language") or "en").lower()
# Official LMSYS Arena-Hard 7-criteria ordinal mapping:
# 0 = STRONG_MODEL_NEEDED: c_sum >= 6 OR (c_sum == 5 and complexity and problem_solving)
# 1 = MODERATE_TIE: c_sum in {3, 4} or other c_sum == 5
# 2 = WEAK_MODEL_SUFFICIENT: c_sum <= 2
if c_sum >= 6 or (c_sum == 5 and c_bool.get("complexity") and c_bool.get("problem_solving")):
lbl = 0
soft = [0.94, 0.05, 0.01] if c_sum == 7 else [0.88, 0.10, 0.02]
elif c_sum <= 2:
lbl = 2
soft = [0.01, 0.05, 0.94] if c_sum <= 1 else [0.02, 0.10, 0.88]
else:
lbl = 1
soft = [0.22, 0.66, 0.12] if c_sum >= 4 else [0.12, 0.66, 0.22]
rec = {
"text": prompt,
"label": lbl,
"soft_target": soft,
"weight": 1.0,
"criteria_sum": c_sum,
"lang": lang,
"hash": h,
"source": "arena_140k_en" if lang == "en" else "arena_140k_non_en",
}
seen_a140.add(h)
if lang == "en":
if len(a140_en_bins[lbl]) < 12000:
a140_en_bins[lbl].append(rec)
else:
if len(a140_ml_bins[lbl]) < 7000:
a140_ml_bins[lbl].append(rec)
print(" arena140k EN counts:", {k: len(v) for k, v in a140_en_bins.items()}, flush=True)
print(" arena140k non-EN counts:", {k: len(v) for k, v in a140_ml_bins.items()}, flush=True)
# Hold out STRICTLY BALANCED held-out test suites FIRST (2,400 EN + 1,800 non-EN)!
ho_en, ho_ml = [], []
tr_a140_en, tr_a140_ml = [], []
for c in (0, 1, 2):
rng.shuffle(a140_en_bins[c])
rng.shuffle(a140_ml_bins[c])
ho_en.extend(a140_en_bins[c][:800])
tr_a140_en.extend(a140_en_bins[c][800:10800]) # up to 10,000 per class
n_ml_ho = min(600, len(a140_ml_bins[c]) // 4)
ho_ml.extend(a140_ml_bins[c][:n_ml_ho])
tr_a140_ml.extend(a140_ml_bins[c][n_ml_ho : n_ml_ho + 6000])
for r in ho_en + ho_ml:
held_out_hashes.add(r["hash"])
rng.shuffle(ho_en)
rng.shuffle(ho_ml)
write_jsonl(eval_dir / "heldout_arena140k_en.jsonl", ho_en)
write_jsonl(eval_dir / "heldout_arena140k_non_en.jsonl", ho_ml)
print(f" heldout_arena140k_en={len(ho_en)}, heldout_arena140k_non_en={len(ho_ml)}", flush=True)
# =========================================================================
# PART 3: ARENA-55K & ROUTELLM BATTLES (STRICTLY BALANCED 1:1:1 PER SOURCE!)
# =========================================================================
print("\n[battles] Loading arena-55k (Apache-2.0) & routellm/gpt4_judge_battles (Apache-2.0)...", flush=True)
a55_by_h: dict[str, list[dict[str, Any]]] = defaultdict(list)
for r in load_dataset("lmarena-ai/arena-human-preference-55k", split="train"):
ma, mb = str(r.get("model_a", "")), str(r.get("model_b", ""))
a_s, b_s = ma in STRONG_MODELS_55K, mb in STRONG_MODELS_55K
a_w, b_w = ma in WEAK_MODELS_55K, mb in WEAK_MODELS_55K
if not ((a_s and b_w) or (b_s and a_w)):
continue
prompt = parse_prompt_field(r.get("prompt"))
if len(prompt) < 15 or len(prompt) > 6000:
continue
h = norm_hash(prompt)
if h in held_out_hashes:
continue
if int(r.get("winner_tie", 0)) == 1:
lbl, soft = 1, [0.15, 0.70, 0.15]
elif (a_s and int(r.get("winner_model_a", 0)) == 1) or (b_s and int(r.get("winner_model_b", 0)) == 1):
lbl, soft = 0, [0.85, 0.12, 0.03]
else:
lbl, soft = 2, [0.03, 0.12, 0.85]
a55_by_h[h].append({"text": prompt, "label": lbl, "soft_target": soft, "weight": 0.65, "hash": h, "source": "arena_55k"})
a55_hashes = sorted(a55_by_h.keys())
rng.shuffle(a55_hashes)
ho_a55, tr_a55_bins = [], defaultdict(list)
for h in a55_hashes:
if len(ho_a55) < 2500:
ho_a55.extend(a55_by_h[h])
held_out_hashes.add(h)
else:
rec = a55_by_h[h][0]
tr_a55_bins[rec["label"]].append(rec)
write_jsonl(eval_dir / "heldout_arena55k_battles.jsonl", ho_a55)
min_a55 = min(len(tr_a55_bins[c]) for c in (0, 1, 2))
tr_a55 = []
for c in (0, 1, 2):
rng.shuffle(tr_a55_bins[c])
tr_a55.extend(tr_a55_bins[c][:min_a55])
print(f" heldout_arena55k_battles={len(ho_a55)}, balanced arena55k train={len(tr_a55)} ({min_a55}/class)", flush=True)
# Strictly balanced 1:1:1 routellm/gpt4_judge_battles (2,500 per class = 7,500!)
rllm_bins: dict[int, list[dict[str, Any]]] = defaultdict(list)
seen_tr = {r["hash"] for r in tr_a140_en + tr_a140_ml + tr_a55}
for r in load_dataset("routellm/gpt4_judge_battles", split="train", streaming=True):
if all(len(rllm_bins[c]) >= 2500 for c in (0, 1, 2)):
break
prompt = parse_prompt_field(r.get("prompt"))
if len(prompt) < 15 or len(prompt) > 6000:
continue
h = norm_hash(prompt)
if h in held_out_hashes or h in seen_tr:
continue
ma = str(r.get("model_a", ""))
a_s = ("gpt-4" in ma.lower()) or (ma in STRONG_MODELS_55K)
if int(r.get("winner_tie", 0)) == 1:
lbl, soft = 1, [0.15, 0.70, 0.15]
elif (a_s and int(r.get("winner_model_a", 0)) == 1) or ((not a_s) and int(r.get("winner_model_b", 0)) == 1):
lbl, soft = 0, [0.85, 0.12, 0.03]
else:
lbl, soft = 2, [0.03, 0.12, 0.85]
if len(rllm_bins[lbl]) < 2500:
seen_tr.add(h)
rllm_bins[lbl].append({"text": prompt, "label": lbl, "soft_target": soft, "weight": 0.65, "hash": h, "source": "routellm_battles"})
min_rllm = min(len(rllm_bins[c]) for c in (0, 1, 2))
tr_rllm = [r for c in (0, 1, 2) for r in rllm_bins[c][:min_rllm]]
print(f" balanced routellm_battles train={len(tr_rllm)} ({min_rllm}/class)", flush=True)
# =========================================================================
# PART 4: STRICTLY BALANCED DISJOINT ANTI-LENGTH (2,000 short complex vs 2,000 long simple!)
# =========================================================================
print("\n[anti-len] Building strictly balanced 2,000 short-complex vs 2,000 long-simple anchors...", flush=True)
short_c, long_s = [], []
for r in load_dataset("google-research-datasets/mbpp", "full", split="train"):
pr = str(r.get("text") or "").strip()
h = norm_hash(pr)
if 25 <= len(pr) <= 500 and h not in held_out_hashes and h not in seen_tr:
seen_tr.add(h)
short_c.append({"text": pr, "label": 0, "soft_target": [0.90, 0.08, 0.02], "weight": 0.80, "hash": h, "source": "mbpp_short_complex"})
for r in load_dataset("qwedsacf/competition_math", split="train"):
if len(short_c) >= 2000:
break
pr = str(r.get("problem") or "").strip()
h = norm_hash(pr)
if 30 <= len(pr) <= 550 and h not in held_out_hashes and h not in seen_tr:
seen_tr.add(h)
short_c.append({"text": pr, "label": 0, "soft_target": [0.92, 0.07, 0.01], "weight": 0.80, "hash": h, "source": "comp_math_short_complex"})
simple_wraps = [
"Summarize the following passage in two brief sentences:\n\n",
"List the main topic and key names mentioned in this text:\n\n",
"Rewrite the main point of this document in one simple paragraph:\n\n",
"Give a one-sentence TL;DR of the following passage:\n\n",
]
for r in load_dataset("FiscalNote/billsum", split="train", streaming=True):
if len(long_s) >= 2000:
break
raw_txt = " ".join(str(r.get("text") or "").split())
if len(raw_txt) < 1200:
continue
# Slice long bills cleanly to 1,400-3,000 chars on a sentence/word boundary!
target_l = rng.randint(1400, 3000)
snip = raw_txt[:target_l]
if len(raw_txt) > target_l:
cut = snip.rfind(". ")
if cut > 1000:
snip = snip[: cut + 1]
pr = simple_wraps[len(long_s) % len(simple_wraps)] + snip
h = norm_hash(pr)
if h not in held_out_hashes and h not in seen_tr:
seen_tr.add(h)
long_s.append({"text": pr, "label": 2, "soft_target": [0.02, 0.08, 0.90], "weight": 0.80, "hash": h, "source": "billsum_long_simple"})
print(f" anti-length anchors: short_complex={len(short_c)}, long_simple={len(long_s)}", flush=True)
# =========================================================================
# PART 5: SYMMETRIC 2,048-TOKEN MULTI-TURN AUGMENTATION (2,000 Class 0 vs 2,000 Class 2!)
# =========================================================================
base_pool = tr_a140_en + tr_a140_ml + tr_a55 + tr_rllm + short_c + long_s
rng.shuffle(base_pool)
# Hold out 3,000 validation rows cleanly BEFORE multi-turn aug!
val_rows = base_pool[:3000]
train_core = base_pool[3000:]
pos_mt = [r for r in train_core if r["label"] == 0 and len(r["text"]) <= 900][:2000]
neg_mt = [r for r in train_core if r["label"] == 2 and len(r["text"]) <= 900][:2000]
mt_aug = []
for r in pos_mt + neg_mt:
pref = make_multiturn_prefix(rng.randint(3600, 5800), rng)
mt_aug.append({**r, "text": pref + r["text"], "weight": 0.85, "source": "multiturn_aug"})
train_all = train_core + mt_aug
rng.shuffle(train_all)
# Also write an English-only subset for tiny-en? NO — tiny-en trains on EN+core cleanly, OR let's train tiny-en on EN rows only so its 32M English capacity isn't diluted by 18K non-EN prompts, while small & base (mmBERT) train on the FULL multilingual mix!
train_en = [r for r in train_all if r.get("lang", "en") == "en"]
val_en = [r for r in val_rows if r.get("lang", "en") == "en"]
write_jsonl(out_dir / "data_multilingual" / "train.jsonl", train_all)
write_jsonl(out_dir / "data_multilingual" / "val.jsonl", val_rows)
write_jsonl(out_dir / "data_en_only" / "train.jsonl", train_en)
write_jsonl(out_dir / "data_en_only" / "val.jsonl", val_en)
stats = {
"eval_suites": {
"ood_length_inverted": len(len_inv),
"ood_autobench_2026": len(ab_rows),
"ood_long_multiturn_2k": len(lt_rows),
"ood_multilingual_mgsm_aya": len(ml_suite),
"heldout_arena140k_en": len(ho_en),
"heldout_arena140k_non_en": len(ho_ml),
"heldout_arena55k_battles": len(ho_a55),
},
"train_multilingual": len(train_all),
"val_multilingual": len(val_rows),
"train_en_only": len(train_en),
"val_en_only": len(val_en),
"components": {
"arena140k_en": len(tr_a140_en),
"arena140k_non_en": len(tr_a140_ml),
"arena55k_balanced": len(tr_a55),
"routellm_balanced": len(tr_rllm),
"short_complex": len(short_c),
"long_simple": len(long_s),
"multiturn_aug": len(mt_aug),
},
}
(out_dir / "dataset_stats.json").write_text(json.dumps(stats, indent=2), encoding="utf-8")
print(f"\n[DONE] Clean v2 Dataset + Eval Suites Built:\n{json.dumps(stats, indent=2)}", flush=True)
if __name__ == "__main__":
main()