Beicicc's picture
ProbeShift reproducibility bundle: code + results + paper + figures
592942b verified
Raw
History Blame Contribute Delete
10.3 kB
"""Central configuration: model registry, dataset registry, shift specs, paths, hyper-params.
Importing this module is dependency-light (no torch / transformers) so it can be used by
analysis scripts on a laptop. Heavy imports live in extract_activations.py / data/*.
"""
from __future__ import annotations
import os
from dataclasses import dataclass, field
from pathlib import Path
# --------------------------------------------------------------------------------------
# Paths
# --------------------------------------------------------------------------------------
ROOT = Path(__file__).resolve().parent
CACHE_DIR = Path(os.environ.get("PROBE_CACHE", ROOT / "cache")) # activation shards
RESULTS_DIR = Path(os.environ.get("PROBE_RESULTS", ROOT / "results")) # metrics, tables
DATA_DIR = Path(os.environ.get("PROBE_DATA", ROOT / "data_cache")) # shifted text cache
for _d in (CACHE_DIR, RESULTS_DIR, DATA_DIR):
_d.mkdir(parents=True, exist_ok=True)
# --------------------------------------------------------------------------------------
# Models — the size ladder (claim C4). Keys are short ids used in shard filenames.
# --------------------------------------------------------------------------------------
@dataclass(frozen=True)
class ModelSpec:
key: str # short id, used on disk (no slashes)
hf_name: str # HF hub id
family: str # for grouping in mixed-effects / size ladder
params_m: float # parameter count in millions (for the scale axis)
MODELS: dict[str, ModelSpec] = {
m.key: m for m in [
ModelSpec("pythia-70m", "EleutherAI/pythia-70m", "pythia", 70),
ModelSpec("pythia-160m", "EleutherAI/pythia-160m", "pythia", 160),
ModelSpec("pythia-410m", "EleutherAI/pythia-410m", "pythia", 410),
ModelSpec("pythia-1.4b", "EleutherAI/pythia-1.4b", "pythia", 1400),
ModelSpec("pythia-6.9b", "EleutherAI/pythia-6.9b", "pythia", 6900), # Tier 3: 7B spot-check
ModelSpec("gpt2", "gpt2", "gpt2", 124),
ModelSpec("gpt2-medium", "gpt2-medium", "gpt2", 355),
ModelSpec("qwen2.5-0.5b", "Qwen/Qwen2.5-0.5B", "qwen", 500),
]
}
# Default ladder for the headline scale experiment (cheapest -> most expensive).
SIZE_LADDER = ["pythia-70m", "pythia-160m", "pythia-410m", "pythia-1.4b"]
# --------------------------------------------------------------------------------------
# Datasets — concept-bearing classification tasks (claim families C1/C3).
# `concept` groups datasets that probe the SAME underlying concept (for the Spearman
# generalisation analysis across concept families).
# --------------------------------------------------------------------------------------
@dataclass(frozen=True)
class DatasetSpec:
key: str
hf_path: str
hf_config: str | None
split: str
text_field: str
label_field: str
concept: str # "sentiment" | "topic" | "pos" | "truth"
num_labels: int
# Domain-shift partner: another DatasetSpec key whose inputs share the label space
# but come from a different domain (used as the `domain` OOD distribution).
domain_partner: str | None = None
#
# NOTE: datasets>=5.0 dropped legacy short names AND script-based datasets (no more
# trust_remote_code). Use fully-qualified `namespace/name` Hub ids that ship parquet.
# Verified loadable 2026-06-22: nyu-mll/glue, stanfordnlp/imdb, fancyzhx/ag_news,
# fancyzhx/dbpedia_14, fancyzhx/amazon_polarity.
DATASETS: dict[str, DatasetSpec] = {
d.key: d for d in [
# --- sentiment concept ---
DatasetSpec("sst2", "nyu-mll/glue", "sst2", "train", "sentence", "label", "sentiment", 2,
domain_partner="imdb"),
DatasetSpec("imdb", "stanfordnlp/imdb", None, "train", "text", "label", "sentiment", 2,
domain_partner="sst2"),
DatasetSpec("amazon_polarity", "fancyzhx/amazon_polarity", None, "train", "content",
"label", "sentiment", 2, domain_partner="sst2"),
# --- topic concept ---
DatasetSpec("ag_news", "fancyzhx/ag_news", None, "train", "text", "label", "topic", 4,
domain_partner="dbpedia"),
DatasetSpec("dbpedia", "fancyzhx/dbpedia_14", None, "train", "content", "label", "topic", 14),
# --- syntactic concept (POS) ---
# WARNING: universal_dependencies is script-based -> NOT loadable under datasets>=5.0.
# TODO(4090): swap to a parquet POS source (e.g. a CoNLL-2003 POS parquet) before using.
DatasetSpec("ud_pos", "universal-dependencies/universal_dependencies", "en_ewt", "train",
"tokens", "upos", "pos", 17),
# --- truthfulness / factual concept (derived, label from existing fields) ---
# TODO(4090): truthful_qa generation may be script-based; counterfact-tracing ships parquet.
DatasetSpec("truthfulqa", "truthfulqa/truthful_qa", "generation", "validation", "question",
"label", "truth", 2),
DatasetSpec("counterfact", "NeelNanda/counterfact-tracing", None, "train", "prompt",
"label", "truth", 2),
# --- extra concepts for cross-concept (LOCO) power; all parquet, verified 2026-06-22 ---
DatasetSpec("emotion", "dair-ai/emotion", None, "train", "text", "label", "emotion", 6),
DatasetSpec("tweet_hate", "cardiffnlp/tweet_eval", "hate", "train", "text", "label",
"hate", 2),
DatasetSpec("tweet_irony", "cardiffnlp/tweet_eval", "irony", "train", "text", "label",
"irony", 2),
DatasetSpec("tweet_offensive", "cardiffnlp/tweet_eval", "offensive", "train", "text",
"label", "offensive", 2),
DatasetSpec("subj", "SetFit/subj", None, "train", "text", "label", "subjectivity", 2),
DatasetSpec("spam", "ucirvine/sms_spam", "plain_text", "train", "sms", "label", "spam", 2),
# --- 3 more concepts -> 12 total (verified loadable 2026-06-22) ---
DatasetSpec("cola", "nyu-mll/glue", "cola", "train", "sentence", "label", "grammaticality", 2),
DatasetSpec("stance", "cardiffnlp/tweet_eval", "stance_feminist", "train", "text", "label",
"stance", 3),
DatasetSpec("amazon_cf", "mteb/amazon_counterfactual", "en", "train", "text", "label",
"counterfactual", 2),
]
}
# --------------------------------------------------------------------------------------
# Distribution shifts (label-preserving). Each (dataset, distribution) pair is one
# activation shard. "iid" is the in-distribution train/test of the dataset itself.
# --------------------------------------------------------------------------------------
SHIFTS = ["iid", "paraphrase", "domain", "length"]
# Back-translation pivot for the `paraphrase` SHIFT (rotation ground truth) — keep single &
# fixed (de) so rotation measurements are consistent across runs.
BT_PIVOTS = ["de"]
# Tier 2: the AUGMENTATION predictor uses MULTIPLE pivots for genuine paraphrastic diversity
# (de/fr/ru). With PROBE_N_AUG=3 each aug uses a different pivot, so augmentation-consistency
# reflects robustness to varied surface forms (not the single-pivot artefact of the 1-aug run).
AUG_PIVOTS = ["de", "fr", "ru"]
# Length buckets (token counts) for the `length` shift: train on SHORT, eval on LONG.
LENGTH_BUCKETS = {"short": (0, 32), "long": (96, 512)}
# --------------------------------------------------------------------------------------
# Extraction hyper-params
# --------------------------------------------------------------------------------------
@dataclass
class ExtractConfig:
pooling: str = "mean" # "mean" (masked) | "last" (last non-pad token)
max_length: int = 256
batch_size: int = 32 # lower for pythia-1.4b on 24GB
dtype: str = "float16"
n_train: int = 2000 # examples used to FIT probes per seed (subsampled from pool)
n_eval: int = 1000 # eval examples per (dataset, distribution) per seed (from pool)
n_train_pool: int = 4000 # examples EXTRACTED for train (multi-seed subsamples from this)
n_eval_pool: int = 2000 # examples EXTRACTED for eval/shifts (subsampled per seed)
device: str = "cuda"
# --------------------------------------------------------------------------------------
# Probe / Stability-Score / stats hyper-params
# --------------------------------------------------------------------------------------
@dataclass
class ProbeConfig:
probe_types: tuple[str, ...] = ("logreg", "mass_mean", "mlp")
l2: float = 1.0 # inverse-C handled inside probes.py
mlp_hidden: int = 128
mlp_epochs: int = 50
layer_selection: str = "iid_val" # pick layer by IID val acc, never post-hoc on OOD
@dataclass
class StabilityConfig:
k_bootstrap: int = 8 # K resamples for dispersion (multi-seed compensates)
n_aug: int = 5 # label-preserving augmentations for consistency
# combine(dispersion, aug_consistency) -> scalar score; weights are a hyper-param we
# report sensitivity for. Pre-registered hypothesis: combination > dispersion alone.
w_dispersion: float = 0.5
w_consistency: float = 0.5
@dataclass
class StatsConfig:
seeds: tuple[int, ...] = (0, 1, 2, 3, 4) # >=5; covers init / resample / augmentation
n_bootstrap: int = 1000
fdr_method: str = "holm" # "holm" | "bh"
# Singletons used across the pipeline (override per-run in run_pipeline.py if needed).
EXTRACT = ExtractConfig()
PROBE = ProbeConfig()
STABILITY = StabilityConfig()
STATS = StatsConfig()
# Env overrides — let a small pilot run cheaply without editing code, e.g.
# PROBE_N_TRAIN=600 PROBE_N_EVAL=400 PROBE_N_AUG=2 PROBE_BATCH=64 python run_pipeline.py ...
EXTRACT.n_train = int(os.environ.get("PROBE_N_TRAIN", EXTRACT.n_train))
EXTRACT.n_eval = int(os.environ.get("PROBE_N_EVAL", EXTRACT.n_eval))
EXTRACT.n_train_pool = int(os.environ.get("PROBE_N_TRAIN_POOL", EXTRACT.n_train_pool))
EXTRACT.n_eval_pool = int(os.environ.get("PROBE_N_EVAL_POOL", EXTRACT.n_eval_pool))
EXTRACT.batch_size = int(os.environ.get("PROBE_BATCH", EXTRACT.batch_size))
STABILITY.n_aug = int(os.environ.get("PROBE_N_AUG", STABILITY.n_aug))