这是一个工程架构设计任务,不是 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 #