alea-runs / alea /gen_hf2.py
Akahsizrr's picture
Upload alea/gen_hf2.py with huggingface_hub
36399b5 verified
Raw History Blame
14.3 kB
"""gen_hf2: real HF datasets -> alea rows, targeting JevBench-weak skills.
Row schema (matches alea/dataset.py):
{"state": str, "questions": {qid: {"type":..., "instructions":...,
"criteria": {key: desc} | {"true":..., "false":...}}},
"targets": {qid: dist|float}, "family": str, "meta": {...}}
choice: criteria = {label_key: option_text}; target = one-hot over keys order
noul: instructions (+ true/false gloss); target = float(0/1)
Datasets (real labeled data; NO JevBench items anywhere):
clinc150 intent routing (fixes mode collapse) choice
logiqa logical reasoning MCQ choice
reclor LSAT-style logical reasoning choice
math_qa GRE-style math MCQ choice
gsm8k grade-school math -> choice over close numbers choice
drop passage + numeric answers choice
strategyqa implicit multi-hop yes/no noul
creak commonsense fact verification noul
bigbench date_understanding/logical_deduction/tracking/
web_of_lies/formal_fallacies/navigate/
temporal_sequences/disambiguation_qa choice/noul
"""
import argparse
import json
import random
from datasets import load_dataset
rng = random.Random(1234)
def choice_row(state, instructions, options_texts, correct_idx, family,
keys=None, meta=None):
"""options_texts: list of option strings; correct_idx into that list."""
n = len(options_texts)
keys = keys or ["opt_%d" % i for i in range(n)]
assert len(keys) == n and 0 <= correct_idx < n
seen, final_opts, final_keys, new_idx = {}, [], [], None
for i, t in enumerate(options_texts):
t = str(t).strip()
if not t:
t = "(empty option %d)" % i
if t in seen:
if i == correct_idx:
new_idx = seen[t]
continue
seen[t] = len(final_opts)
final_opts.append(t)
final_keys.append(keys[i])
if i == correct_idx:
new_idx = len(final_opts) - 1
if new_idx is None or len(final_opts) < 2:
return None
tgt = [0.0] * len(final_opts)
tgt[new_idx] = 1.0
return {"state": str(state)[:20000],
"questions": {"q0": {"type": "choice", "instructions": instructions,
"criteria": dict(zip(final_keys, final_opts))}},
"targets": {"q0": tgt},
"family": family, "meta": meta or {}}
def noul_row(state, instructions, is_true, family, true_gloss="",
false_gloss="", meta=None):
crit = {}
if true_gloss:
crit["true"] = true_gloss
if false_gloss:
crit["false"] = false_gloss
q = {"type": "noul", "instructions": instructions}
if crit:
q["criteria"] = crit
return {"state": str(state)[:20000],
"questions": {"q0": q},
"targets": {"q0": float(is_true)},
"family": family, "meta": meta or {}}
def gen_clinc(n, rng):
"""Intent classification with distractor intents -> kills mode collapse."""
ds = load_dataset("clinc_oos", "plus", split="train")
names = ds.features["intent"].names
out = []
idxs = list(range(len(ds)))
rng.shuffle(idxs)
for i in idxs:
if len(out) >= n:
break
r = ds[i]
true_name = names[r["intent"]].replace("_", " ")
k = rng.randint(3, 6)
others = rng.sample([x for x in names if x != names[r["intent"]]], k)
opts = [true_name] + [o.replace("_", " ") for o in others]
order = list(range(len(opts)))
rng.shuffle(order)
shuffled = [opts[j] for j in order]
ci = shuffled.index(true_name)
st = ("Customer message received by the virtual assistant:\n\n\""
+ r["text"].strip() + "\"")
row = choice_row(st, "Classify the user's intent into exactly one of "
"the listed intents.", shuffled, ci,
"hf_clinc_intent", meta={"src": "clinc150"})
if row:
out.append(row)
return out
def gen_logiqa(n, rng):
ds = None
for nm in ("jeggers/logiqa", "EleutherAI/logiqa", "lucasmccabe/logiqa"):
try:
ds = load_dataset(nm, split="train")
break
except Exception:
continue
if ds is None:
return []
out = []
for r in ds:
if len(out) >= n:
break
st = "Passage:\n%s\n\nQuestion:\n%s" % (r["context"].strip(),
r["query"].strip())
opts = [o.strip() for o in r["options"]]
row = choice_row(st, "Choose the option that is logically entailed or "
"best answers the question.", opts,
int(r["correct_option"]), "hf_logiqa",
meta={"src": "logiqa"})
if row:
out.append(row)
return out
def gen_reclor(n, rng):
ds = load_dataset("metaeval/reclor", split="train")
out = []
for r in ds:
if len(out) >= n:
break
st = "Passage:\n%s\n\nQuestion:\n%s" % (r["context"].strip(),
r["question"].strip())
opts = [o.strip() for o in r["answers"]]
row = choice_row(st, "Choose the option that best completes the "
"logical argument.", opts, int(r["label"]),
"hf_reclor", meta={"src": "reclor"})
if row:
out.append(row)
return out
def gen_mathqa(n, rng):
ds = load_dataset("allenai/math_qa", split="train", trust_remote_code=True)
out = []
letter = "abcde"
for r in ds:
if len(out) >= n:
break
opts = [o.strip() for o in r["options"].split(" , ")]
if len(opts) != 5:
continue
ci = letter.find(r["correct"])
if ci < 0:
continue
st = "Problem:\n%s" % r["Problem"].strip()
row = choice_row(st, "Solve the problem and choose the correct "
"answer.", opts, ci, "hf_mathqa",
meta={"src": "mathqa"})
if row:
out.append(row)
return out
def gen_gsm8k(n, rng):
ds = load_dataset("openai/gsm8k", "main", split="train")
out = []
fmt = lambda x: ("%g" % x)
for r in ds:
if len(out) >= n:
break
try:
ans = float(r["answer"].split("####")[-1].replace(",", "").strip())
except ValueError:
continue
cands = {ans * f for f in (0.5, 0.75, 0.9, 1.1, 1.25, 1.5, 2.0)}
cands |= {ans + d for d in (-3, -2, -1, 1, 2, 3)}
cands = [c for c in cands if abs(c - ans) > max(0.51, 0.04 * abs(ans))]
rng.shuffle(cands)
opts = [fmt(x) for x in ([ans] + cands[:3])]
order = list(range(4)); rng.shuffle(order)
shuffled = [opts[j] for j in order]
ci = shuffled.index(fmt(ans))
st = "Problem:\n%s" % r["question"].strip()
row = choice_row(st, "Solve the problem. Choose the exact final "
"answer.", shuffled, ci, "hf_gsm8k",
meta={"src": "gsm8k"})
if row:
out.append(row)
return out
def gen_drop(n, rng):
ds = load_dataset("ucinlp/drop", split="train")
out = []
for r in ds:
if len(out) >= n:
break
spans = r["answers_spans"]["spans"]
if len(spans) != 1:
continue
ans = spans[0].strip()
if not ans:
continue
try:
a = float(ans.replace(",", "").replace("$", "").replace("%", ""))
cands = {a * f for f in (0.5, 0.75, 1.25, 1.5, 2.0)} | {a + d for d in (-2, -1, 1, 2)}
cands = [c for c in cands if abs(c - a) > max(0.4, 0.03 * abs(a))]
rng.shuffle(cands)
fmt = lambda x: ("%g" % x)
opts = [fmt(x) for x in ([a] + cands[:3])]
order = list(range(4)); rng.shuffle(order)
shuffled = [opts[j] for j in order]
ci = shuffled.index(fmt(a))
st = "Passage:\n%s\n\nQuestion:\n%s" % (r["passage"][:6000],
r["question"])
row = choice_row(st, "Answer the question about the passage with "
"the correct number.", shuffled, ci, "hf_drop",
meta={"src": "drop"})
if row:
out.append(row)
except ValueError:
if ans.lower() in ("yes", "no"):
st = "Passage:\n%s\n\nQuestion:\n%s" % (r["passage"][:6000],
r["question"])
out.append(noul_row(st, "Answer yes or no based only on the "
"passage.", ans.lower() == "yes",
"hf_drop_noul", meta={"src": "drop"}))
return out
def gen_strategyqa(n, rng):
ds = None
for name in ("ChilleD/StrategyQA", "tasksource/strategy-qa"):
try:
ds = load_dataset(name, split="train")
break
except Exception:
continue
if ds is None:
return []
out = []
for r in ds:
if len(out) >= n:
break
q = r.get("question") or r.get("Question") or ""
a = r.get("answer", r.get("Answer"))
if not q or a is None:
continue
out.append(noul_row("Question: %s" % q.strip(),
"Answer yes or no. Reason about the implied "
"facts carefully.", bool(a), "hf_strategyqa",
meta={"src": "strategyqa"}))
return out
def gen_creak(n, rng):
ds = None
for name in ("amariucaitheodor/creak", "creak"):
try:
ds = load_dataset(name, split="train")
break
except Exception:
continue
if ds is None:
return []
out = []
for r in ds:
if len(out) >= n:
break
sent = r.get("sentence", "")
lab = r.get("label", "")
if not sent or lab not in ("true", "false"):
continue
out.append(noul_row("Claim: %s" % sent.strip(),
"Decide whether the claim is factually true.",
lab == "true", "hf_creak", meta={"src": "creak"}))
return out
BB_TASKS = [
("date_understanding", "choice"),
("logical_deduction", "choice"),
("tracking_shuffled_objects", "choice"),
("formal_fallacies_syllogisms_negation", "noul"),
("navigate", "noul"),
("temporal_sequences", "choice"),
("disambiguation_qa", "choice"),
("logical_fallacy_detection", "choice"),
("logic_grid_puzzle", "choice"),
("logical_sequence", "choice"),
("logical_args", "choice"),
("repeat_copy_logic", "choice"),
("chess_state_tracking", "choice"),
]
def gen_bigbench(n_per_task, rng):
out = []
for task, kind in BB_TASKS:
try:
ds = None
for sp in ("train", "validation"):
try:
ds = load_dataset("tasksource/bigbench", task, split=sp)
break
except Exception:
continue
except Exception as e:
print("bigbench skip", task, str(e)[:60])
continue
cnt = 0
idxs = list(range(len(ds)))
rng.shuffle(idxs)
for i in idxs:
if cnt >= n_per_task:
break
r = ds[i]
inp = (r.get("inputs") or r.get("input") or "").strip()
import ast as _ast
tgts = r.get("multiple_choice_targets") or []
scrs = r.get("multiple_choice_scores") or []
if isinstance(tgts, str):
try: tgts = _ast.literal_eval(tgts)
except Exception: tgts = []
if isinstance(scrs, str):
try: scrs = _ast.literal_eval(scrs)
except Exception: scrs = []
if not inp or len(tgts) < 2 or not any(scrs):
continue
ci = list(scrs).index(1)
opts = [str(o).strip() for o in tgts]
if kind == "noul" and len(opts) == 2:
yesish = [o.lower().startswith(("yes", "true", "valid",
"correct"))
for o in opts]
if sum(yesish) == 1:
out.append(noul_row(inp, "Answer yes or no.",
ci == yesish.index(True),
"hf_bb_" + task,
meta={"src": task}))
cnt += 1
continue
row = choice_row(inp, "Choose the correct answer.", opts, ci,
"hf_bb_" + task, meta={"src": task})
if row:
out.append(row)
cnt += 1
print("bb", task, cnt)
return out
GENS = {
"clinc": gen_clinc,
"logiqa": gen_logiqa,
"reclor": gen_reclor,
"gsm8k": gen_gsm8k,
"drop": gen_drop,
"strategyqa": gen_strategyqa,
"bigbench": gen_bigbench,
}
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--out", default="data/hf2.jsonl")
ap.add_argument("--per", type=int, default=6000)
ap.add_argument("--bb-per", type=int, default=3000)
ap.add_argument("--only", default="")
args = ap.parse_args()
rows = []
only = set(args.only.split(",")) if args.only else None
for name, fn in GENS.items():
if only and name not in only:
continue
try:
got = fn(args.bb_per if name == "bigbench" else args.per, rng)
except Exception as e:
print(name, "FAILED", type(e).__name__, str(e)[:120])
continue
print(name, len(got))
rows += got
rng.shuffle(rows)
with open(args.out, "w") as f:
for r in rows:
f.write(json.dumps(r, ensure_ascii=False) + "\n")
print("TOTAL", len(rows), "->", args.out)
if __name__ == "__main__":
main()