Download src/extract_embeddings.py from zaaabik/paper_extraction: direct link, hf CLI and curl.
- Browser
- Download file 2.14 kB
-
https://huggingface.co/datasets/zaaabik/paper_extraction/resolve/main/src/extract_embeddings.py
- Command line
-
hf download hf://datasets/zaaabik/paper_extraction/src/extract_embeddings.py
-
curl -L -o extract_embeddings.py https://huggingface.co/datasets/zaaabik/paper_extraction/resolve/main/src/extract_embeddings.py
2.14 kB
| """Penultimate-layer CLS embedding extractor. | |
| Faithful port of ``max_probe_fine_tune_seeds/produce_embeddings.py: | |
| extract_features`` (L77) using the same ``src/utils/pooling.py: | |
| CLSTokenPooling(layer_number=-1)`` semantics, but driven by our YAML | |
| config rather than Hydra. | |
| For each split it writes: | |
| outputs/<cfg>/baselines/<cfg>_embeddings_<split>.pkl | |
| a Python pickle with keys: | |
| features : (N, D) float32 penultimate-layer CLS pooled features | |
| logits : (N, C) float32 classifier logits (matches predictions parquet) | |
| targets : (N,) int64 ground-truth labels | |
| idx : (N,) int64 sample indices (aligned with predictions_<split>.parquet["idx"]) | |
| This format is designed so all downstream baselines (Mahalanobis × 4, | |
| probes) can read it without modification. | |
| """ | |
| from __future__ import annotations | |
| from pathlib import Path | |
| from typing import List, Tuple | |
| import numpy as np | |
| import pandas as pd | |
| import torch | |
| from tqdm import tqdm | |
| def extract_penultimate(model, dataloader, device, pooling): | |
| """Run the model over the dataloader and pool the requested layer. | |
| Uses the seq-classification model head (logits shape (B, C)). | |
| ``pooling`` is a callable with the signature | |
| ``(hidden_states, input_ids, model) -> (B, D)``. | |
| """ | |
| model.eval() | |
| feats, logits, targets = [], [], [] | |
| use_autocast = device.type == "cuda" | |
| for batch in tqdm(dataloader, desc="penultimate-cls"): | |
| ids = batch["input_ids"].to(device) | |
| att = batch["attention_mask"].to(device) | |
| lbl = batch["label"] | |
| with torch.autocast(device_type=device.type, enabled=use_autocast): | |
| out = model(input_ids=ids, attention_mask=att, | |
| output_hidden_states=True, output_attentions=False) | |
| pooled = pooling(out.hidden_states, input_ids=ids, model=model) | |
| feats.append(pooled.float().cpu().numpy()) | |
| logits.append(out.logits.float().cpu().numpy()) | |
| targets.append(lbl.cpu().numpy()) | |
| return ( | |
| np.concatenate(feats, axis=0), | |
| np.concatenate(logits, axis=0), | |
| np.concatenate(targets, axis=0), | |
| ) | |