Download code/set4_goldfish_lib.py from Cross-Mergeability/compose-audit: direct link, hf CLI and curl.
- Browser
- Download file 1.09 kB
-
https://huggingface.co/datasets/Cross-Mergeability/compose-audit/resolve/main/code/set4_goldfish_lib.py
- Command line
-
hf download hf://datasets/Cross-Mergeability/compose-audit/code/set4_goldfish_lib.py
-
curl -L -o set4_goldfish_lib.py https://huggingface.co/datasets/Cross-Mergeability/compose-audit/resolve/main/code/set4_goldfish_lib.py
1.09 kB
| """Shared with set4_goldfish.py: cross-lingual sentence-level activations.""" | |
| import sys | |
| sys.path.insert(0,"/root/compose-audit") | |
| from common import * | |
| 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)} | |