"""SeqRoute-1M query families. Every builder reads the raw files downloaded by scripts/seqroute/fetch_raw.py (pinned commits in manifests/raw_sources.json) and returns a list of rows with the fields task_family, source_dataset, source_id, source_split, subject, prompt, evaluator_type, payload(dict), reference(str). Payloads hold gold answers / unit tests / constraint specs; they are never shown to a model or to a router. """ from __future__ import annotations import ast import json import random import re import sys from pathlib import Path import numpy as np import pandas as pd RAW = Path("/mnt/localssd/seqroute1m/raw") sys.path.insert(0, str(Path(__file__).resolve().parents[3])) def rp(repo: str, path: str) -> Path: return RAW / repo.replace("/", "__") / path.replace("/", "__") def rd(repo: str, path: str) -> pd.DataFrame: f = rp(repo, path) if f.suffix == ".parquet": return pd.read_parquet(f) if f.suffix == ".jsonl": return pd.read_json(f, lines=True) return pd.read_json(f) def row(family, source, sid, split, prompt, evaluator, payload, subject="", reference="", group=None): return dict(task_family=family, source_dataset=source, source_id=str(sid), source_split=split, subject=subject, prompt=prompt, evaluator_type=evaluator, payload=payload, reference=reference, group_id=str(group) if group is not None else f"{source}/{sid}") import hashlib def hash_str(x) -> str: return hashlib.sha1(str(x).encode()).hexdigest()[:10] LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" MATH_INSTR = "Solve the following math problem. Think step by step, then give the final answer on the last line in the form 'Final answer: \\boxed{ANSWER}'.\n\n" MC_INSTR = "Answer the following multiple-choice question. Think step by step, then finish with a final line of the form 'Final answer: X' where X is the letter of the correct option.\n\n" HE_INSTR = ("Complete the following Python function. Reply with the complete function (including signature and any needed imports) in a single ```python code block, " "followed by nothing else.\n\n") MBPP_INSTR = "Write a Python function for the task below. Reply with the complete code (including any needed imports) in a single ```python code block, followed by nothing else.\n\n" APPS_INSTR = ("Solve the following competitive-programming problem in Python. The program reads from standard input and writes to standard output. " "Reply with the complete program in a single ```python code block, followed by nothing else.\n\n") EXACT_INSTR = "Answer the following question. Think step by step, then finish with a final line of the form 'Final answer: X' where X is your answer, with no extra words.\n\n" def mc_prompt(question: str, options: list[str]) -> str: return MC_INSTR + question.strip() + "\n\n" + "\n".join(f"{LETTERS[i]}. {o}" for i, o in enumerate(options)) def last_boxed(text: str) -> str | None: idx = text.rfind("\\boxed") i = text.find("{", idx) if idx >= 0 else -1 if i < 0: return None depth = 0 for j in range(i, len(text)): depth += (text[j] == "{") - (text[j] == "}") if depth == 0: return text[i + 1:j] return None # ========================================================================================================================================= def math_word(): out = [] for sp in ("train", "test"): d = rd("openai/gsm8k", f"main/{sp}-00000-of-00001.parquet") for i, r in d.iterrows(): g = r["answer"].split("####")[-1].strip().replace(",", "") out.append(row("math_word", "gsm8k", f"{sp}/{i}", sp, MATH_INSTR + r["question"], "math_exact", dict(answer_type="math", benchmark="gsm8k", gold=g), reference=g)) return out def math_competition(): out = [] for s in ["algebra", "counting_and_probability", "geometry", "intermediate_algebra", "number_theory", "prealgebra", "precalculus"]: for sp in ("train", "test"): d = rd("EleutherAI/hendrycks_math", f"{s}/{sp}-00000-of-00001.parquet") for i, r in d.iterrows(): g = last_boxed(r["solution"]) if g: out.append(row("math_competition", "hendrycks_math", f"{s}/{sp}/{i}", sp, MATH_INSTR + r["problem"], "math_exact", dict(answer_type="math", benchmark="math", gold=g, level=r["level"]), subject=s, reference=g)) return out STEM = {"physics", "chemistry", "biology", "engineering"} def knowledge(): d = rd("TIGER-Lab/MMLU-Pro", "data/test-00000-of-00001.parquet") out = [] for _, r in d.iterrows(): if r["category"] in STEM | {"math"}: continue opts = [o for o in r["options"] if o != "N/A"] out.append(row("knowledge", "mmlu_pro", r["question_id"], "test", mc_prompt(r["question"], opts), "mc_exact", dict(answer_type="mc", benchmark="mmlu_pro", gold=r["answer"]), subject=r["category"], reference=r["answer"])) return out def science(): out = [] d = rd("TIGER-Lab/MMLU-Pro", "data/test-00000-of-00001.parquet") for _, r in d.iterrows(): if r["category"] in STEM: opts = [o for o in r["options"] if o != "N/A"] out.append(row("science", "mmlu_pro_stem", r["question_id"], "test", mc_prompt(r["question"], opts), "mc_exact", dict(answer_type="mc", benchmark="mmlu_pro", gold=r["answer"]), subject=r["category"], reference=r["answer"])) d = rd("m-a-p/SuperGPQA", "SuperGPQA-all.jsonl") for _, r in d[d.discipline == "Science"].iterrows(): out.append(row("science", "supergpqa", r["uuid"], "train", mc_prompt(r["question"], list(r["options"])), "mc_exact", dict(answer_type="mc", benchmark="supergpqa", gold=r["answer_letter"]), subject=r["field"], reference=r["answer_letter"])) for sp in ("train", "validation", "test"): d = rd("allenai/ai2_arc", f"ARC-Challenge/{sp}-00000-of-00001.parquet") for _, r in d.iterrows(): labs, txt = list(r["choices"]["label"]), list(r["choices"]["text"]) if r["answerKey"] not in labs: continue letter = LETTERS[labs.index(r["answerKey"])] out.append(row("science", "arc_challenge", r["id"], sp, mc_prompt(r["question"], txt), "mc_exact", dict(answer_type="mc", benchmark="arc", gold=letter), subject="arc", reference=letter)) return out BBH = ["boolean_expressions", "causal_judgement", "date_understanding", "disambiguation_qa", "dyck_languages", "formal_fallacies", "geometric_shapes", "hyperbaton", "logical_deduction_five_objects", "logical_deduction_seven_objects", "logical_deduction_three_objects", "movie_recommendation", "multistep_arithmetic_two", "navigate", "object_counting", "penguins_in_a_table", "reasoning_about_colored_objects", "ruin_names", "salient_translation_error_detection", "snarks", "sports_understanding", "temporal_sequences", "tracking_shuffled_objects_five_objects", "tracking_shuffled_objects_seven_objects", "tracking_shuffled_objects_three_objects", "web_of_lies", "word_sorting"] def logic_reasoning(): out = [] for t in BBH: d = rd("lukaemon/bbh", f"{t}/test-00000-of-00001.parquet") for i, r in d.iterrows(): tgt = str(r["target"]).strip() m = re.fullmatch(r"\(([A-R])\)", tgt) gold, kind = (m.group(1), "letter") if m else (tgt, "text") out.append(row("logic_reasoning", "bbh", f"{t}/{i}", "test", EXACT_INSTR + r["input"].strip(), "exact_str", dict(gold=gold, kind=kind), subject=t, reference=gold)) for sp in ("train", "validation"): d = rd("tau/commonsense_qa", f"data/{sp}-00000-of-00001.parquet") for _, r in d.iterrows(): labs, txt = list(r["choices"]["label"]), list(r["choices"]["text"]) out.append(row("logic_reasoning", "commonsenseqa", r["id"], sp, mc_prompt(r["question"], txt), "mc_exact", dict(answer_type="mc", benchmark="csqa", gold=r["answerKey"]), subject="commonsense", reference=r["answerKey"])) return out def code_generation(): out = [] d = rd("openai/openai_humaneval", "openai_humaneval/test-00000-of-00001.parquet") for _, r in d.iterrows(): out.append(row("code_generation", "humaneval", r["task_id"], "test", f"{HE_INSTR}```python\n{r['prompt']}\n```", "unit_tests", dict(kind="humaneval", test=r["test"], entry_point=r["entry_point"], func_prompt=r["prompt"]), reference=r["canonical_solution"], group="humaneval/" + r["task_id"].split("/")[-1])) d = rd("Muennighoff/mbpp", "data/mbpp.jsonl") for _, r in d.iterrows(): tests = list(r["test_list"]) out.append(row("code_generation", "mbpp", r["task_id"], "full", f"{MBPP_INSTR}{r['text']}\nYour code must pass these tests:\n" + "\n".join(tests), "unit_tests", dict(kind="mbpp", tests=tests, imports=[r["test_setup_code"]] if r["test_setup_code"] else []), reference=r["code"], group=f"mbpp/{r['task_id']}")) d = rd("likaixin/APPS-verified", "apps_verified.json") for _, r in d.iterrows(): if r["difficulty"] not in ("introductory", "interview"): continue try: io = json.loads(r["input_output"]) except Exception: continue if io.get("fn_name") or not io.get("inputs") or len(io["inputs"]) > 20 or len(r["question"]) > 6000: continue out.append(row("code_generation", "apps", r["problem_id"], "train", APPS_INSTR + r["question"], "unit_tests", dict(kind="apps", inputs=io["inputs"], outputs=io["outputs"]), subject=r["difficulty"])) return out REPAIR_INSTR = ("The following Python function is supposed to behave as described but contains a bug. Fix the bug. Reply with the complete corrected function " "in a single ```python code block, followed by nothing else.\n\n") def code_repair_humanevalfix(): d = rd("bigcode/humanevalpack", "python/test-00000-of-00001.parquet") out = [] for _, r in d.iterrows(): buggy = r["prompt"] + r["buggy_solution"] out.append(row("code_repair", "humanevalfix", r["task_id"], "test", f"{REPAIR_INSTR}```python\n{buggy}\n```", "unit_tests", dict(kind="humaneval", test=(r["test_setup"] or "") + "\n" + r["test"], entry_point=r["entry_point"], func_prompt=r["prompt"]), subject=str(r["bug_type"]), reference=r["prompt"] + r["canonical_solution"], group="humaneval/" + r["task_id"].split("/")[-1])) return out # ---- AST mutations for MBPP-based repair (each mutant is verified to fail at least one test while the original passes all) -------------- class _Mut(ast.NodeTransformer): def __init__(self, target: int, kind_rng: random.Random): self.target, self.i, self.rng, self.desc = target, 0, kind_rng, None def _hit(self): self.i += 1 return self.i - 1 == self.target def visit_Compare(self, n): self.generic_visit(n) swap = {ast.Lt: ast.LtE, ast.LtE: ast.Lt, ast.Gt: ast.GtE, ast.GtE: ast.Gt, ast.Eq: ast.NotEq, ast.NotEq: ast.Eq} if type(n.ops[0]) in swap and self._hit(): n.ops[0] = swap[type(n.ops[0])](); self.desc = "comparison" return n def visit_BinOp(self, n): self.generic_visit(n) swap = {ast.Add: ast.Sub, ast.Sub: ast.Add, ast.Mult: ast.Add, ast.FloorDiv: ast.Mod, ast.Mod: ast.FloorDiv} if type(n.op) in swap and self._hit(): n.op = swap[type(n.op)](); self.desc = "arithmetic" return n def visit_BoolOp(self, n): self.generic_visit(n) if self._hit(): n.op = ast.Or() if isinstance(n.op, ast.And) else ast.And(); self.desc = "boolean" return n def visit_Constant(self, n): if isinstance(n.value, int) and not isinstance(n.value, bool) and self._hit(): self.desc = "constant" return ast.copy_location(ast.Constant(n.value + self.rng.choice([-1, 1])), n) return n def visit_Call(self, n): self.generic_visit(n) if isinstance(n.func, ast.Name) and n.func.id in ("min", "max", "any", "all") and self._hit(): n.func.id = {"min": "max", "max": "min", "any": "all", "all": "any"}[n.func.id]; self.desc = "builtin" return n def _count_sites(tree) -> int: m = _Mut(-1, random.Random(0)) m.visit(ast.parse(ast.unparse(tree))) return m.i def _mutate_task(args): """Worker: for one MBPP task return a verified buggy variant (original passes all tests, mutant fails at least one) or None.""" from llmroute.summ import rewardval as R k, seed = args rng = random.Random(seed * 100003 + k) d = _MBPP_DF r = d.iloc[k] code = r["code"].replace("\r\n", "\n").replace("\t", " ") tests = list(r["test_list"]) imports = [r["test_setup_code"]] if r["test_setup_code"] else [] gold = dict(kind="mbpp", tests=tests, imports=imports) try: tree = ast.parse(code) except SyntaxError: return None ns = _count_sites(tree) if ns == 0 or R.code_fraction({"qa_gold": gold}, f"```python\n{code}\n```") < 1.0: return None sites = list(range(ns)) rng.shuffle(sites) for s_ in sites[:6]: m = _Mut(s_, rng) mut = m.visit(ast.parse(code)) if m.desc is None: continue bug = ast.unparse(mut) if bug == ast.unparse(ast.parse(code)): continue if R.code_fraction({"qa_gold": gold}, f"```python\n{bug}\n```") < 1.0: p = f"{REPAIR_INSTR}Task description: {r['text']}\nThe code must pass these tests:\n" + "\n".join(tests) + f"\n\nBuggy code:\n```python\n{bug}\n```" return row("code_repair", "mbpp_mutants", f"{r['task_id']}/{s_}", "full", p, "unit_tests", gold, subject=m.desc, reference=code, group=f"mbpp/{r['task_id']}") return None _MBPP_DF = None def code_repair_mbpp(n_target: int = 1100, seed: int = 20261010, procs: int = 96): global _MBPP_DF from multiprocessing import get_context _MBPP_DF = rd("Muennighoff/mbpp", "data/mbpp.jsonl") order = list(range(len(_MBPP_DF))) random.Random(seed).shuffle(order) out = [] with get_context("fork").Pool(procs) as pool: for res in pool.imap(_mutate_task, [(k, seed) for k in order], chunksize=2): if res is not None: out.append(res) if len(out) >= n_target: pool.terminate() break return out # ========================================================================================================================================= def _summ_prompts(): from llmroute.summ import tasks as T return T.TASKS["cnndm"], T.TASKS["xsum"] def summ_news(): t, _ = _summ_prompts() out = [] for sp in ("test", "validation"): d = rd("abisee/cnn_dailymail", f"3.0.0/{sp}-00000-of-00001.parquet") for _, r in d.iterrows(): out.append(row("summ_news", "cnn_dailymail", r["id"], sp, t.prompt({"source_document": r["article"]}), "judge_summ", dict(style="cnndm", references=[r["highlights"]], source=r["article"]), reference=r["highlights"])) return out def summ_abstractive(): _, t = _summ_prompts() out = [] for sp in ("test", "validation"): d = rd("EdinburghNLP/xsum", f"data/{sp}-00000-of-00001.parquet") for _, r in d.iterrows(): out.append(row("summ_abstractive", "xsum", r["id"], sp, t.prompt({"source_document": r["document"]}), "judge_summ", dict(style="xsum", references=[r["summary"]], source=r["document"]), reference=r["summary"])) return out SIMP_INSTR = ("Simplify the following sentence so that it is easier to read and understand, while preserving its meaning and all important information. " "Output only the simplified sentence, with no preamble or notes.") def simplification(): out = [] for sp in ("test", "validation"): d = rd("facebook/asset", f"simplification/{sp}-00000-of-00001.parquet") for i, r in d.iterrows(): out.append(row("simplification", "asset", f"{sp}/{i}", sp, f"{SIMP_INSTR}\n\n=== SENTENCE ===\n{r['original']}\n\n=== SIMPLIFIED ===\n", "simplification", dict(source=r["original"], references=[str(x) for x in r["simplifications"]]), reference=str(r["simplifications"][0]))) return out LANG = {"en": "English", "de": "German", "fr": "French"} def translation(): out = [] for pair in ("de-en", "fr-en"): other = pair.split("-")[0] for sp in ("test", "validation"): d = rd("wmt/wmt14", f"{pair}/{sp}-00000-of-00001.parquet") for i, r in d.iterrows(): tr = r["translation"] if not (5 <= len(tr["en"].split()) <= 120): continue for src, tgt in ((other, "en"), ("en", other)): ins = f"Translate the following {LANG[src]} text into {LANG[tgt]}. Output only the {LANG[tgt]} translation, with no preamble or notes." out.append(row("translation", f"wmt14_{src}-{tgt}", f"{sp}/{i}", sp, f"{ins}\n\n=== INPUT ===\n{tr[src]}\n\n=== OUTPUT ===\n", "comet", dict(direction=f"{src}-{tgt}", source=tr[src], references=[tr[tgt]]), reference=tr[tgt], group=f"wmt14/{pair}/{sp}/{i}")) return out NER_INSTR = ('Extract all named entities from the sentence. Return ONLY a JSON object with the keys "PER", "ORG", "LOC", "MISC", each mapping to a list of ' 'entity strings exactly as written in the sentence (empty list if none).') ADE_INSTR = ('Extract every (drug, adverse effect) pair that the text states as caused by the drug. Return ONLY a JSON list of objects of the form ' '{"drug": "...", "effect": "..."} using the exact strings from the text.') CONLL_TAGS = ["O", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC", "B-MISC", "I-MISC"] def information_extraction(): out = [] for sp in ("test", "validation", "train"): d = rd("tomaarsen/conll2003", f"data/{sp}-00000-of-00001.parquet") for _, r in d.iterrows(): if len(r["tokens"]) < 6: continue ents = {"PER": [], "ORG": [], "LOC": [], "MISC": []} cur, ctype = [], None for tok, t in list(zip(r["tokens"], [CONLL_TAGS[x] for x in r["ner_tags"]])) + [("", "O")]: if t.startswith("B-") or t == "O" or (t.startswith("I-") and t[2:] != ctype): if cur: ents[ctype].append(" ".join(cur)) cur, ctype = ([tok], t[2:]) if t != "O" else ([], None) else: cur.append(tok) s = " ".join(r["tokens"]) out.append(row("information_extraction", "conll2003", f"{sp}/{r['id']}", sp, f"{NER_INSTR}\n\n=== SENTENCE ===\n{s}\n\n=== JSON ===\n", "extraction_f1", dict(kind="ner", gold=ents), reference=json.dumps(ents), group=f"conll/{sp}/{r['document_id']}")) d = rd("ade-benchmark-corpus/ade_corpus_v2", "Ade_corpus_v2_drug_ade_relation/train-00000-of-00001.parquet") by: dict[str, set] = {} for _, r in d.iterrows(): by.setdefault(r["text"], set()).add((r["drug"].strip(), r["effect"].strip())) for i, t in enumerate(sorted(t for t in by if 8 <= len(t.split()) <= 120)): pairs = sorted(by[t]) out.append(row("information_extraction", "ade_corpus_v2", i, "train", f"{ADE_INSTR}\n\n=== TEXT ===\n{t}\n\n=== JSON ===\n", "extraction_f1", dict(kind="ade", gold=[list(p) for p in pairs]), reference=json.dumps([dict(drug=a, effect=b) for a, b in pairs]))) return out def classification(): out = [] specs = { "ag_news": ("news article topic", ["World", "Sports", "Business", "Sci/Tech"]), "emotion": ("emotion expressed in the message", ["sadness", "joy", "love", "anger", "fear", "surprise"]), "sst5": ("sentiment of the movie-review sentence", ["very negative", "negative", "neutral", "positive", "very positive"]), "trec": ("type of answer the question asks for (ABBR=abbreviation, ENTY=entity, DESC=description, HUM=human, LOC=location, NUM=numeric)", ["ABBR", "ENTY", "DESC", "HUM", "LOC", "NUM"]), } srcs = {} for sp in ("test",): d = rd("fancyzhx/ag_news", f"data/{sp}-00000-of-00001.parquet"); srcs["ag_news"] = [(f"{sp}/{i}", r["text"], int(r["label"])) for i, r in d.iterrows()] d = pd.concat([rd("dair-ai/emotion", f"split/{sp}-00000-of-00001.parquet") for sp in ("test", "validation", "train")]).reset_index(drop=True) srcs["emotion"] = [(f"e/{i}", r["text"], int(r["label"])) for i, r in d.iterrows()] d = pd.concat([rd("SetFit/sst5", f"{sp}.jsonl") for sp in ("test", "dev", "train")]).reset_index(drop=True) srcs["sst5"] = [(f"s/{i}", r["text"], int(r["label"])) for i, r in d.iterrows()] d = pd.concat([rd("CogComp/trec", f"default/{sp}/0000.parquet") for sp in ("test", "train")]).reset_index(drop=True) srcs["trec"] = [(f"t/{i}", r["text"], int(r["coarse_label"])) for i, r in d.iterrows()] for name, (what, labels) in specs.items(): for sid, text, y in srcs[name]: if len(text.split()) < 3: continue ins = f"Classify the {what}. Choose exactly one label from: {', '.join(labels)}. Reply with only the label." out.append(row("classification", name, sid, "mixed", f"{ins}\n\n=== TEXT ===\n{text}\n\n=== LABEL ===\n", "label_exact", dict(gold=labels[y], labels=labels), reference=labels[y])) return out E2E_VALUES = {"eatType": ["coffee shop", "restaurant", "pub"], "food": ["English", "French", "Chinese", "Indian", "Italian", "Japanese", "Fast food"], "priceRange": ["cheap", "moderate", "high", "less than £20", "£20-25", "more than £30"], "customer rating": ["low", "average", "high", "1 out of 5", "3 out of 5", "5 out of 5"], "area": ["city centre", "riverside"], "familyFriendly": ["yes", "no"]} JSON_INSTR = ("Convert the restaurant description into a JSON object. Use only these keys, and include a key only if the description states it: " '"name" (free text), "eatType" (one of: coffee shop, restaurant, pub), "food" (one of: English, French, Chinese, Indian, Italian, Japanese, Fast food), ' '"priceRange" (one of: cheap, moderate, high, less than £20, £20-25, more than £30), "customer rating" (one of: low, average, high, 1 out of 5, 3 out of 5, 5 out of 5), ' '"area" (one of: city centre, riverside), "familyFriendly" (one of: yes, no), "near" (free text). Return ONLY the JSON object.') def json_generation(): out, seen = [], set() for sp in ("train", "validation", "test"): d = rd("tuetschek/e2e_nlg", f"default/{sp}/0000.parquet") for i, r in d.iterrows(): mr = r["meaning_representation"] if mr in seen: continue seen.add(mr) gold = {m.group(1): m.group(2) for m in re.finditer(r"([A-Za-z ]+)\[([^\]]*)\]", mr)} gold = {k.strip(): v for k, v in gold.items()} out.append(row("json_generation", "e2e_nlg", f"{sp}/{i}", sp, f"{JSON_INSTR}\n\n=== DESCRIPTION ===\n{r['human_reference']}\n\n=== JSON ===\n", "json_slots", dict(gold=gold), reference=json.dumps(gold))) return out def _long_prompt(ctx, q, qasper=False): note = " If the question cannot be answered from the passage, reply exactly: unanswerable." if qasper else "" return f"Answer the question based on the given passage. Only give the answer, as concisely as possible, without any explanation.{note}\n\n=== PASSAGE ===\n{ctx}\n\n=== QUESTION ===\n{q}\n\n=== ANSWER ===\n" def long_context_qa(): out, seen = [], set() for t in ["qasper", "multifieldqa_en", "hotpotqa", "2wikimqa", "musique", "narrativeqa", "qasper_e", "multifieldqa_en_e", "hotpotqa_e", "2wikimqa_e"]: f = RAW / "lb" / "data" / f"{t}.jsonl" for l in open(f): r = json.loads(l) if r["_id"] in seen: continue seen.add(r["_id"]) base = t[:-2] if t.endswith("_e") else t out.append(row("long_context_qa", f"longbench_{base}", r["_id"], "test", _long_prompt(r["context"], r["input"], base == "qasper"), "qa_f1", dict(gold=r["answers"], unanswerable_ok=base == "qasper"), reference=r["answers"][0])) return out RC_INSTR = "Read the passage and answer the question. Answer as briefly as possible (a number, date, name, or short phrase) with no explanation." def reading_comprehension(): out = [] d = rd("ucinlp/drop", "data/validation-00000-of-00001.parquet") for _, r in d.iterrows(): spans = [str(s) for s in r["answers_spans"]["spans"]] if not spans: continue out.append(row("reading_comprehension", "drop", r["query_id"], "validation", f"{RC_INSTR}\n\n=== PASSAGE ===\n{r['passage']}\n\n=== QUESTION ===\n{r['question']}\n\n=== ANSWER ===\n", "qa_f1", dict(gold=[", ".join(spans)] + (spans if len(spans) > 1 else []), unanswerable_ok=False), reference=", ".join(spans), group=f"drop/{r['section_id']}")) d = rd("rajpurkar/squad_v2", "squad_v2/validation-00000-of-00001.parquet") for _, r in d.iterrows(): ans = [str(a) for a in r["answers"]["text"]] ins = RC_INSTR + " If the passage does not contain the answer, reply exactly: unanswerable." out.append(row("reading_comprehension", "squad_v2", r["id"], "validation", f"{ins}\n\n=== PASSAGE ===\n{r['context']}\n\n=== QUESTION ===\n{r['question']}\n\n=== ANSWER ===\n", "qa_f1", dict(gold=ans, unanswerable_ok=True), reference=ans[0] if ans else "unanswerable", group="squad/" + r["title"] + "/" + str(hash_str(r["context"])))) return out def table_reasoning(): out = [] for sp in ("test", "validation", "train"): d = rd("wenhu/tab_fact", f"tab_fact/{sp}/0000.parquet") for _, r in d.iterrows(): tbl = r["table_text"] if len(tbl) > 4000: continue tbl = "\n".join(" | ".join(c.strip() for c in ln.split("#")) for ln in tbl.split("\n")) g = "True" if int(r["label"]) == 1 else "False" p = (f"Below is a table (caption: {r['table_caption']}). Decide whether the statement is true or false according to the table. Think briefly, then finish with a final line " f"'Final answer: True' or 'Final answer: False'.\n\n=== TABLE ===\n{tbl}\n\n=== STATEMENT ===\n{r['statement']}") out.append(row("table_reasoning", "tabfact", f"{sp}/{r['id']}", sp, p, "exact_str", dict(gold=g, kind="text"), reference=g, group=f"tabfact/{r['table_id']}")) return out def multilingual(): out = [] for lang in ["bn", "de", "en", "es", "fr", "ja", "ru", "sw", "te", "th", "zh"]: d = rd("juletxara/mgsm", f"{lang}/test-00000-of-00001.parquet") for i, r in d.iterrows(): g = str(int(r["answer_number"])) if float(r["answer_number"]).is_integer() else str(r["answer_number"]) out.append(row("multilingual", f"mgsm_{lang}", i, "test", MATH_INSTR + r["question"], "math_exact", dict(answer_type="math", benchmark="gsm8k", gold=g), subject=lang, reference=g)) for lang in ["ar", "bn", "de", "es", "fr", "hi", "id", "it", "ja", "ko", "pt", "sw", "yo", "zh"]: d = rd("CohereLabs/Global-MMLU-Lite", f"{lang}/test-00000-of-00001.parquet") for _, r in d.iterrows(): opts = [r["option_a"], r["option_b"], r["option_c"], r["option_d"]] out.append(row("multilingual", f"global_mmlu_lite_{lang}", r["sample_id"], "test", mc_prompt(r["question"], opts), "mc_exact", dict(answer_type="mc", benchmark="mmlu", gold=str(r["answer"]).strip().upper()), subject=lang, reference=str(r["answer"]).strip().upper())) return out