File size: 2,143 Bytes
55d72e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
"""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


@torch.no_grad()
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),
    )