Download src/extract_punct_dist.py from zaaabik/paper_extraction: direct link, hf CLI and curl.
- Browser
- Download file 6.63 kB
-
https://huggingface.co/datasets/zaaabik/paper_extraction/resolve/main/src/extract_punct_dist.py
- Command line
-
hf download hf://datasets/zaaabik/paper_extraction/src/extract_punct_dist.py
-
curl -L -o extract_punct_dist.py https://huggingface.co/datasets/zaaabik/paper_extraction/resolve/main/src/extract_punct_dist.py
6.63 kB
| """Punctuation-graph-distance features. | |
| For each sample, build the per-layer co-attention token graph | |
| G_l(t1, t2) = mean over heads of attention from t1 to t2 | |
| and treat its row-stochastic dual as a directed weighted graph. We compute | |
| the shortest-path "attention distance" from every token t to the nearest | |
| punctuation token, where edge weight is | |
| w(t1, t2) = -log( max(G_l(t1, t2), eps) ) | |
| This is the standard negative-log transformation that turns multiplicative | |
| attention chains into additive distances --- the same trick used for | |
| attention flow / attention rollout, applied here to discover discourse | |
| boundaries via punctuation as anchors. | |
| For each layer l, we extract per-sample statistics of {dist(t, punct) : t}: | |
| mean, std, min, max, fraction with finite distance, median. We also | |
| extract the same statistics for distance to special tokens (CLS = position 0; | |
| SEP = last non-padded position) and the cross-layer std of the | |
| mean-distance-to-punct trajectory. | |
| Pure attention/tokenizer-derived; no class softmax used. | |
| """ | |
| from __future__ import annotations | |
| from pathlib import Path | |
| from typing import List, Tuple | |
| import numpy as np | |
| import torch | |
| from scipy.sparse import csr_matrix | |
| from scipy.sparse.csgraph import shortest_path | |
| from tqdm import tqdm | |
| PUNCT_CHARS = set(".,;:!?\"'`()[]{}-—–…") | |
| def _punct_token_ids(tokenizer) -> set: | |
| out = set() | |
| vocab = tokenizer.get_vocab() | |
| for tok, idx in vocab.items(): | |
| s = tok.replace("##", "").replace("Ġ", "").replace("▁", "") | |
| if s and all(c in PUNCT_CHARS for c in s): | |
| out.add(idx) | |
| return out | |
| def _shortest_path_to_set(D: np.ndarray, anchors: np.ndarray) -> np.ndarray: | |
| """Dijkstra: for each row return min over anchors of shortest-path distance. | |
| D is a (T, T) directed weighted adjacency where row i has the out-edge | |
| weights from node i. anchors is a boolean (T,) mask. | |
| Returns a (T,) array of distances; np.inf for unreachable. | |
| """ | |
| sp = shortest_path(csr_matrix(D), directed=True, return_predecessors=False) | |
| # sp[i, j] = shortest dist i -> j | |
| if anchors.sum() == 0: | |
| return np.full(D.shape[0], np.inf, dtype=np.float32) | |
| return sp[:, anchors].min(axis=1).astype(np.float32) | |
| def _stats(v: np.ndarray) -> np.ndarray: | |
| finite = v[np.isfinite(v)] | |
| if len(finite) == 0: | |
| return np.zeros(6, dtype=np.float32) | |
| return np.array([ | |
| float(finite.mean()), float(finite.std()), | |
| float(finite.min()), float(finite.max()), | |
| float(np.median(finite)), | |
| float(len(finite) / max(len(v), 1)), | |
| ], dtype=np.float32) | |
| def _process_one(args): | |
| attn_path, punct_mask, T_sample = args | |
| with np.load(attn_path, allow_pickle=True) as d: | |
| A = np.asarray(d["attn"]).astype(np.float32) | |
| T_a = int(d.get("seq_len", A.shape[-1])) | |
| A = A[:, :, :T_a, :T_a] | |
| L, _, _, _ = A.shape | |
| T = min(T_a, T_sample) | |
| pmask = punct_mask[:T].astype(bool) | |
| if pmask.sum() == 0: | |
| # No punctuation: return zeros (matches normal output dim = L*6*2 + 4) | |
| return np.zeros(L * 6 * 2 + 4, dtype=np.float32) | |
| # CLS = 0, SEP = T - 1 (RoBERTa/ELECTRA convention) | |
| cls_mask = np.zeros(T, dtype=bool); cls_mask[0] = True | |
| sep_mask = np.zeros(T, dtype=bool); sep_mask[T - 1] = True | |
| feats: List[float] = [] | |
| dist_means_per_layer = [] | |
| for l in range(L): | |
| G = A[l].mean(axis=0)[:T, :T] | |
| eps = 1e-6 | |
| # Edge weight = -log(G); zero G → inf weight (no edge) | |
| W = -np.log(np.clip(G, eps, 1.0)) | |
| # Zero-out self-loops by setting them to a large finite value (not 0 which means no edge) | |
| np.fill_diagonal(W, 0.0) | |
| # Compute shortest-path distance from every token to nearest punctuation | |
| try: | |
| d_punct = _shortest_path_to_set(W, pmask) | |
| d_cls = _shortest_path_to_set(W, cls_mask) | |
| except Exception: | |
| feats.extend([0.0]*12); dist_means_per_layer.append(0.0); continue | |
| feats.extend(_stats(d_punct).tolist()) | |
| feats.extend(_stats(d_cls).tolist()) | |
| # mean dist to punct, used for cross-layer std | |
| finite = d_punct[np.isfinite(d_punct)] | |
| dist_means_per_layer.append(float(finite.mean()) if len(finite) else 0.0) | |
| # Cross-layer std of mean dist-to-punct | |
| dl = np.asarray(dist_means_per_layer, dtype=np.float32) | |
| cross_std = float(dl.std()) if len(dl) > 0 else 0.0 | |
| cross_mean = float(dl.mean()) if len(dl) > 0 else 0.0 | |
| cross_min = float(dl.min()) if len(dl) > 0 else 0.0 | |
| cross_max = float(dl.max()) if len(dl) > 0 else 0.0 | |
| feats.append(cross_std) | |
| feats.append(cross_mean) | |
| feats.append(cross_min) | |
| feats.append(cross_max) | |
| return np.array(feats, dtype=np.float32) | |
| def compute_punct_dist( | |
| attn_dir: Path, tokenizer, model_max_length: int, | |
| df, text_col: str, n_workers: int = 1, | |
| ) -> Tuple[np.ndarray, List[str]]: | |
| """Return per-sample feature matrix (N, 12*L + 4).""" | |
| punct_ids = _punct_token_ids(tokenizer) | |
| rows = [] | |
| iterable = df.reset_index(drop=True) | |
| # Layer count from the attention dumps, not assumed to be 12. | |
| with np.load(Path(attn_dir) / f"{int(iterable.iloc[0]['idx']):06d}.npz") as _z: | |
| L = int(_z["attn"].shape[0]) | |
| # Pre-tokenize to get per-sample punctuation masks | |
| args_list = [] | |
| for i, r in tqdm(iterable.iterrows(), total=len(iterable), desc="punct-dist tokenize"): | |
| idx = int(r["idx"]) | |
| 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=bool) | |
| T_sample = len(ids) | |
| args_list.append((attn_dir / f"{idx:06d}.npz", is_punct, T_sample)) | |
| if n_workers <= 1: | |
| rows = [_process_one(a) for a in tqdm(args_list, desc="punct-dist")] | |
| else: | |
| from multiprocessing import Pool | |
| with Pool(processes=n_workers) as pool: | |
| rows = list(tqdm(pool.imap(_process_one, args_list, chunksize=8), | |
| total=len(args_list), desc=f"punct-dist[{n_workers}w]")) | |
| arr = np.stack(rows, axis=0) | |
| cols = [] | |
| for l in range(L): | |
| for st in ("mean", "std", "min", "max", "median", "finite_frac"): | |
| cols.append(f"punctD_d2p_{st}_L{l}") | |
| for st in ("mean", "std", "min", "max", "median", "finite_frac"): | |
| cols.append(f"punctD_d2c_{st}_L{l}") | |
| cols.extend(["punctD_crossL_std", "punctD_crossL_mean", | |
| "punctD_crossL_min", "punctD_crossL_max"]) | |
| return arr, cols | |