"""Punctuation-template attention feature (Kostenok et al. 2024 §D). For each sample we identify punctuation token positions via the tokenizer and build a per-sample template mask T_mask[i, j] = 1 if token j is a punctuation token, 0 otherwise. We then compute, per (layer, head): feature = 1 - sum(attn * T_mask) / sum(T_mask) which is small when the head attends strongly to punctuation tokens and ~1 when the head ignores them. """ from __future__ import annotations from pathlib import Path from typing import List, Tuple import numpy as np import torch from torch.utils.data import DataLoader from tqdm import tqdm PUNCT_CHARS = set(".,;:!?\"'`()[]{}-—–…") def _punct_token_ids(tokenizer) -> set: """All token IDs whose decoded text is a punctuation-only string.""" out = set() vocab = tokenizer.get_vocab() for tok, idx in vocab.items(): # Decode the single token; strip BERT/RoBERTa's space/##/Ġ markers s = tok.replace("##", "").replace("Ġ", "").replace("▁", "") if s and all(c in PUNCT_CHARS for c in s): out.add(idx) return out @torch.no_grad() def compute_punct_template(attn_dir: Path, tokenizer, model_max_length: int, df, text_col: str) -> Tuple[np.ndarray, List[str]]: L, H = 12, 12 punct_ids = _punct_token_ids(tokenizer) rows = [] for _, r in tqdm(df.reset_index(drop=True).iterrows(), total=len(df), desc="punct-template"): idx = int(r["idx"]) # Re-tokenize to get per-token IDs for this sample enc = tokenizer(r[text_col], truncation=True, max_length=model_max_length, padding="max_length", return_tensors="pt") ids = enc["input_ids"][0].tolist() is_punct = np.array([tid in punct_ids for tid in ids], dtype=np.float32) # (T,) if is_punct.sum() == 0: # No punctuation tokens — feature defaults to 1.0 rows.append(np.ones(L * H, dtype=np.float32)) continue # Build template mask: every row attends to every punctuation position T = is_punct.shape[0] T_mask = np.tile(is_punct[None, :], (T, 1)) # (T, T) denom = float(T_mask.sum()) # Load attention dump path = attn_dir / f"{idx:06d}.npz" with np.load(path, allow_pickle=True) as d: A = np.asarray(d["attn"]).astype(np.float32) # (L, H, T_attn, T_attn) T_attn = A.shape[-1] T_mask = T_mask[:T_attn, :T_attn] denom = float(T_mask.sum()) if denom <= 0: rows.append(np.ones(L * H, dtype=np.float32)) continue feats = np.zeros(L * H, dtype=np.float32) for l in range(L): for h in range(H): feats[l * H + h] = 1.0 - float((A[l, h] * T_mask).sum() / denom) rows.append(feats) arr = np.stack(rows, axis=0).astype(np.float32) cols = [f"punct_L{l}H{h}" for l in range(L) for h in range(H)] return arr, cols