Download scripts/05_extract_streaming.py from zaaabik/paper_extraction: direct link, hf CLI and curl.
- Browser
- Download file 9.21 kB
-
https://huggingface.co/datasets/zaaabik/paper_extraction/resolve/main/scripts/05_extract_streaming.py
- Command line
-
hf download hf://datasets/zaaabik/paper_extraction/scripts/05_extract_streaming.py
-
curl -L -o 05_extract_streaming.py https://huggingface.co/datasets/zaaabik/paper_extraction/resolve/main/scripts/05_extract_streaming.py
9.21 kB
| #!/usr/bin/env python3 | |
| """Extract attention features without ever storing the full attention set. | |
| Stages 01 and 02 are split: 01 dumps one (L, H, T, T) tensor per sample to | |
| disk, 02 reads them back. That costs ~50 GB per configuration and ~60 GB for | |
| a Yelp-sized split, and it is what makes substantially longer sequence lengths | |
| impractical. | |
| This script fuses them. Samples are processed in chunks: a chunk's attention | |
| is materialised, every family is computed from it, and the tensors are | |
| discarded before the next chunk. Peak attention on disk is CHUNK samples | |
| rather than the whole split, so the cost is bounded by --chunk and not by | |
| the dataset. | |
| The family extractors are called unmodified, on the same inputs in the same | |
| order, so the output files are identical to the two-stage pipeline. Verify | |
| with --verify-against, which compares against an existing extraction. | |
| python extraction/scripts/05_extract_streaming.py --config <cfg.yaml> | |
| python extraction/scripts/05_extract_streaming.py --config <cfg.yaml> \ | |
| --chunk 128 --scratch /dev/shm/attn | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import shutil | |
| import sys | |
| import time | |
| from pathlib import Path | |
| import numpy as np | |
| import pandas as pd | |
| import torch | |
| ROOT = Path(__file__).resolve().parents[1] | |
| sys.path.insert(0, str(ROOT)) | |
| sys.path.insert(0, str(ROOT.parent)) | |
| from src.utils import load_config, seed_everything, device_from_cfg, ensure_dir | |
| from src.load_data import load_splits | |
| from src.load_model import load_classification_model, move | |
| from src.extract_attention import _build_dataloader | |
| from src.family_specs import write_family_file | |
| M2 = ("graph", "ripser", "template") | |
| TOKTOPO = ("toktopo_pd", "toktopo_graph") | |
| def _dump_chunk(model, batch_texts, tokenizer, cfg, device, scratch: Path, | |
| idxs: list[int]) -> None: | |
| """Run the encoder over one chunk and write its attention to scratch.""" | |
| scratch.mkdir(parents=True, exist_ok=True) | |
| loader = _build_dataloader(batch_texts, tokenizer, cfg["data"]["text_col"], | |
| cfg["data"]["label_col"], cfg["model"]["max_length"], | |
| cfg["inference"]["batch_size"]) | |
| pos = 0 | |
| with torch.no_grad(): | |
| for batch in loader: | |
| out = model(input_ids=batch["input_ids"].to(device), | |
| attention_mask=batch["attention_mask"].to(device), | |
| output_attentions=True) | |
| attn = torch.stack(out.attentions, dim=1).cpu().numpy().astype(np.float16) | |
| for b in range(attn.shape[0]): | |
| seq = int(batch["attention_mask"][b].sum().item()) | |
| np.savez_compressed(scratch / f"{idxs[pos]:06d}.npz", | |
| attn=attn[b, :, :, :seq, :seq], seq_len=seq) | |
| pos += 1 | |
| def main() -> None: | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--config", required=True) | |
| ap.add_argument("--splits", nargs="+", default=["train", "validation", "test"]) | |
| ap.add_argument("--chunk", type=int, default=512, | |
| help="samples whose attention is on disk at once") | |
| ap.add_argument("--workers", type=int, default=8) | |
| ap.add_argument("--scratch", type=Path, default=None, | |
| help="where chunk attention goes (default: <output_dir>/_chunk)") | |
| ap.add_argument("--force", action="store_true", | |
| help="recompute a split even if its family files exist") | |
| ap.add_argument("--verify-against", type=Path, default=None, | |
| help="an existing outputs/<cfg> dir; compare features and exit") | |
| args = ap.parse_args() | |
| cfg = load_config(args.config) | |
| seed_everything(cfg["seed"]) | |
| cfg_name = cfg["run_name"] | |
| out_dir = ensure_dir(cfg["paths"]["output_dir"]) | |
| ensure_dir(out_dir / "features") | |
| device = device_from_cfg(cfg) | |
| scratch = args.scratch or (out_dir / "_chunk") | |
| splits_data = load_splits(cfg) | |
| model, tokenizer = load_classification_model( | |
| cfg["model"]["pretrained_path"], num_labels=cfg["model"].get("num_labels"), | |
| base_tokenizer=cfg["model"].get("base_tokenizer"), | |
| do_lower_case=cfg["model"].get("do_lower_case"), | |
| is_peft=cfg["model"].get("is_peft", False), | |
| base_model=cfg["model"].get("base_model")) | |
| model = move(model, device).eval() | |
| from src.extract_topological_features import recompute_from_attention | |
| # reuse stage 02's array reshaping so both paths flatten identically | |
| from importlib.util import spec_from_file_location, module_from_spec | |
| _sp = spec_from_file_location("_s02", Path(__file__).parent / "02_extract_features.py") | |
| _s02 = module_from_spec(_sp); _sp.loader.exec_module(_s02) | |
| _split_topology_arrays = _s02._split_topology_arrays | |
| from src.extract_toktopo import compute_toktopo | |
| from src.extract_intra_attn_features import compute_intra_attn_features | |
| from src.extract_punct_dist import compute_punct_dist | |
| STREAM_FAMILIES = ["ripser", "template", "graph", "toktopo_pd", "toktopo_graph", | |
| "intra_attn", "punct"] | |
| for split in args.splits: | |
| # A split is written only once all of its families are computed, so a | |
| # complete set of family files means the split finished; an interrupted | |
| # run resumes at the first split that has none. | |
| done = [(out_dir / "features" / f"{cfg_name}_{fam}_{split}.npz").exists() | |
| for fam in STREAM_FAMILIES] | |
| if all(done) and not args.force: | |
| print(f"[skip] {split}: streamed families already present", flush=True) | |
| continue | |
| preds = pd.read_parquet(out_dir / f"predictions_{split}.parquet") | |
| idxs = preds["idx"].tolist() | |
| raw = splits_data[split].reset_index(drop=True) | |
| raw_m = raw.loc[raw["idx"].isin(idxs)].set_index("idx").loc[idxs].reset_index() | |
| N = len(idxs) | |
| acc: dict[str, list] = {} | |
| cols: dict[str, list] = {} | |
| t0 = time.time() | |
| for s in range(0, N, args.chunk): | |
| e = min(s + args.chunk, N) | |
| sub_idx = idxs[s:e] | |
| shutil.rmtree(scratch, ignore_errors=True) | |
| _dump_chunk(model, raw_m.iloc[s:e], tokenizer, cfg, device, scratch, sub_idx) | |
| g, r, t = recompute_from_attention(scratch, sub_idx, n_workers=args.workers) | |
| (rip, rc), (tem, tc), (grp, gc) = _split_topology_arrays(g, r, t, len(sub_idx)) | |
| for fam, arr, c in (("ripser", rip, rc), ("template", tem, tc), ("graph", grp, gc)): | |
| acc.setdefault(fam, []).append(arr); cols[fam] = c | |
| tt, tcols = compute_toktopo(scratch, sub_idx, n_workers=args.workers, max_dim=1) | |
| acc.setdefault("_toktopo", []).append(tt); cols["_toktopo"] = tcols | |
| ia, iac = compute_intra_attn_features(scratch, sub_idx, device=device) | |
| acc.setdefault("intra_attn", []).append(ia); cols["intra_attn"] = iac | |
| pu, puc = compute_punct_dist(scratch, tokenizer, cfg["model"]["max_length"], | |
| raw_m.iloc[s:e].reset_index(drop=True), | |
| cfg["data"]["text_col"], n_workers=args.workers) | |
| acc.setdefault("punct", []).append(pu); cols["punct"] = puc | |
| shutil.rmtree(scratch, ignore_errors=True) | |
| print(f" [{split}] {e}/{N} ({time.time()-t0:.0f}s)", flush=True) | |
| # split the pooled toktopo block into its two families, as stage 02 does | |
| tt = np.concatenate(acc.pop("_toktopo"), axis=0); tcols = cols.pop("_toktopo") | |
| pd_cols = [i for i, c in enumerate(tcols) if c.startswith("toktopo_h")] | |
| gr_cols = [i for i, c in enumerate(tcols) | |
| if not c.startswith("toktopo_h") and "_xbc_" not in c] | |
| write_family_file(out_dir, cfg_name, "toktopo_pd", split, | |
| tt[:, pd_cols], [tcols[i] for i in pd_cols], idxs) | |
| write_family_file(out_dir, cfg_name, "toktopo_graph", split, | |
| tt[:, gr_cols], [tcols[i] for i in gr_cols], idxs) | |
| for fam, parts in acc.items(): | |
| write_family_file(out_dir, cfg_name, fam, split, | |
| np.concatenate(parts, axis=0), cols[fam], idxs) | |
| print(f"[{split}] {N} samples, peak attention on disk = {args.chunk} " | |
| f"({time.time()-t0:.0f}s)", flush=True) | |
| if args.verify_against: | |
| ok = True | |
| for split in args.splits: | |
| for fam in list(M2) + list(TOKTOPO) + ["intra_attn", "punct"]: | |
| a = out_dir / "features" / f"{cfg_name}_{fam}_{split}.npz" | |
| b = args.verify_against / "features" / f"{cfg_name}_{fam}_{split}.npz" | |
| if not b.exists(): | |
| continue | |
| x = np.load(a, allow_pickle=True)["features"] | |
| y = np.load(b, allow_pickle=True)["features"] | |
| same = x.shape == y.shape and np.allclose(x, y, rtol=1e-5, atol=1e-6, | |
| equal_nan=True) | |
| ok &= same | |
| print(f" {'OK ' if same else 'DIFF'} {fam}_{split} {x.shape}") | |
| print("VERIFY", "PASS" if ok else "FAIL") | |
| if __name__ == "__main__": | |
| main() | |