Download src/cross_features/prep.py from zaaabik/paper_extraction: direct link, hf CLI and curl.
- Browser
- Download file 5.5 kB
-
https://huggingface.co/datasets/zaaabik/paper_extraction/resolve/main/src/cross_features/prep.py
- Command line
-
hf download hf://datasets/zaaabik/paper_extraction/src/cross_features/prep.py
-
curl -L -o prep.py https://huggingface.co/datasets/zaaabik/paper_extraction/resolve/main/src/cross_features/prep.py
5.5 kB
| """PReP — Perturbation-Robustness Probes (Phase 4, idx 10). | |
| Run K=16 noisy forward passes per sample with Gaussian noise injected | |
| on the input embeddings: e_k = e_0 + σ · N(0, I) where σ = SIGMA_REL · | |
| ‖e_0‖ / √(numel(e_0)). Collect anchor-layer [CLS] hidden states | |
| Z_l = {z_l^(k)}_{k=0}^{15} for l ∈ {0, 4, 8, 12} and summarise: | |
| per-anchor: | |
| effective rank of cov(Z_l) (1) | |
| mean displacement from clean (1) | |
| cross-anchor (4 layer pairs × 18 Ripser scalars): | |
| persistence on the 16×16 distance matrix between perturbations | |
| at each anchor pair (4 × 18 = 72) | |
| Output dim = 4·2 + 4·18 = 80. | |
| Memory: noise is shared across the batch, so the per-batch cost is | |
| roughly 16 × (one forward). Disables ``torch.no_grad`` is unnecessary — | |
| forwards are pure inference. | |
| """ | |
| from __future__ import annotations | |
| import numpy as np | |
| import torch | |
| from .persistence_summary import ripser_summary_from_distance, column_names as pcol | |
| ANCHORS = [0, 4, 8, 12] | |
| K = 16 | |
| SIGMA_REL = 0.05 | |
| def _columns(): | |
| cols = [] | |
| for l in ANCHORS: | |
| cols.append(f"prep_L{l}_effrank") | |
| cols.append(f"prep_L{l}_displacement") | |
| for k in range(len(ANCHORS)): | |
| cols.extend(pcol(f"prep_anchor{ANCHORS[k]}")) | |
| return cols | |
| COLUMNS = _columns() | |
| DIM = len(COLUMNS) | |
| def _input_embed_module(model): | |
| if hasattr(model, "roberta"): | |
| return model.roberta.embeddings | |
| if hasattr(model, "electra"): | |
| return model.electra.embeddings | |
| return model.embeddings | |
| def _forward_with_embedding_noise(model, ids, att, noise, anchors_set): | |
| """Single forward with noise added on input embeddings; capture anchor outputs.""" | |
| emb_mod = _input_embed_module(model) | |
| captured = {} | |
| handles = [] | |
| def make_hook(l_idx, label): | |
| def fn(module, inputs, output): | |
| if isinstance(output, tuple): output = output[0] | |
| captured[label] = output.detach().clone() | |
| return fn | |
| # Intercept the embedding output and add noise | |
| def emb_post_hook(module, inputs, output): | |
| return output + noise | |
| handles.append(emb_mod.register_forward_hook(emb_post_hook)) | |
| # Capture anchor layer outputs (using HF's hidden_states convention) | |
| # We use the encoder's per-layer hook (covers anchors > 0). | |
| if hasattr(model, "roberta"): | |
| encoder_layers = model.roberta.encoder.layer | |
| elif hasattr(model, "electra"): | |
| encoder_layers = model.electra.encoder.layer | |
| else: | |
| encoder_layers = model.encoder.layer | |
| for l in anchors_set: | |
| if l == 0: | |
| # anchor 0 == embedding output | |
| handles.append(emb_mod.register_forward_hook(make_hook(l, l))) | |
| else: | |
| handles.append(encoder_layers[l - 1].register_forward_hook(make_hook(l, l))) | |
| try: | |
| _ = model(input_ids=ids, attention_mask=att, return_dict=True) | |
| finally: | |
| for h in handles: h.remove() | |
| return captured | |
| def extract_prep(model, input_ids, attention_mask, cache, pred_label=None): | |
| """Return (features (B, 80), columns).""" | |
| device = input_ids.device | |
| B = input_ids.shape[0] | |
| feats = np.zeros((B, DIM), dtype=np.float32) | |
| emb_mod = _input_embed_module(model) | |
| # Clean embedding to scale noise | |
| with torch.no_grad(): | |
| e0 = emb_mod(input_ids) # (B, T, D) | |
| sigma = SIGMA_REL * e0.norm() / float(np.sqrt(e0.numel())) | |
| # Anchors → list of (K+1) (B, T, D) tensors at each anchor | |
| anchors_set = set(ANCHORS) | |
| # Clean pass: anchor states | |
| clean = _forward_with_embedding_noise(model, input_ids, attention_mask, | |
| noise=torch.zeros_like(e0), | |
| anchors_set=anchors_set) | |
| # Noisy passes | |
| perturbed = {l: [] for l in ANCHORS} | |
| for k in range(K): | |
| noise = sigma * torch.randn_like(e0) | |
| cap = _forward_with_embedding_noise(model, input_ids, attention_mask, | |
| noise=noise, anchors_set=anchors_set) | |
| for l in ANCHORS: | |
| perturbed[l].append(cap[l][:, 0, :].cpu().numpy()) # (B, D) | |
| # Per-sample features | |
| for b in range(B): | |
| for ai, l in enumerate(ANCHORS): | |
| # Z_l: (K, D) at sample b | |
| Z = np.stack([perturbed[l][k][b] for k in range(K)], axis=0) | |
| clean_b = clean[l][b, 0, :].cpu().numpy() | |
| # Effective rank of cov(Z) | |
| Zc = Z - Z.mean(axis=0, keepdims=True) | |
| cov = Zc.T @ Zc / max(K - 1, 1) | |
| try: | |
| sv = np.linalg.svd(cov, compute_uv=False) | |
| p = sv / (sv.sum() + 1e-12) | |
| eff_rank = float(np.exp(-(p * np.log(p + 1e-12)).sum())) | |
| except np.linalg.LinAlgError: | |
| eff_rank = 0.0 | |
| displacement = float(np.linalg.norm(Z - clean_b[None, :], axis=1).mean()) | |
| feats[b, ai * 2 + 0] = eff_rank | |
| feats[b, ai * 2 + 1] = displacement | |
| # Persistence on the K×K distance matrix of perturbations at anchor l | |
| Zn = Z / (np.linalg.norm(Z, axis=1, keepdims=True) + 1e-12) | |
| cos = Zn @ Zn.T | |
| D = 1.0 - cos | |
| np.fill_diagonal(D, 0.0) | |
| pers, _ = ripser_summary_from_distance(D, maxdim=1, | |
| prefix=f"prep_anchor{l}") | |
| base = len(ANCHORS) * 2 + ai * 18 | |
| feats[b, base : base + 18] = pers | |
| return feats, COLUMNS | |