Beicicc's picture
ProbeShift reproducibility bundle: code + results + paper + figures
592942b verified
Raw
History Blame Contribute Delete
5.05 kB
"""Load HF datasets into a unified record format.
A loaded split is a dict:
{"texts": list[str], "labels": np.ndarray[int], "ids": np.ndarray[int]}
`ids` are stable per (dataset, split) so the SAME example can be aligned across the
iid / paraphrase / length shards (paraphrase keeps the id of its source).
Standard text-classification datasets are loaded directly. POS / truthfulness datasets
are *derived* into a probing format (see builder functions). Derived builders are marked
TODO where a modelling choice should be revisited on the 4090.
"""
from __future__ import annotations
import numpy as np
from config import DATASETS, DatasetSpec
def _subsample(texts, labels, n, seed):
rng = np.random.default_rng(seed)
n = min(n, len(texts))
# stratified-ish: shuffle then take n (good enough; balance checked downstream)
idx = rng.permutation(len(texts))[:n]
return [texts[i] for i in idx], np.asarray(labels)[idx], idx.astype(np.int64)
# --------------------------------------------------------------------------------------
# Builders for derived / non-trivial datasets
# --------------------------------------------------------------------------------------
def _build_ud_pos(spec, split, n, seed):
"""Word-in-context POS probe: pick one target token per sentence, mark it with [],
label = its UPOS tag. Simple, deterministic target selection (first content word).
TODO(4090): consider sampling multiple target positions per sentence for more data.
"""
from datasets import load_dataset
ds = load_dataset(spec.hf_path, spec.hf_config, split=split)
texts, labels = [], []
for ex in ds:
toks, tags = ex["tokens"], ex["upos"]
if not toks:
continue
j = min(range(len(toks)), key=lambda i: (tags[i] in (0,), i)) # first non-punct-ish
marked = " ".join(toks[:j] + ["[" + toks[j] + "]"] + toks[j + 1:])
texts.append(marked)
labels.append(int(tags[j]))
return _subsample(texts, labels, n, seed)
def _build_truthfulqa(spec, split, n, seed):
"""Derive a binary truth probe from TruthfulQA: (question + correct answer) -> 1,
(question + incorrect answer) -> 0. Label comes from existing fields (no annotation).
"""
from datasets import load_dataset
ds = load_dataset(spec.hf_path, spec.hf_config, split=split)
texts, labels = [], []
for ex in ds:
q = ex["question"]
for a in ex.get("correct_answers", [])[:1]:
texts.append(f"Q: {q} A: {a}"); labels.append(1)
for a in ex.get("incorrect_answers", [])[:1]:
texts.append(f"Q: {q} A: {a}"); labels.append(0)
return _subsample(texts, labels, n, seed)
def _build_counterfact(spec, split, n, seed):
"""Derive true/false statements from counterfact-tracing prompt + target_true/false."""
from datasets import load_dataset
ds = load_dataset(spec.hf_path, split=split)
texts, labels = [], []
for ex in ds:
prompt = ex.get("prompt") or ex.get("relation_prefix", "")
t, f = ex.get("target_true"), ex.get("target_false")
if t:
texts.append(f"{prompt} {t}".strip()); labels.append(1)
if f:
texts.append(f"{prompt} {f}".strip()); labels.append(0)
return _subsample(texts, labels, n, seed)
_DERIVED = {
"ud_pos": _build_ud_pos,
"truthfulqa": _build_truthfulqa,
"counterfact": _build_counterfact,
}
# --------------------------------------------------------------------------------------
# Public API
# --------------------------------------------------------------------------------------
def load(dataset_key: str, n: int, split: str | None = None, seed: int = 0) -> dict:
spec: DatasetSpec = DATASETS[dataset_key]
split = split or spec.split
if dataset_key in _DERIVED:
texts, labels, ids = _DERIVED[dataset_key](spec, split, n, seed)
else:
from datasets import load_dataset
ds = load_dataset(spec.hf_path, spec.hf_config, split=split)
texts = list(ds[spec.text_field])
labels = list(ds[spec.label_field])
texts, labels, ids = _subsample(texts, labels, n, seed)
return {"texts": texts, "labels": np.asarray(labels, dtype=np.int64), "ids": ids}
def load_train_eval(dataset_key: str, n_train: int, n_eval: int, seed: int = 0
) -> tuple[dict, dict]:
"""Disjoint IID train / eval draws from the dataset's train split.
If the dataset is smaller than n_train + n_eval, split PROPORTIONALLY so eval is never
empty (small datasets like tweet_eval/stance_feminist have <1500 rows).
"""
full = load(dataset_key, n=n_train + n_eval, split=None, seed=seed)
n = len(full["texts"])
cut = n_train if n >= n_train + n_eval else max(1, int(n * n_train / (n_train + n_eval)))
tr = {"texts": full["texts"][:cut], "labels": full["labels"][:cut],
"ids": full["ids"][:cut]}
ev = {"texts": full["texts"][cut:], "labels": full["labels"][cut:],
"ids": full["ids"][cut:]}
return tr, ev