File size: 1,087 Bytes
47a719e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
"""Shared with set4_goldfish.py: cross-lingual sentence-level activations."""
import sys
sys.path.insert(0,"/root/compose-audit")
from common import *

@torch.no_grad()
def sent_acts(model, tok, lines, dev, bs=16, maxlen=128):
    """Mean-pooled per-sentence residual activations, {layer: (n_sent, d)} -- rows are matched
    ACROSS LANGUAGES by FLORES sentence id, which is what makes a cross-lingual basis map fittable."""
    outs = None
    for i in range(0, len(lines), bs):
        enc = tok(lines[i:i + bs], return_tensors="pt", padding=True, truncation=True, max_length=maxlen)
        ids = enc["input_ids"].to(dev); am = enc["attention_mask"].to(dev).float()
        hs = model(ids, attention_mask=enc["attention_mask"].to(dev), output_hidden_states=True).hidden_states
        if outs is None:
            outs = [[] for _ in hs]
        w = am / am.sum(1, keepdim=True).clamp(min=1)
        for j, h in enumerate(hs):
            outs[j].append((h.float() * w.unsqueeze(-1)).sum(1).cpu())
    return {j: torch.cat(o).numpy().astype(np.float64) for j, o in enumerate(outs)}