"""gen_hf3: second wave of real HF data — legal/policy/multi-hop/social. Targets the skills JevBench-hard actually tests: apply a long document's rules to a concrete case (contract-nli, casehold, ledgar), multi-hop retrieval (hotpot, 2wiki), algebra MCQ (aqua), commonsense/social (cosmos, siqa, swag, medmcqa), answerability (squad_v2). """ import argparse import json import random from datasets import load_dataset rng = random.Random(555) def choice_row(state, instructions, options_texts, correct_idx, family, meta=None): n = len(options_texts) keys = ["opt_%d" % i for i in range(n)] seen, fo, fk, ni = {}, [], [], None for i, t in enumerate(options_texts): t = str(t).strip() if not t: t = "(empty %d)" % i if t in seen: if i == correct_idx: ni = seen[t] continue seen[t] = len(fo) fo.append(t); fk.append(keys[i]) if i == correct_idx: ni = len(fo) - 1 if ni is None or len(fo) < 2: return None tgt = [0.0] * len(fo); tgt[ni] = 1.0 return {"state": str(state)[:20000], "questions": {"q0": {"type": "choice", "instructions": instructions, "criteria": dict(zip(fk, fo))}}, "targets": {"q0": tgt}, "family": family, "meta": meta or {}} def noul_row(state, instructions, val, family, meta=None): return {"state": str(state)[:20000], "questions": {"q0": {"type": "noul", "instructions": instructions}}, "targets": {"q0": float(val)}, "family": family, "meta": meta or {}} def gen_contractnli(n, rng): """Contract + hypothesis -> entailment/contradiction/neutral (3-way).""" ds = None for repo, cfg in (("coastalcph/lex_glue", "contract_nli"), ("jonathanli/lex-glue", "contract_nli")): try: ds = load_dataset(repo, cfg, split="train") break except Exception: continue if ds is None: return [] out = [] label_names = ["entailment", "neutral", "contradiction"] feats = ds.features.get("label") if feats is not None and hasattr(feats, "names"): label_names = feats.names idxs = list(range(len(ds))); rng.shuffle(idxs) for i in idxs: if len(out) >= n: break r = ds[i] doc = (r.get("contract_text") or r.get("document") or "")[:9000] hyp = r.get("hypothesis") or r.get("premise") or "" lab = r.get("label") if not doc or not hyp or lab is None: continue ci = int(lab) if ci >= len(label_names): continue st = ("CONTRACT EXCERPT:\n%s\n\nHYPOTHESIS UNDER REVIEW:\n%s" % (doc, hyp)) row = choice_row(st, "Decide the relationship between the contract " "text and the hypothesis.", ["the contract entails the hypothesis", "the contract neither entails nor contradicts it", "the contract contradicts the hypothesis"], {"entailment": 0, "neutral": 1, "contradiction": 2}.get(label_names[ci].lower(), 1), "hf_contractnli", meta={"src": "contract_nli"}) if row: out.append(row) return out def gen_casehold(n, rng): ds = None for repo in ("coastalcph/lex_glue", "jonathanli/lex-glue"): try: ds = load_dataset(repo, "case_hold", split="train") break except Exception: continue if ds is None: return [] out = [] idxs = list(range(len(ds))); rng.shuffle(idxs) for i in idxs: if len(out) >= n: break r = ds[i] ctx = str(r.get("context") or "")[:6000] endings = [str(e) for e in (r.get("endings") or [])] lab = int(r.get("label", -1)) if not ctx or len(endings) < 2 or lab < 0 or lab >= len(endings): continue row = choice_row("Case context:\n%s" % ctx, "Choose the holding that correctly completes the " "legal reasoning.", endings, lab, "hf_casehold", meta={"src": "lex_glue_case_hold"}) if row: out.append(row) return out def gen_ledgar(n, rng): """Contract clause -> provision type among sampled options.""" ds = None for repo in ("coastalcph/lex_glue", "jonathanli/lex-glue"): try: ds = load_dataset(repo, "ledgar", split="train") break except Exception: continue if ds is None: return [] names = ds.features["label"].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[int(r["label"])].replace("_", " ").lower() k = rng.randint(3, 6) others = rng.sample([x.replace("_", " ").lower() for x in names if x != names[int(r["label"])]], k) opts = [true_name] + others order = list(range(len(opts))); rng.shuffle(order) shuffled = [opts[j] for j in order] ci = shuffled.index(true_name) st = "Contract clause:\n%s" % str(r.get("text") or "")[:3000] row = choice_row(st, "Classify the provision type of this clause.", shuffled, ci, "hf_ledgar", meta={"src": "ledgar"}) if row: out.append(row) return out def gen_unfair_tos(n, rng): """ToS clause -> unfairness category.""" ds = None for repo in ("coastalcph/lex_glue", "jonathanli/lex-glue"): try: ds = load_dataset(repo, "unfair_tos", split="train") break except Exception: continue if ds is None: return [] names = ds.features["label"].names out = [] idxs = list(range(len(ds))); rng.shuffle(idxs) for i in idxs: if len(out) >= n: break r = ds[i] lab = int(r["label"]) txt = str(r.get("text") or "")[:3000] if not txt: continue opts = [x.replace("_", " ") for x in names] row = choice_row("Terms-of-service clause:\n%s" % txt, "Classify the unfairness category of this clause.", opts, lab, "hf_unfair_tos", meta={"src": "unfair_tos"}) if row: out.append(row) return out def gen_hotpot(n, rng): try: ds = load_dataset("hotpotqa/hotpot_qa", "distractor", split="train") except Exception: try: ds = load_dataset("hotpot_qa", "distractor", split="train", trust_remote_code=True) except Exception: return [] out = [] idxs = list(range(len(ds))); rng.shuffle(idxs) for i in idxs: if len(out) >= n: break r = ds[i] # build a passage bundle from context titles/sentences ctx = r.get("context") or {} titles = ctx.get("title") or [] sents = ctx.get("sentences") or [] parts = [] for t, ss in zip(titles[:8], sents[:8]): parts.append("%s: %s" % (t, " ".join(ss[:4]))) st = ("Passages:\n%s\n\nQuestion: %s" % ("\n".join(parts), r["question"])) ans = r.get("answer", "") if not ans or len(ans) > 120: continue # distractors from other answers oi = idxs[rng.randint(0, len(idxs) - 1)] wrong = [] while len(wrong) < 3: w = ds[oi].get("answer", "") if w and w != ans and len(w) < 120 and w not in wrong: wrong.append(w) oi = idxs[rng.randint(0, len(idxs) - 1)] opts = [ans] + wrong order = list(range(4)); rng.shuffle(order) shuffled = [opts[j] for j in order] ci = shuffled.index(ans) row = choice_row(st, "Choose the answer that the passages jointly " "support.", shuffled, ci, "hf_hotpot", meta={"src": "hotpot"}) if row: out.append(row) return out def gen_aqua(n, rng): try: ds = load_dataset("deepmind/aqua_rat", "raw", split="train") except Exception: try: ds = load_dataset("aqua_rat", split="train", trust_remote_code=True) except Exception: return [] out = [] letter = "abcde" for r in ds: if len(out) >= n: break opts = r.get("options") or [] opts = [o[2:].strip() if len(o) > 2 and o[1] == ")" else o.strip() for o in opts] if len(opts) != 5: continue ci = letter.find(str(r.get("correct", "")).lower()) if ci < 0: continue row = choice_row("Problem:\n%s" % r["question"].strip(), "Solve and choose the correct answer.", opts, ci, "hf_aqua", meta={"src": "aqua_rat"}) if row: out.append(row) return out def gen_medmcqa(n, rng): try: ds = load_dataset("openlifescienceai/medmcqa", split="train") except Exception: try: ds = load_dataset("medmcqa", split="train", trust_remote_code=True) except Exception: return [] out = [] idxs = list(range(len(ds))); rng.shuffle(idxs) for i in idxs: if len(out) >= n: break r = ds[i] opts = [r.get(k, "") for k in ("opa", "opb", "opc", "opd")] cop = r.get("cop") if not all(opts) or cop is None or int(cop) > 3: continue st = "Clinical question:\n%s" % (r.get("question") or "") row = choice_row(st, "Choose the best answer.", opts, int(cop), "hf_medmcqa", meta={"src": "medmcqa"}) if row: out.append(row) return out def gen_cosmos(n, rng): try: ds = load_dataset("allenai/cosmos_qa", split="train") except Exception: try: ds = load_dataset("cosmos_qa", split="train", trust_remote_code=True) except Exception: return [] out = [] idxs = list(range(len(ds))); rng.shuffle(idxs) for i in idxs: if len(out) >= n: break r = ds[i] opts = [r.get("answer%d" % k, "") for k in range(4)] lab = r.get("label") if not all(opts) or lab is None: continue st = "Context:\n%s\n\nQuestion:\n%s" % (r.get("context", ""), r.get("question", "")) row = choice_row(st, "Choose the most plausible answer.", opts, int(lab), "hf_cosmos", meta={"src": "cosmos_qa"}) if row: out.append(row) return out def gen_squad2(n, rng): """Answerable vs unanswerable -> noul (abstention signal).""" try: ds = load_dataset("rajpurkar/squad_v2", split="train") except Exception: return [] out = [] idxs = list(range(len(ds))); rng.shuffle(idxs) for i in idxs: if len(out) >= n: break r = ds[i] ans = r.get("answers", {}).get("text") or [] st = "Passage:\n%s\n\nQuestion:\n%s" % (r["context"][:5000], r["question"]) out.append(noul_row(st, "Is the question answerable from the " "passage?", len(ans) > 0, "hf_squad2_answerable", meta={"src": "squad_v2"})) return out def gen_siqa(n, rng): try: ds = load_dataset("allenai/social_i_qa", split="train") except Exception: try: ds = load_dataset("social_i_qa", split="train", trust_remote_code=True) except Exception: return [] out = [] for r in ds: if len(out) >= n: break opts = [r.get("answerA", ""), r.get("answerB", ""), r.get("answerC", "")] lab = r.get("label") if not all(opts) or lab is None: continue st = "Situation:\n%s\n\nQuestion:\n%s" % (r.get("context", ""), r.get("question", "")) row = choice_row(st, "Choose the best answer.", opts, int(lab) - 1, "hf_siqa", meta={"src": "siqa"}) if row: out.append(row) return out def gen_swag(n, rng): try: ds = load_dataset("allenai/swag", "regular", split="train") except Exception: try: ds = load_dataset("swag", split="train", trust_remote_code=True) except Exception: return [] out = [] idxs = list(range(len(ds))); rng.shuffle(idxs) for i in idxs: if len(out) >= n: break r = ds[i] opts = [r.get("ending%d" % k, "") for k in range(4)] lab = r.get("label") if not all(opts) or lab is None: continue st = "%s %s" % (r.get("startphrase", ""), r.get("sent1", "")) row = choice_row(st, "Choose the most plausible continuation.", opts, int(lab), "hf_swag", meta={"src": "swag"}) if row: out.append(row) return out GENS = { "ledgar": gen_ledgar, "unfair_tos": gen_unfair_tos, "casehold": gen_casehold, "hotpot": gen_hotpot, "aqua": gen_aqua, "medmcqa": gen_medmcqa, "squad2": gen_squad2, "swag": gen_swag, } def main(): ap = argparse.ArgumentParser() ap.add_argument("--out", default="data/hf3.jsonl") ap.add_argument("--per", type=int, default=5000) 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.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()