| 这是一个工程架构设计任务,不是 ADR 决策。我直接输出完整的实验代码架构 spec。下面是为《Probe Stability Score》设计的、可在单卡 4090 上运行的完整工程化 spec。 |
|
|
| --- |
|
|
| # Probe Stability Score · 实验代码架构 Spec |
|
|
| 设计目标:一次性激活抽取 + 缓存复用,所有探针/指标计算只读缓存;严控显存与 GPU·h(≤30 GPU·h);单条命令复现最小可行实验(MVE)。 |
|
|
| --- |
|
|
| ## 1. 目录 / 文件树 |
|
|
| ``` |
| probe_stability/ |
| ├── README.md |
| ├── pyproject.toml # 依赖 + 入口 console_scripts |
| ├── Makefile # make mve / make full / make figures |
| ├── configs/ |
| │ ├── base.yaml # 全局:路径、dtype、seed 列表、CI 参数 |
| │ ├── models.yaml # 7 个模型的 HF id、层数、d_model、最佳 batch |
| │ ├── datasets.yaml # 8 个任务:HF id、字段映射、label 空间、采样数 |
| │ ├── shifts.yaml # back-translation / domain / length 三类 shift 配置 |
| │ ├── probes.yaml # logreg / mass_mean / mlp / control 超参 |
| │ ├── metrics.yaml # Score 双分量权重、bootstrap、多重检验方法 |
| │ └── experiments/ |
| │ ├── mve.yaml # 最小可行:pythia-70m + SST-2 + 1 shift + 2 seed |
| │ └── full.yaml # 全量矩阵 |
| ├── env/ |
| │ └── download_models.py # 预下载所有 HF 权重到本地缓存(离线复现) |
| ├── src/probe_stability/ |
| │ ├── __init__.py |
| │ ├── cli.py # Typer/argparse 主入口,子命令路由 |
| │ ├── config.py # OmegaConf 加载 + dataclass schema 校验 |
| │ ├── registry.py # MODEL/DATASET/PROBE/SHIFT 注册表(字符串→构造器) |
| │ ├── utils/ |
| │ │ ├── seeding.py # set_all_seeds(seed) |
| │ │ ├── logging.py # rich/structlog,JSONL run log |
| │ │ ├── io.py # shard 路径生成、原子写、manifest 读写 |
| │ │ ├── gpu.py # 显存监控、autocast、空缓存、OOM 自动降 batch |
| │ │ └── hashing.py # config/input 指纹 → 缓存 key、幂等跳过 |
| │ ├── data/ |
| │ │ ├── loaders.py # 8 个数据集统一加载为 Example schema |
| │ │ ├── schema.py # Example / DistributionSet dataclass |
| │ │ ├── sampling.py # 分层下采样、固定 split、length buckets 切分 |
| │ │ └── shifts/ |
| │ │ ├── base.py # Shift 抽象基类 |
| │ │ ├── backtranslation.py # NLLB / opus-mt 本地往返翻译 |
| │ │ ├── domain.py # Amazon multi-domain / IMDB↔SST-2 域迁移 |
| │ │ └── length.py # 短/中/长 token 分桶 |
| │ ├── fidelity/ |
| │ │ └── mnli_filter.py # 本地 DeBERTa-v3-MNLI 过滤 label flip |
| │ ├── extract/ |
| │ │ ├── activations.py # 核心:逐层 residual-stream 抽取 + 流式落盘 |
| │ │ ├── hooks.py # 各架构 residual hook 适配(Pythia/GPT2/Qwen2) |
| │ │ └── pooling.py # last-token / mean pooling |
| │ ├── cache/ |
| │ │ ├── store.py # ShardStore:read/write float16 分片 + manifest |
| │ │ └── manifest.py # 全局缓存索引(parquet),完整性校验 |
| │ ├── probes/ |
| │ │ ├── base.py # Probe 抽象:fit/predict/direction |
| │ │ ├── logreg.py # sklearn / torch LogReg |
| │ │ ├── mass_mean.py # difference-of-means 方向探针 |
| │ │ ├── mlp.py # 2-layer MLP (torch) |
| │ │ └── control.py # random-label control-task 包装器 |
| │ ├── eval/ |
| │ │ ├── train_eval.py # 读缓存→训练→IID/OOD 评估 单元 |
| │ │ ├── directions.py # 概念方向、跨分布 cosine 旋转 |
| │ │ └── selectivity.py # selectivity = acc(real) - acc(control) |
| │ ├── score/ |
| │ │ └── stability.py # 双分量 Probe Stability Score 计算 |
| │ ├── stats/ |
| │ │ ├── bootstrap.py # bootstrap CI |
| │ │ ├── correlation.py # Spearman(Score ↔ OOD drop) |
| │ │ ├── effect_size.py # Cliff's delta |
| │ │ └── multiple_testing.py # Holm / Benjamini-Hochberg |
| │ └── pipeline/ |
| │ ├── stage_extract.py # 阶段1:激活抽取(写缓存) |
| │ ├── stage_probe.py # 阶段2:探针训练+评估(读缓存) |
| │ ├── stage_score.py # 阶段3:Score 聚合 |
| │ └── stage_stats.py # 阶段4:统计检验 + 表格 |
| ├── scripts/ |
| │ ├── run_mve.sh # 一条命令复现 MVE |
| │ ├── run_full.sh |
| │ └── make_figures.py # 论文图(cosine 旋转、Score↔drop 散点) |
| ├── tests/ |
| │ ├── test_cache_roundtrip.py |
| │ ├── test_shapes.py |
| │ ├── test_probes_smoke.py |
| │ └── test_score_math.py |
| └── artifacts/ # 运行产物(git-ignored) |
| ├── cache/ # 激活分片 |
| ├── results/ # parquet 结果表 |
| ├── figures/ |
| └── logs/ |
| ``` |
|
|
| --- |
|
|
| ## 2. 各模块职责 + 关键函数签名 |
|
|
| ### 2.1 config / registry |
|
|
| ```python |
| # config.py |
| @dataclass |
| class RunConfig: |
| models: list[str]; datasets: list[str]; shifts: list[str] |
| probes: list[str]; seeds: list[int] |
| cache_dir: Path; results_dir: Path |
| pooling: str = "last_token" # last_token | mean |
| dtype: str = "float16" |
| max_examples_per_dist: int = 4000 # 控制规模/显存 |
| extract_batch: dict[str, int] = ... # 每模型 batch 覆盖 |
| |
| def load_config(exp_path: str, overrides: list[str]) -> RunConfig: ... |
| |
| # registry.py |
| def register(kind: str, name: str): ... # 装饰器 |
| def build_model(name: str) -> "LMWrapper": ... |
| def build_dataset(name: str) -> "DistributionSet": ... |
| def build_probe(name: str, **kw) -> "Probe": ... |
| def build_shift(name: str) -> "Shift": ... |
| ``` |
|
|
| ### 2.2 data |
|
|
| ```python |
| # schema.py |
| @dataclass(frozen=True) |
| class Example: |
| uid: str; text: str; label: int; meta: dict # meta 含 domain/length_bucket |
| |
| @dataclass |
| class DistributionSet: |
| name: str # e.g. "sst2" |
| distribution: str # "iid" | "bt_de" | "domain_books" | "len_long" |
| examples: list[Example] |
| num_labels: int |
| |
| # loaders.py |
| def load_dataset(name: str, split: str, max_n: int, seed: int) -> DistributionSet: ... |
| # 支持: sst2 imdb amazon_multi ag_news dbpedia ud_pos truthfulqa_bin counterfact_bin |
| |
| # sampling.py |
| def stratified_subsample(ds: DistributionSet, n: int, seed: int) -> DistributionSet: ... |
| def length_buckets(ds: DistributionSet, tokenizer, edges=(32,128)) -> dict[str, DistributionSet]: ... |
| |
| # shifts/base.py |
| class Shift(ABC): |
| name: str |
| @abstractmethod |
| def apply(self, ds: DistributionSet) -> DistributionSet: ... |
| # 产出 distribution 字段已改写、label 暂保留(待 fidelity 过滤) |
| |
| # shifts/backtranslation.py |
| class BackTranslationShift(Shift): |
| def __init__(self, pivot="deu_Latn", model="facebook/nllb-200-distilled-600M", |
| batch_size=32, device="cuda"): ... |
| def apply(self, ds) -> DistributionSet: ... # text→pivot→en,流式 batch |
| ``` |
|
|
| ### 2.3 fidelity |
|
|
| ```python |
| # mnli_filter.py |
| class MNLIFidelityFilter: |
| def __init__(self, model="MoritzLaurer/DeBERTa-v3-base-mnli", thresh=0.5): ... |
| def keep_mask(self, src_texts: list[str], shifted_texts: list[str]) -> np.ndarray: |
| """双向蕴含判定:保留语义未翻转(label-preserving)样本,返回 bool mask""" |
| def filter(self, src: DistributionSet, shifted: DistributionSet) -> DistributionSet: ... |
| ``` |
|
|
| ### 2.4 extract(核心) |
|
|
| ```python |
| # hooks.py |
| def residual_hook_points(model, arch: str) -> list[tuple[int, nn.Module]]: |
| """返回 [(layer_idx, module)],module 输出即该层 residual-stream。 |
| Pythia(GPTNeoX): gpt_neox.layers[i]; GPT2: transformer.h[i]; Qwen2: model.layers[i]""" |
| |
| # pooling.py |
| def pool(hidden: Tensor, attn_mask: Tensor, mode: str) -> Tensor: |
| """(B,T,D)->(B,D);last_token 取最后非 pad 位,mean 做 mask 平均""" |
| |
| # activations.py |
| class ActivationExtractor: |
| def __init__(self, model_name: str, dtype="float16", device="cuda", |
| pooling="last_token", max_len=256): ... |
| |
| @torch.inference_mode() |
| def extract(self, ds: DistributionSet, store: "ShardStore", |
| batch_size: int, layers: list[int] | None = None) -> ShardMeta: |
| """单次前向抓全层 residual,逐 batch pool→cast fp16→流式 append 落盘。 |
| 返回写入分片的元信息(n, layers, d_model)。""" |
| ``` |
|
|
| 抽取核心逻辑:注册 forward hook 抓全部层 → 一次前向 → 每层 pool → fp16 → 立即追加写盘,**不在显存/内存累积全量激活**。 |
|
|
| ### 2.5 cache |
|
|
| ```python |
| # store.py 分片单位 = (model, dataset, distribution);层维进 .npz 同文件多 key 或单层一文件 |
| class ShardStore: |
| def __init__(self, root: Path, dtype="float16"): ... |
| def shard_path(self, model, dataset, distribution, layer, seed_split="all") -> Path: ... |
| def open_writer(self, model, dataset, distribution, n_layers, d_model, n: int): ... |
| def append(self, layer_arrays: dict[int, np.ndarray], labels, uids): ... # 流式 |
| def finalize(self): ... # 写 X.npy / y.npy / uids |
| def load(self, model, dataset, distribution, layer) -> tuple[np.ndarray, np.ndarray, list[str]]: |
| """mmap 读取 X(fp16), y(int8), uids""" |
| def exists(self, model, dataset, distribution, layer) -> bool: ... # 幂等跳过 |
| |
| # manifest.py |
| def update_manifest(root: Path, meta: dict): ... # 追加到 manifest.parquet |
| def verify_cache(root: Path) -> list[str]: ... # 返回缺失/损坏 shard |
| ``` |
|
|
| ### 2.6 probes |
|
|
| ```python |
| # base.py |
| class Probe(ABC): |
| @abstractmethod |
| def fit(self, X: np.ndarray, y: np.ndarray) -> "Probe": ... |
| @abstractmethod |
| def predict(self, X: np.ndarray) -> np.ndarray: ... |
| @abstractmethod |
| def direction(self) -> np.ndarray | None: # 概念方向(单位向量),MLP 返回 None 或一阶近似 |
| ... |
| |
| # logreg.py LogRegProbe(C=1.0, max_iter=1000) —— 内部 X 升精到 float32 训练 |
| # mass_mean.py MassMeanProbe —— direction = (μ_pos - μ_neg)/||·||;阈值=中点投影 |
| # mlp.py MLPProbe(hidden=256, epochs=30, lr=1e-3, device="cuda") —— direction=输入层雅可比近似 |
| # control.py |
| class ControlTaskProbe(Probe): |
| def __init__(self, inner: Probe, seed: int): |
| """random-label control:固定随机标签置换后训练同结构探针""" |
| ``` |
|
|
| ### 2.7 eval / score / stats |
|
|
| ```python |
| # train_eval.py |
| def fit_and_eval(probe_name, store, model, dataset, |
| train_dist="iid", eval_dists=("iid","bt_de",...), |
| seed=0) -> ProbeResult: |
| """读 train_dist 缓存→fit→在各 eval_dist 上算 acc;返回 acc 字典 + 方向向量""" |
| |
| # directions.py |
| def cosine_rotation(dir_iid: np.ndarray, dir_ood: np.ndarray) -> float: ... # 1 - cos |
| def aggregate_directions(results: list[ProbeResult], by="layer") -> pd.DataFrame: ... |
| |
| # selectivity.py |
| def selectivity(real_acc: float, control_acc: float) -> float: ... |
| |
| # score/stability.py |
| def probe_stability_score(acc_iid, acc_ood, dir_iid, dir_ood, |
| w_perf=0.5, w_geom=0.5) -> dict: |
| """双分量: |
| perf_component = acc_ood / acc_iid (性能保持度,∈[0,1]) |
| geom_component = cos(dir_iid, dir_ood) (方向稳定度,∈[-1,1]→clip[0,1]) |
| score = w_perf*perf + w_geom*geom |
| 返回 {score, perf_component, geom_component}""" |
| |
| # stats/ |
| def bootstrap_ci(values, fn=np.mean, n=1000, alpha=0.05, seed=0) -> tuple[float,float,float]: ... |
| def spearman_with_ci(score, ood_drop, n_boot=1000) -> dict: ... # rho + CI + p |
| def cliffs_delta(a, b) -> float: ... |
| def holm_bonferroni(pvals) -> np.ndarray: ... |
| def benjamini_hochberg(pvals, q=0.05) -> np.ndarray: ... |
| ``` |
|
|
| ### 2.8 pipeline |
|
|
| ```python |
| # stage_extract.py |
| def run_extract(cfg: RunConfig): |
| for model in cfg.models: |
| ext = ActivationExtractor(model, ...) |
| for ds_name in cfg.datasets: |
| base = load_dataset(ds_name, "test", cfg.max_examples_per_dist, seed=0) |
| dists = [base] + [filter_fidelity(s.apply(base), base) for s in shifts] |
| for d in dists: |
| if store.exists(model, ds_name, d.distribution, layer=0): continue # 幂等 |
| ext.extract(d, store, batch_size=cfg.extract_batch[model]) |
| del ext; free_gpu() # 关键:释放当前模型再载下一个 |
| |
| # stage_probe.py / stage_score.py / stage_stats.py 全程只读缓存,CPU/小 GPU 即可 |
| ``` |
|
|
| --- |
|
|
| ## 3. 数据流与缓存格式 |
|
|
| ### 3.1 数据流 |
|
|
| ``` |
| 原始数据集 ──load_dataset──► DistributionSet(iid) |
| │ |
| shift.apply ──┼──► bt_de / domain_x / len_* (候选) |
| │ |
| MNLI fidelity 过滤 ─┘──► label-preserving DistributionSet |
| │ |
| ActivationExtractor(单模型常驻)│ 一次前向抓全层 → pool → fp16 → 流式 |
| ▼ |
| ShardStore 落盘 (阶段1结束) |
| │ (此后 GPU 几乎闲置) |
| fit_and_eval(读缓存) ──────┼──► ProbeResult{acc[dist], direction} |
| ▼ |
| stability.py ──► Score(双分量) |
| ▼ |
| stats ──► Spearman/CI/Holm-BH/Cliff's δ ──► results/*.parquet ──► figures |
| ``` |
|
|
| ### 3.2 缓存目录与 shard 命名 |
|
|
| 分片粒度:`(model, dataset, distribution)` 一组目录,层维拆文件,便于按层流式与按需读取。 |
|
|
| ``` |
| artifacts/cache/ |
| └── {model}/{dataset}/{distribution}/ |
| ├── X_layer{LL}.npy # 每层一个,float16,shape (N, d_model) |
| ├── y.npy # int8, shape (N,) |
| ├── uids.npy # <U32 字符串 id, shape (N,) |
| └── meta.json # {n, n_layers, d_model, pooling, dtype, src_hash, created} |
| ``` |
|
|
| 命名约定: |
|
|
| | 占位符 | 取值示例 | 说明 | |
| |---|---|---| |
| | `{model}` | `pythia-70m`, `gpt2-medium`, `qwen2.5-0.5b` | HF id 安全化 | |
| | `{dataset}` | `sst2`, `ag_news`, `ud_pos` | configs/datasets.yaml key | |
| | `{distribution}` | `iid`, `bt_de`, `domain_books`, `len_long` | iid + shift 产物 | |
| | `{LL}` | `00`..`24` | 层索引零填充两位(含 embedding 层为 0) | |
|
|
| ### 3.3 dtype / shape 约定 |
|
|
| | 数组 | dtype | shape | 备注 | |
| |---|---|---|---| |
| | `X_layer{LL}` | float16 | (N, d_model) | residual-stream pooled;训练时升 float32 | |
| | `y` | int8 | (N,) | 标签;多分类 ≤127 类够用 | |
| | `uids` | <U32 | (N,) | 跨分布对齐(fidelity 后 N 可不同) | |
| | `manifest.parquet` | — | 一行一 shard | 列:model,dataset,distribution,layer,n,d_model,bytes,sha1 | |
| |
| 约定:同一 `(model,dataset)` 下所有 distribution 的 `d_model`、`n_layers` 一致;`X` 列序 = `residual_hook_points` 返回顺序。 |
| |
| --- |
| |
| ## 4. 显存与运行时控制策略 |
| |
| 1. **单模型常驻、串行换模型**:外层循环按 model,处理完所有 dataset/shift 后 `del model; gc.collect(); torch.cuda.empty_cache()` 再载下一个。任一时刻显存只住一个 LM。1.4B 在 fp16 约 2.8 GB 权重,远低于 24 GB。 |
| |
| 2. **激活抽取一律 `torch.inference_mode()` + fp16 autocast**,不建图、不存梯度。一次前向用 hook 抓全层,避免逐层多次前向。 |
| |
| 3. **流式落盘,绝不全量驻留**:每个 batch 抽取→pool 成 (B,D)→cast fp16→`np.memmap` 追加写,显存/内存只持有一个 batch 的激活。pool 后丢弃 (B,T,D) 中间张量。 |
| |
| 4. **batch 自适应降级**:`gpu.py` 包装 OOM 捕获,触发即 `batch//=2` 重试,直到成功;最优 batch 记入 `models.yaml` 复用。`max_len=256` 截断,长样本不爆显存。 |
| |
| 5. **辅助模型(NLLB / DeBERTa-MNLI)单独阶段跑**,与 LM 抽取错峰,跑完即释放;同样 fp16 + batch 流式。 |
| |
| 6. **探针阶段几乎不吃显存**:LogReg/mass-mean 走 CPU(numpy/sklearn);MLP 用小 GPU batch(X 已是 (N,D) 向量,512 batch 占用极小)。可与抽取分进程。 |
| |
| 7. **mmap 读缓存**:`np.load(..., mmap_mode='r')`,大矩阵不一次性进内存;训练时按需切片升 float32。 |
| |
| 8. **幂等跳过**:`store.exists()` 命中即跳过,中断后续跑零浪费;`hashing.py` 用 config+输入指纹做 key。 |
| |
| --- |
| |
| ## 5. 4090 上各阶段运行时估算(目标 ≤30 GPU·h) |
| |
| 规模假设:8 数据集 × (1 IID + 3 shift 各取代表) ≈ 每数据集 ~4 distribution;每 distribution 上限 4000 样本;7 模型;`max_len=256`。 |
| |
| | 阶段 | 主要开销 | GPU·h 估算 | |
| |---|---|---| |
| | **辅助:back-translation (NLLB-600M)** | 8 数据集 × ~4000 × fp16,~往返 2 次 | ~4.0 | |
| | **辅助:MNLI fidelity (DeBERTa-base)** | 仅对 shift 样本,分类一次/样本 | ~1.5 | |
| | **阶段1:激活抽取(7 模型)** | 小模型(70M/160M/410M/gpt2-s/m/qwen0.5b)合计 ~3.5;1.4B 单独 ~3.0;总样本 ~8×4×4000=128k 前向/模型 | ~8.0 | |
| | **阶段2:探针训练+评估** | LogReg/mass-mean 走 CPU(忽略 GPU);MLP 全配置 GPU 小 batch | ~3.0 | |
| | **阶段3:Score 聚合** | 纯 CPU | ~0 | |
| | **阶段4:统计(bootstrap/检验)** | 纯 CPU(可多进程) | ~0 | |
| | **缓冲(重跑/调参/失败重试)** | — | ~5.0 | |
| | **合计** | | **≈ 24.5 GPU·h ✓ ≤30** | |
| |
| 降本旋钮:`max_examples_per_dist` 调到 2000 可再省 ~40% 抽取与翻译时间;shift 数从 3 减到 2;1.4B 仅在子集数据集上跑。 |
| |
| --- |
| |
| ## 6. 复现入口(一条命令跑通 MVE) |
| |
| `configs/experiments/mve.yaml`:`pythia-70m` × `sst2` × (`iid` + `bt_de` 一个 shift) × `{logreg, mass_mean, control}` × `seeds=[0,1]`,`max_examples_per_dist=500`。预计 **< 10 分钟、< 4 GB 显存**。 |
| |
| `scripts/run_mve.sh`: |
| |
| ```bash |
| #!/usr/bin/env bash |
| set -euo pipefail |
| python -m probe_stability.cli run \ |
| --exp configs/experiments/mve.yaml \ |
| --stages extract,probe,score,stats \ |
| --out artifacts/ |
| ``` |
| |
| 一条命令: |
| |
| ```bash |
| bash scripts/run_mve.sh |
| # 等价于 |
| python -m probe_stability.cli run --exp configs/experiments/mve.yaml --stages all |
| ``` |
| |
| 产物:`artifacts/cache/pythia-70m/sst2/{iid,bt_de}/X_layer*.npy`、`artifacts/results/{probe_results,scores,stats}.parquet`、`artifacts/figures/score_vs_drop.png`。 |
| |
| 全量:`python -m probe_stability.cli run --exp configs/experiments/full.yaml --stages all`。 |
| |
| CLI 子命令(便于分阶段重跑、节省 GPU·h): |
| |
| ```bash |
| probe-stability extract --exp ... # 仅写缓存(吃 GPU) |
| probe-stability probe --exp ... # 仅读缓存训探针(几乎不吃 GPU) |
| probe-stability score --exp ... |
| probe-stability stats --exp ... |
| probe-stability verify-cache # 校验分片完整性 |
| ``` |
| |
| --- |
| |
| 关键工程取舍:**抽取与训练彻底解耦**(缓存为界)是 GPU·h 预算可控的核心——GPU 只在阶段1+辅助阶段被占用,探针的多 seed × 多探针 × 多分布组合爆炸全部落在读缓存的 CPU 侧;**单模型常驻串行**保证 1.4B 也安全;**流式 fp16 落盘 + 幂等跳过**让中断可续、零重复计算。如果需要,我可以接着把任意单个模块(如 `activations.py` 的 hook 抽取或 `stability.py` 的 Score 计算)落成可运行代码。 |