Download alea/gen_hf.py from Akahsizrr/alea-runs: direct link, hf CLI and curl.
- Browser
- Download file 30.7 kB
-
https://huggingface.co/datasets/Akahsizrr/alea-runs/resolve/aa0b0ad83671b2039b47234a37b7634b9d3e2fc1/alea/gen_hf.py
- Command line
-
hf download hf://datasets/Akahsizrr/alea-runs@aa0b0ad83671b2039b47234a37b7634b9d3e2fc1/alea/gen_hf.py
-
curl -L -o gen_hf.py https://huggingface.co/datasets/Akahsizrr/alea-runs/resolve/aa0b0ad83671b2039b47234a37b7634b9d3e2fc1/alea/gen_hf.py
30.7 kB
| """HuggingFace datasets -> decision-model rows. | |
| Real human-labeled corpora, mostly DET (hard) targets — complementing the | |
| synthetic SOFT families. Lazy load via `datasets`, module-level cache, rows | |
| drawn with replacement like the other gen modules. | |
| Primitive mapping: | |
| MCQ (sciq/arc/obqa/csqa/race/mmlu/hellaswag/winogrande/piqa) -> choice | |
| topic cls (ag_news/dbpedia/yahoo/trec/emotion/banking77/finpb) -> choice | |
| binary (sst2/cola/mrpc/wnli/qnli/rte/imdb/rt/amazon/paws/wic/boolq) -> noul | |
| NLI (snli/mnli) -> choice + shared-state noul probes | |
| go_emotions (multi-label) -> shared-state noul probes | |
| ordinal (yelp stars/sst5/app_reviews) -> score (5-level) | |
| stsb 0-5 similarity -> regress (normal quantiles, annotator spread) | |
| squad_v2 -> noul answerability | |
| """ | |
| import math | |
| import random | |
| from statistics import NormalDist | |
| from .genbase import (generate, emit, q_choice, q_noul, q_score, q_regress, | |
| validate_row, write_jsonl) | |
| rng = random.Random() | |
| _ND = NormalDist() | |
| _CACHE = {} | |
| def _trunc(s, n): | |
| s = " ".join(str(s).split()) | |
| if len(s) <= n: | |
| return s | |
| return s[:n].rsplit(" ", 1)[0] + "..." | |
| def _ds(key, *args, **kw): | |
| """load_dataset with cache; kw['cols'] limits kept columns if given.""" | |
| if key not in _CACHE: | |
| from datasets import load_dataset | |
| cols = kw.pop("cols", None) | |
| try: | |
| ds = load_dataset(*args, **kw) | |
| except Exception: | |
| _CACHE[key] = [] | |
| return _CACHE[key] | |
| rows = ds.to_list() if hasattr(ds, "to_list") else list(ds) | |
| if cols: | |
| rows = [{c: r.get(c) for c in cols} for r in rows] | |
| _CACHE[key] = rows | |
| return _CACHE[key] | |
| def _pick(rows): | |
| return rows[rng.randrange(len(rows))] | |
| def _onehot(n, k): | |
| t = [0.0] * n | |
| t[k] = 1.0 | |
| return t | |
| def _shuffle_opts(options, k): | |
| """Return (shuffled_options, new_index_of_true).""" | |
| idx = list(range(len(options))) | |
| rng.shuffle(idx) | |
| return [options[i] for i in idx], idx.index(k) | |
| # --------------------------------------------------------------------------- | |
| # MCQ -> choice | |
| # --------------------------------------------------------------------------- | |
| _SCIQ_Q = ["Pick the correct answer.", "Which answer is correct?", | |
| "Choose the right answer to this science question.", | |
| "Select the correct option."] | |
| _ARC_Q = ["Choose the correct answer.", "Which option correctly answers the question?", | |
| "Select the right answer.", "Pick the answer."] | |
| _OBQA_Q = ["Which fact answers the question?", "Choose the correct answer.", | |
| "Select the right option.", "Pick the correct answer."] | |
| _CSQA_Q = ["Choose the most sensible answer.", "Which option best answers the question?", | |
| "Pick the correct answer.", "Select the best answer."] | |
| _RACE_Q = ["Answer the question about the passage.", | |
| "Choose the correct answer based on the article.", | |
| "Which option best answers the question?", "Pick the right answer."] | |
| _MMLU_Q = ["Choose the correct answer.", "Select the right answer.", | |
| "Which option is correct?", "Pick the best answer."] | |
| _HS_Q = ["Which ending continues the passage most sensibly?", | |
| "Pick the most plausible continuation.", | |
| "Choose the ending that makes the most sense.", | |
| "Select the most likely continuation."] | |
| def gen_hf_sciq(): | |
| r = _pick(_ds("sciq", "allenai/sciq", split="train", | |
| cols=["question", "correct_answer", "distractor1", | |
| "distractor2", "distractor3", "support"])) | |
| options = [r["correct_answer"], r["distractor1"], r["distractor2"], | |
| r["distractor3"]] | |
| options, k = _shuffle_opts([_trunc(o, 120) for o in options], 0) | |
| sup = _trunc(r.get("support") or "", 400) | |
| state = ((f"Passage: {sup}\n" if sup else "") | |
| + f"Question: {_trunc(r['question'], 200)}") | |
| return state, [q_choice("ans", rng.choice(_SCIQ_Q), options, | |
| _onehot(len(options), k))] | |
| def _gen_arc(cfg): | |
| r = _pick(_ds(f"arc_{cfg}", "allenai/ai2_arc", cfg, split="train", | |
| cols=["question", "choices", "answerKey"])) | |
| labels = r["choices"]["label"] | |
| texts = [_trunc(t, 140) for t in r["choices"]["text"]] | |
| if r["answerKey"] not in labels: | |
| raise ValueError("bad key") | |
| k = labels.index(r["answerKey"]) | |
| texts, k = _shuffle_opts(texts, k) | |
| state = f"Question: {_trunc(r['question'], 250)}" | |
| return state, [q_choice("ans", rng.choice(_ARC_Q), texts, | |
| _onehot(len(texts), k))] | |
| def gen_hf_arc_easy(): | |
| return _gen_arc("ARC-Easy") | |
| def gen_hf_arc_challenge(): | |
| return _gen_arc("ARC-Challenge") | |
| def gen_hf_openbookqa(): | |
| r = _pick(_ds("obqa", "allenai/openbookqa", "main", split="train", | |
| cols=["question_stem", "choices", "answerKey"])) | |
| labels = r["choices"]["label"] | |
| texts = [_trunc(t, 140) for t in r["choices"]["text"]] | |
| if r["answerKey"] not in labels: | |
| raise ValueError("bad key") | |
| k = labels.index(r["answerKey"]) | |
| texts, k = _shuffle_opts(texts, k) | |
| state = f"Question: {_trunc(r['question_stem'], 250)}" | |
| return state, [q_choice("ans", rng.choice(_OBQA_Q), texts, | |
| _onehot(len(texts), k))] | |
| def gen_hf_csqa(): | |
| r = _pick(_ds("csqa", "tau/commonsense_qa", split="train", | |
| cols=["question", "choices", "answerKey"])) | |
| labels = r["choices"]["label"] | |
| texts = [_trunc(t, 140) for t in r["choices"]["text"]] | |
| if r["answerKey"] not in labels: | |
| raise ValueError("bad key") | |
| k = labels.index(r["answerKey"]) | |
| texts, k = _shuffle_opts(texts, k) | |
| state = f"Question: {_trunc(r['question'], 250)}" | |
| return state, [q_choice("ans", rng.choice(_CSQA_Q), texts, | |
| _onehot(len(texts), k))] | |
| def gen_hf_race(): | |
| r = _pick(_ds("race", "ehovy/race", "all", split="train", | |
| cols=["article", "question", "options", "answer"])) | |
| art = _trunc(r["article"], 900) | |
| q = r["question"].replace("_", "_____") | |
| options = [_trunc(o, 140) for o in r["options"]] | |
| k = "ABCD".index(r["answer"]) | |
| state = f"Article: {art}\nQuestion: {_trunc(q, 200)}" | |
| return state, [q_choice("ans", rng.choice(_RACE_Q), options, | |
| _onehot(len(options), k))] | |
| def gen_hf_mmlu(): | |
| r = _pick(_ds("mmlu", "cais/mmlu", "all", split="test", | |
| cols=["subject", "question", "choices", "answer"])) | |
| options = [_trunc(o, 160) for o in r["choices"]] | |
| subj = r["subject"].replace("_", " ") | |
| state = (f"Subject: {subj}\nQuestion: {_trunc(r['question'], 300)}") | |
| return state, [q_choice("ans", rng.choice(_MMLU_Q), options, | |
| _onehot(len(options), int(r["answer"])))] | |
| def gen_hf_hellaswag(): | |
| r = _pick(_ds("hellaswag", "Rowan/hellaswag", split="train", | |
| cols=["ctx", "endings", "label"])) | |
| endings = [_trunc(e, 180) for e in r["endings"]] | |
| state = f"Passage: {_trunc(r['ctx'], 500)}" | |
| return state, [q_choice("end", rng.choice(_HS_Q), endings, | |
| _onehot(len(endings), int(r["label"])))] | |
| def gen_hf_winogrande(): | |
| r = _pick(_ds("winogrande", "allenai/winogrande", "winogrande_xl", | |
| split="train", | |
| cols=["sentence", "option1", "option2", "answer"])) | |
| sent = r["sentence"].replace("_", "_____") | |
| options, k = _shuffle_opts([r["option1"], r["option2"]], | |
| int(r["answer"]) - 1) | |
| state = f"Sentence: {_trunc(sent, 250)}" | |
| qs = [q_choice("fill", "Which option correctly fills the blank?", | |
| options, _onehot(2, k))] | |
| if rng.random() < 0.4: | |
| qs.append(q_noul("first", "Is the first listed option correct?", | |
| float(k == 0))) | |
| return state, qs | |
| def gen_hf_piqa(): | |
| r = _pick(_ds("piqa", "nthngdy/piqa", split="train", | |
| cols=["goal", "sol1", "sol2", "label"])) | |
| options, k = _shuffle_opts([_trunc(r["sol1"], 200), | |
| _trunc(r["sol2"], 200)], int(r["label"])) | |
| state = f"Goal: {_trunc(r['goal'], 200)}" | |
| return state, [q_choice("sol", "Which solution achieves the goal?", | |
| options, _onehot(2, k))] | |
| # --------------------------------------------------------------------------- | |
| # topic classification -> choice | |
| # --------------------------------------------------------------------------- | |
| _AGN_Q = ["Which topic does this article belong to?", | |
| "Classify this news article.", "Pick the correct news category.", | |
| "What is the subject of this article?"] | |
| _DBP_Q = ["Which category does this entity belong to?", | |
| "Classify this description.", "Pick the correct category."] | |
| _YAH_Q = ["Which topic best fits this question?", | |
| "Classify this question by subject.", | |
| "Pick the most appropriate topic."] | |
| _EMO_Q = ["Which emotion does this text express?", | |
| "Classify the emotion in this text.", | |
| "Pick the dominant emotion."] | |
| _FIN_Q = ["Classify the sentiment of this financial text.", | |
| "Is this text bearish, neutral or bullish?", | |
| "Pick the sentiment of this finance post."] | |
| _BANK_Q = ["Which banking intent does this query express?", | |
| "Classify this customer-service query.", | |
| "Pick the correct intent label."] | |
| def gen_hf_ag_news(): | |
| r = _pick(_ds("ag_news", "fancyzhx/ag_news", split="train", | |
| cols=["text", "label"])) | |
| classes = ["world", "sports", "business", "sci/tech"] | |
| state = f"News article: {_trunc(r['text'], 450)}" | |
| qs = [q_choice("topic", rng.choice(_AGN_Q), classes, | |
| _onehot(4, int(r["label"])))] | |
| if rng.random() < 0.35: | |
| c = rng.randrange(4) | |
| qs.append(q_noul("is", f"Is this a {classes[c]} article?", | |
| float(int(r["label"]) == c))) | |
| return state, qs | |
| def gen_hf_dbpedia(): | |
| r = _pick(_ds("dbpedia", "fancyzhx/dbpedia_14", split="train", | |
| cols=["title", "content", "label"])) | |
| classes = ["company", "educational institution", "artist", "athlete", | |
| "office holder", "mean of transportation", "building", | |
| "natural place", "village", "animal", "plant", "album", | |
| "film", "written work"] | |
| state = (f"Title: {_trunc(r['title'], 80)}\n" | |
| f"Description: {_trunc(r['content'], 350)}") | |
| return state, [q_choice("cat", rng.choice(_DBP_Q), classes, | |
| _onehot(14, int(r["label"])))] | |
| def gen_hf_yahoo(): | |
| r = _pick(_ds("yahoo", "community-datasets/yahoo_answers_topics", | |
| split="train", | |
| cols=["question_title", "question_content", "topic"])) | |
| classes = ["society & culture", "science & math", "health", | |
| "education & reference", "computers & internet", "sports", | |
| "business & finance", "entertainment & music", | |
| "family & relationships", "politics & government"] | |
| state = (f"Question: {_trunc(r['question_title'], 120)}\n" | |
| f"Details: {_trunc(r['question_content'], 280)}") | |
| return state, [q_choice("topic", rng.choice(_YAH_Q), classes, | |
| _onehot(10, int(r["topic"])))] | |
| def gen_hf_emotion(): | |
| r = _pick(_ds("emotion", "dair-ai/emotion", split="train", | |
| cols=["text", "label"])) | |
| classes = ["sadness", "joy", "love", "anger", "fear", "surprise"] | |
| lab = int(r["label"]) | |
| state = f"Text: {_trunc(r['text'], 350)}" | |
| qs = [q_choice("emo", rng.choice(_EMO_Q), classes, _onehot(6, lab))] | |
| if rng.random() < 0.4: # multi-probe on same state | |
| c = rng.randrange(6) | |
| qs.append(q_noul("is", f"Does this text express {classes[c]}?", | |
| float(lab == c))) | |
| return state, qs | |
| def gen_hf_financial(): | |
| r = _pick(_ds("finpb", "zeroshot/twitter-financial-news-sentiment", | |
| split="train", cols=["text", "label"])) | |
| classes = ["bearish", "neutral", "bullish"] | |
| lab = int(r["label"]) | |
| state = f"Financial tweet: {_trunc(r['text'], 300)}" | |
| qs = [q_choice("sent", rng.choice(_FIN_Q), classes, _onehot(3, lab))] | |
| if rng.random() < 0.35: | |
| qs.append(q_noul("neg", "Is this text bearish in tone?", | |
| float(lab == 0))) | |
| return state, qs | |
| def gen_hf_banking77(): | |
| rows = _ds("banking77", "mteb/banking77", split="train", | |
| cols=["text", "label", "label_text"]) | |
| r = _pick(rows) | |
| lab = int(r["label"]) | |
| true_name = str(r["label_text"]).replace("_", " ") | |
| # full 77-way option set is a stress test; 12-way subset keeps length sane | |
| pool = list({str(x["label_text"]).replace("_", " ") | |
| for x in rng.sample(rows, min(60, len(rows)))} - {true_name}) | |
| options = rng.sample(pool, min(11, len(pool))) + [true_name] | |
| options, k = _shuffle_opts(options, len(options) - 1) | |
| state = f"Customer query: {_trunc(r['text'], 250)}" | |
| return state, [q_choice("intent", rng.choice(_BANK_Q), options, | |
| _onehot(len(options), k))] | |
| # --------------------------------------------------------------------------- | |
| # binary -> noul | |
| # --------------------------------------------------------------------------- | |
| def _binary_gen(key, loader, state_fmt, qlist, second=None, extra=None): | |
| r = _pick(_ds(key, *loader["args"], **loader["kw"])) | |
| y = float(r["label"]) | |
| state = state_fmt(r) | |
| instr, pol = qlist[rng.randrange(len(qlist))] | |
| qs = [q_noul("y", instr, y if pol else 1.0 - y)] | |
| if second and rng.random() < 0.35: | |
| qs.append(q_choice("cls", second[0], second[1], | |
| [1.0 - y if pol else y, y if pol else 1.0 - y])) | |
| if extra and rng.random() < 0.4: | |
| q = extra(r) | |
| if q: | |
| qs.append(q) | |
| return state, qs | |
| _SST2_Q = [("Is this review positive?", 1), ("Does this review express praise?", 1), | |
| ("Is this a favorable review?", 1), ("Is this review negative?", 0)] | |
| _COLA_Q = [("Is this sentence grammatically acceptable?", 1), | |
| ("Would a native speaker find this sentence grammatical?", 1), | |
| ("Is this sentence ungrammatical?", 0)] | |
| _MRPC_Q = [("Are these two sentences paraphrases?", 1), | |
| ("Do these sentences mean the same thing?", 1), | |
| ("Are these sentences semantically equivalent?", 1)] | |
| _QNLI_Q = [("Does the sentence answer the question?", 1), | |
| ("Is the question answered by the sentence?", 1), | |
| ("Does the sentence fail to answer the question?", 0)] | |
| _RTE_Q = [("Does the premise entail the hypothesis?", 1), | |
| ("Is the hypothesis supported by the premise?", 1), | |
| ("Can we conclude the hypothesis from the premise?", 1)] | |
| _WNLI_Q = [("Does the first sentence entail the second?", 1), | |
| ("Is the second sentence implied by the first?", 1)] | |
| _IMDB_Q = [("Is this movie review positive?", 1), | |
| ("Did the reviewer like this film?", 1), | |
| ("Is this review negative?", 0)] | |
| _RT_Q = [("Is this review positive?", 1), ("Is this a fresh review?", 1), | |
| ("Is this review rotten?", 0)] | |
| _AMZ_Q = [("Is this product review positive?", 1), | |
| ("Is the customer satisfied?", 1), ("Is this review negative?", 0)] | |
| _PAWS_Q = [("Are these sentences paraphrases?", 1), | |
| ("Do these two sentences have the same meaning?", 1)] | |
| _WIC_Q = [("Does the highlighted word mean the same in both sentences?", 1), | |
| ("Is the target word used with the same sense in both sentences?", 1)] | |
| _BOOLQ_Q = [("Is the correct answer to the question 'yes'?", 1), | |
| ("Would the passage answer yes to this question?", 1)] | |
| def gen_hf_sst2(): | |
| return _binary_gen("sst2", {"args": ("nyu-mll/glue", "sst2"), | |
| "kw": {"split": "train", | |
| "cols": ["sentence", "label"]}}, | |
| lambda r: f"Review excerpt: {_trunc(r['sentence'], 300)}", | |
| _SST2_Q, second=("Classify the sentiment.", | |
| ["negative", "positive"])) | |
| def gen_hf_cola(): | |
| return _binary_gen("cola", {"args": ("nyu-mll/glue", "cola"), | |
| "kw": {"split": "train", | |
| "cols": ["sentence", "label"]}}, | |
| lambda r: f"Sentence: {_trunc(r['sentence'], 250)}", | |
| _COLA_Q) | |
| def gen_hf_mrpc(): | |
| return _binary_gen( | |
| "mrpc", {"args": ("nyu-mll/glue", "mrpc"), | |
| "kw": {"split": "train", | |
| "cols": ["sentence1", "sentence2", "label"]}}, | |
| lambda r: (f"Sentence A: {_trunc(r['sentence1'], 250)}\n" | |
| f"Sentence B: {_trunc(r['sentence2'], 250)}"), | |
| _MRPC_Q) | |
| def gen_hf_qnli(): | |
| return _binary_gen( | |
| "qnli", {"args": ("nyu-mll/glue", "qnli"), | |
| "kw": {"split": "train", | |
| "cols": ["question", "sentence", "label"]}}, | |
| lambda r: (f"Question: {_trunc(r['question'], 200)}\n" | |
| f"Sentence: {_trunc(r['sentence'], 300)}"), | |
| _QNLI_Q) | |
| def gen_hf_rte(): | |
| return _binary_gen( | |
| "rte", {"args": ("nyu-mll/glue", "rte"), | |
| "kw": {"split": "train", | |
| "cols": ["premise", "hypothesis", "label"]}}, | |
| lambda r: (f"Premise: {_trunc(r['premise'], 300)}\n" | |
| f"Hypothesis: {_trunc(r['hypothesis'], 200)}"), | |
| _RTE_Q) | |
| def gen_hf_wnli(): | |
| return _binary_gen( | |
| "wnli", {"args": ("nyu-mll/glue", "wnli"), | |
| "kw": {"split": "train", | |
| "cols": ["sentence1", "sentence2", "label"]}}, | |
| lambda r: (f"Sentence 1: {_trunc(r['sentence1'], 250)}\n" | |
| f"Sentence 2: {_trunc(r['sentence2'], 250)}"), | |
| _WNLI_Q) | |
| def gen_hf_imdb(): | |
| return _binary_gen("stanfordnlp/imdb", {"args": ("stanfordnlp/imdb",), | |
| "kw": {"split": "train", | |
| "cols": ["text", "label"]}}, | |
| lambda r: f"Movie review: {_trunc(r['text'], 600)}", | |
| _IMDB_Q, second=("Classify the review.", | |
| ["negative", "positive"])) | |
| def gen_hf_rotten(): | |
| return _binary_gen("rt", {"args": ("cornell-movie-review-data/rotten_tomatoes",), | |
| "kw": {"split": "train", | |
| "cols": ["text", "label"]}}, | |
| lambda r: f"Review: {_trunc(r['text'], 300)}", | |
| _RT_Q, second=("Classify the review.", | |
| ["rotten", "fresh"])) | |
| def gen_hf_amazon(): | |
| return _binary_gen("amz", {"args": ("fancyzhx/amazon_polarity",), | |
| "kw": {"split": "train", | |
| "cols": ["content", "label"]}}, | |
| lambda r: f"Product review: {_trunc(r['content'], 500)}", | |
| _AMZ_Q, second=("Classify the review.", | |
| ["negative", "positive"])) | |
| def gen_hf_paws(): | |
| return _binary_gen( | |
| "paws", {"args": ("google-research-datasets/paws", "labeled_final"), | |
| "kw": {"split": "train", | |
| "cols": ["sentence1", "sentence2", "label"]}}, | |
| lambda r: (f"Sentence A: {_trunc(r['sentence1'], 250)}\n" | |
| f"Sentence B: {_trunc(r['sentence2'], 250)}"), | |
| _PAWS_Q) | |
| def gen_hf_wic(): | |
| def st(r): | |
| w = r["word"] | |
| return (f"Word: '{w}'\nSentence A: {_trunc(r['sentence1'], 220)}\n" | |
| f"Sentence B: {_trunc(r['sentence2'], 220)}") | |
| return _binary_gen( | |
| "wic", {"args": ("aps/super_glue", "wic"), | |
| "kw": {"split": "train", | |
| "cols": ["word", "sentence1", "sentence2", "label"]}}, | |
| st, _WIC_Q) | |
| def gen_hf_boolq(): | |
| r = _pick(_ds("boolq", "aps/super_glue", "boolq", split="train", | |
| cols=["question", "passage", "label"])) | |
| y = float(r["label"]) | |
| state = (f"Passage: {_trunc(r['passage'], 500)}\n" | |
| f"Question: {_trunc(r['question'], 200)}") | |
| instr, pol = _BOOLQ_Q[rng.randrange(len(_BOOLQ_Q))] | |
| qs = [q_noul("ans", instr, y if pol else 1.0 - y)] | |
| if rng.random() < 0.3: | |
| qs.append(q_choice("yn", "What is the correct answer?", | |
| ["yes", "no"], [y, 1.0 - y])) | |
| return state, qs | |
| # --------------------------------------------------------------------------- | |
| # NLI -> choice + shared-state probes | |
| # --------------------------------------------------------------------------- | |
| _NLI_Q = ["What is the relationship between premise and hypothesis?", | |
| "Classify the entailment relation.", | |
| "Does the premise entail, contradict, or leave neutral the hypothesis?"] | |
| def _nli_gen(key, cfg): | |
| rows = _ds(key, *cfg[0], **cfg[1]) | |
| while True: | |
| r = _pick(rows) | |
| lab = int(r["label"]) | |
| if lab >= 0: # snli has -1 unlabeled rows | |
| break | |
| classes = ["entailment", "neutral", "contradiction"] | |
| state = (f"Premise: {_trunc(r['premise'], 350)}\n" | |
| f"Hypothesis: {_trunc(r['hypothesis'], 180)}") | |
| qs = [q_choice("rel", rng.choice(_NLI_Q), classes, _onehot(3, lab))] | |
| # shared-state probes: ask about the other relations on the SAME state | |
| probes = rng.sample(range(3), k=rng.choice([1, 2])) | |
| for i, p in enumerate(probes): | |
| qs.append(q_noul( | |
| f"is{p}", f"Is the relation '{classes[p]}'?", | |
| float(lab == p))) | |
| return state, qs | |
| def gen_hf_snli(): | |
| return _nli_gen("snli", (("stanfordnlp/snli",), {"split": "train", | |
| "cols": ["premise", "hypothesis", | |
| "label"]})) | |
| def gen_hf_mnli(): | |
| return _nli_gen("mnli", (("nyu-mll/glue", "mnli"), {"split": "train", | |
| "cols": ["premise", | |
| "hypothesis", | |
| "label"]})) | |
| def gen_hf_goemotions(): | |
| rows = _ds("goemo", "google-research-datasets/go_emotions", "simplified", | |
| split="train", cols=["text", "labels"]) | |
| if not rows: | |
| raise ValueError("empty") | |
| r = _pick(rows) | |
| labs = set(r["labels"]) or {27} # empty -> neutral (id 27) | |
| names = ["admiration", "amusement", "anger", "annoyance", "approval", | |
| "caring", "confusion", "curiosity", "desire", "disappointment", | |
| "disapproval", "disgust", "embarrassment", "excitement", "fear", | |
| "gratitude", "grief", "joy", "love", "nervousness", "optimism", | |
| "pride", "realization", "relief", "remorse", "sadness", | |
| "surprise", "neutral"] | |
| state = f"Text: {_trunc(r['text'], 350)}" | |
| qs = [] | |
| pos = rng.choice(sorted(labs)) | |
| negs = rng.sample([i for i in range(28) if i not in labs], | |
| k=rng.choice([1, 2])) | |
| for i, p in enumerate([pos] + negs): | |
| qs.append(q_noul(f"e{i}", | |
| f"Does this text express {names[p]}?", | |
| float(p in labs))) | |
| if rng.random() < 0.5: | |
| c = rng.choice(sorted(labs)) | |
| qs.append(q_noul("cls", f"Is {names[c]} among the emotions?", | |
| 1.0)) | |
| return state, qs | |
| # --------------------------------------------------------------------------- | |
| # ordinal -> score (5 levels) | |
| # --------------------------------------------------------------------------- | |
| _STAR_LV = ["1 star", "2 stars", "3 stars", "4 stars", "5 stars"] | |
| _YELP_Q = ["How many stars did the reviewer give?", | |
| "Rate this review from 1 to 5 stars.", | |
| "What star rating does this review correspond to?"] | |
| _SST5_LV = ["very negative", "negative", "neutral", "positive", | |
| "very positive"] | |
| _SST5_Q = ["Classify the sentiment on a five-point scale.", | |
| "Rate the sentiment of this sentence.", | |
| "Pick the sentiment level."] | |
| _APP_Q = ["How many stars did the user give this app?", | |
| "Rate this app review from 1 to 5 stars.", | |
| "What star rating does this review show?"] | |
| def gen_hf_yelp(): | |
| r = _pick(_ds("yelp", "Yelp/yelp_review_full", split="train", | |
| cols=["text", "label"])) | |
| lab = int(r["label"]) # 0-4 -> 1-5 stars | |
| state = f"Yelp review: {_trunc(r['text'], 500)}" | |
| qs = [q_score("stars", rng.choice(_YELP_Q), _STAR_LV, _onehot(5, lab))] | |
| if rng.random() < 0.3: | |
| qs.append(q_noul("pos", "Is this a positive review (4-5 stars)?", | |
| float(lab >= 3))) | |
| return state, qs | |
| def gen_hf_sst5(): | |
| r = _pick(_ds("sst5", "SetFit/sst5", split="train", | |
| cols=["text", "label"])) | |
| lab = int(r["label"]) | |
| state = f"Sentence: {_trunc(r['text'], 300)}" | |
| return state, [q_score("sent", rng.choice(_SST5_Q), _SST5_LV, | |
| _onehot(5, lab))] | |
| def gen_hf_app_reviews(): | |
| r = _pick(_ds("apprev", "sealuzh/app_reviews", split="train", | |
| cols=["review", "star"])) | |
| lab = int(r["star"]) - 1 # 1-5 -> 0-4 | |
| state = f"App store review: {_trunc(r['review'], 400)}" | |
| qs = [q_score("stars", rng.choice(_APP_Q), _STAR_LV, _onehot(5, lab))] | |
| if rng.random() < 0.3: | |
| qs.append(q_noul("pos", "Is this a positive review (4-5 stars)?", | |
| float(lab >= 3))) | |
| return state, qs | |
| # --------------------------------------------------------------------------- | |
| # continuous -> regress | |
| # --------------------------------------------------------------------------- | |
| def _bucket_quantiles(lo, hi): | |
| """19 quantiles of Uniform(lo, hi).""" | |
| taus = [0.05 + 0.05 * i for i in range(19)] | |
| return [lo + t * (hi - lo) for t in taus] | |
| def gen_hf_stsb(): | |
| r = _pick(_ds("stsb", "nyu-mll/glue", "stsb", split="train", | |
| cols=["sentence1", "sentence2", "label"])) | |
| score = float(r["label"]) # 0-5 human similarity | |
| state = (f"Sentence A: {_trunc(r['sentence1'], 250)}\n" | |
| f"Sentence B: {_trunc(r['sentence2'], 250)}") | |
| # model annotator disagreement as Normal(score, 0.6) clipped to [0,5] | |
| sd = 0.6 | |
| taus = [0.05 + 0.05 * i for i in range(19)] | |
| qs19 = [min(5.0, max(0.0, score + _ND.inv_cdf(t) * sd)) for t in taus] | |
| qs = [q_regress("sim", "Predict the semantic similarity score (0-5).", | |
| qs19, unit="similarity points")] | |
| if rng.random() < 0.35: | |
| thr = rng.choice([1.0, 2.0, 3.0, 4.0]) | |
| qs.append(q_noul("hi", f"Is the similarity above {thr}?", | |
| float(score > thr))) | |
| return state, qs | |
| def gen_hf_yelp_reg(): | |
| """Star rating -> regress on bucket uncertainty (uniform within star).""" | |
| r = _pick(_ds("yelp", "Yelp/yelp_review_full", split="train", | |
| cols=["text", "label"])) | |
| lab = int(r["label"]) # 0-4 | |
| state = f"Yelp review: {_trunc(r['text'], 500)}" | |
| lo, hi = float(lab), float(lab + 1) | |
| qs = [q_regress("stars", "Predict the star rating (0-5 scale).", | |
| _bucket_quantiles(lo, hi), unit="stars")] | |
| return state, qs | |
| # --------------------------------------------------------------------------- | |
| # squad_v2 -> answerability noul | |
| # --------------------------------------------------------------------------- | |
| def gen_hf_squad2(): | |
| r = _pick(_ds("squad2", "rajpurkar/squad_v2", split="train", | |
| cols=["context", "question", "answers"])) | |
| answerable = len(r["answers"]["text"]) > 0 | |
| state = (f"Context: {_trunc(r['context'], 600)}\n" | |
| f"Question: {_trunc(r['question'], 200)}") | |
| qs = [q_noul("ans", "Is this question answerable from the context?", | |
| float(answerable))] | |
| if answerable and rng.random() < 0.4: | |
| ans = r["answers"]["text"][0] | |
| qs.append(q_noul("short", f"Is the answer short (under 40 chars)?", | |
| float(len(ans) < 40))) | |
| return state, qs | |
| FAMILIES = { | |
| # MCQ | |
| "hf_sciq": gen_hf_sciq, "hf_arc_easy": gen_hf_arc_easy, | |
| "hf_arc_chal": gen_hf_arc_challenge, "hf_obqa": gen_hf_openbookqa, | |
| "hf_csqa": gen_hf_csqa, "hf_race": gen_hf_race, | |
| "hf_mmlu": gen_hf_mmlu, "hf_hellaswag": gen_hf_hellaswag, | |
| "hf_winogrande": gen_hf_winogrande, "hf_piqa": gen_hf_piqa, | |
| # topic cls | |
| "hf_ag_news": gen_hf_ag_news, "hf_dbpedia": gen_hf_dbpedia, | |
| "hf_emotion": gen_hf_emotion, "hf_financial": gen_hf_financial, | |
| "hf_banking77": gen_hf_banking77, | |
| # binary | |
| "hf_sst2": gen_hf_sst2, "hf_cola": gen_hf_cola, | |
| "hf_mrpc": gen_hf_mrpc, "hf_qnli": gen_hf_qnli, | |
| "hf_rte": gen_hf_rte, "hf_wnli": gen_hf_wnli, | |
| "hf_imdb": gen_hf_imdb, "hf_rotten": gen_hf_rotten, | |
| "hf_amazon": gen_hf_amazon, "hf_paws": gen_hf_paws, | |
| "hf_wic": gen_hf_wic, "hf_boolq": gen_hf_boolq, | |
| # NLI / multi-probe | |
| "hf_snli": gen_hf_snli, "hf_mnli": gen_hf_mnli, | |
| "hf_goemo": gen_hf_goemotions, | |
| # ordinal | |
| "hf_yelp": gen_hf_yelp, "hf_sst5": gen_hf_sst5, | |
| "hf_app_rev": gen_hf_app_reviews, | |
| # regress | |
| "hf_stsb": gen_hf_stsb, "hf_yelp_reg": gen_hf_yelp_reg, | |
| # answerability | |
| "hf_squad2": gen_hf_squad2, | |
| } | |
| WEIGHTS = {k: 1.0 for k in FAMILIES} | |
| WEIGHTS.update({"hf_squad2": 0.6, "hf_app_rev": 0.7, "hf_banking77": 0.6, | |
| "hf_mmlu": 0.8, "hf_goemo": 0.8, "hf_yelp_reg": 0.5}) | |
| def make_rows(n, seed): | |
| return generate(FAMILIES, WEIGHTS, n, seed, rng) | |
| if __name__ == "__main__": | |
| rows = make_rows(20, 0) | |
| seen = {} | |
| for r in rows: | |
| validate_row(r) | |
| seen[r["family"]] = seen.get(r["family"], 0) + 1 | |
| print(f"{len(rows)} rows OK") | |
| print(seen) | |