File size: 16,534 Bytes
55d72e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
"""Phase 2 — extract all feature families for one config × all splits.

Writes per-family files to:
  outputs/<cfg>/features/<cfg>_<family>_<split>.npz

Each .npz contains:
  features  (N, D)     float32
  columns   (D,)       object  (feature names)
  idx       (N,)       int64   (aligned with predictions_<split>.parquet["idx"])

Families produced (17 total):
  Single-v1 base:
    ripser, template, graph, toktopo_pd, toktopo_graph, intra_attn,
    punct, cls_last, cls_mid, cls_begin
  PCB-JS extra:
    js_morepairs                         (stratified-3 layers {1,6,11})
  PCB-Best candidates:
    ai_morepairs                         (stratified-3 layers {1,6,11})
    ai_s4                                (stratified-4 layers {0,4,8,11})
    plcross, swpd, cbh1                  (last-2 layers {10,11})
    toktopo_xbc                          (4 hand-picked layer pairs)

Idempotent: each family file is skipped if it already exists. Use
``--force`` to re-extract everything; ``--families a b c`` to extract a
subset only.
"""
from __future__ import annotations

import argparse
import sys
import time
from pathlib import Path
from typing import List, Tuple

import numpy as np
import pandas as pd
import torch

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))

from src.utils import load_config, seed_everything, device_from_cfg, ensure_dir
from src.load_data import load_splits
from src.family_specs import (
    ALL_FAMILIES, SINGLE_V1, PCB_JS_EXTRA, PCB_BEST_CANDIDATES,
    PAIR_STRATEGY, file_for, write_family_file,
)


# ---------------------------------------------------------------------------
# Family extractor implementations
# ---------------------------------------------------------------------------
def _need(out_dir, cfg_name, split, family_list, force):
    """Return the subset of families whose file is missing (or force=True)."""
    missing = []
    for f in family_list:
        p = file_for(out_dir, cfg_name, f, split)
        if force or not p.exists():
            missing.append(f)
    return missing


def _split_topology_arrays(graph_arr, ripser_arr, template_arr, n_samples):
    """Take the (L, H, ...) arrays returned by recompute_from_attention,
    flatten the per-head feature axis to per-sample feature vectors, and
    return three (N, D) feature matrices with proper column names."""
    # ripser  shape (L, H, N, 14)  -> per-sample (L*H*14,)
    L, H, N, R = ripser_arr.shape
    assert N == n_samples
    ripser_flat = np.moveaxis(ripser_arr, 2, 0).reshape(N, L * H * R)
    ripser_cols = [f"ripser_L{l}H{h}_s{s}" for l in range(L) for h in range(H) for s in range(R)]
    # template shape (L, H, 7, N)
    L, H, T, N2 = template_arr.shape
    assert N2 == n_samples
    template_flat = np.moveaxis(template_arr, -1, 0).reshape(N2, L * H * T)
    template_cols = [f"template_L{l}H{h}_t{t}" for l in range(L) for h in range(H) for t in range(T)]
    # graph    shape (L, H, 9, N, 6)
    L, H, G, N3, K = graph_arr.shape
    assert N3 == n_samples
    graph_flat = np.moveaxis(graph_arr, 3, 0).reshape(N3, L * H * G * K)
    graph_cols = [f"graph_L{l}H{h}_g{g}_k{k}" for l in range(L) for h in range(H)
                  for g in range(G) for k in range(K)]
    return (ripser_flat, ripser_cols), (template_flat, template_cols), (graph_flat, graph_cols)


def _split_by_prefix(features, columns, name_to_prefix):
    """Split features into multiple per-family groups by column-name prefix
    matching. Returns {family: (sub_features, sub_columns)}."""
    cols_arr = np.array(columns, dtype=object)
    out = {}
    for fam, prefix_test in name_to_prefix.items():
        mask = np.array([prefix_test(c) for c in cols_arr])
        if mask.any():
            out[fam] = (features[:, mask], [c for c, k in zip(columns, mask) if k])
        else:
            out[fam] = (np.zeros((features.shape[0], 0), dtype=np.float32), [])
    return out


# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------
def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--config", required=True)
    ap.add_argument("--splits", nargs="+", default=["train", "validation", "test"])
    ap.add_argument("--families", nargs="+", default=None,
                    help="Families to extract. Default: SINGLE_V1, the ten families "
                         "that 03_stage_features.py stages and AttnTopo is built "
                         "from. Pass 'all' for every family in the repository, "
                         "including the 41 exploratory ones nothing consumes.")
    ap.add_argument("--force", action="store_true",
                    help="Re-extract even if family file already exists")
    ap.add_argument("--workers", type=int, default=8)
    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"])
    feat_dir = ensure_dir(out_dir / "features")
    device = device_from_cfg(cfg)
    # Default to the families that are actually staged and used. ALL_FAMILIES
    # carries 41 more -- cross-barcode, pairwise interaction, and other
    # exploratory groups -- which 03_stage_features.py does not stage and no
    # module reads. Computing them added roughly 3.5 h per 20-NG configuration
    # and 13 h per Yelp configuration for output nothing consumes.
    if args.families == ["all"]:
        target_families = ALL_FAMILIES
    else:
        target_families = args.families or SINGLE_V1

    splits_data = load_splits(cfg)
    print(f"[{cfg_name}] target families={target_families}  splits={args.splits}")

    # ------------------------- M2 topology -----------------------------
    M2_FAMS = ["ripser", "template", "graph"]
    if any(f in target_families for f in M2_FAMS):
        from src.extract_topological_features import recompute_from_attention
        rec_dir = ensure_dir(out_dir / "recomputed")
        for split in args.splits:
            missing = _need(out_dir, cfg_name, split,
                            [f for f in M2_FAMS if f in target_families], args.force)
            if not missing:
                print(f"  [skip-m2 {split}] all M2 family files exist"); continue
            df = pd.read_parquet(out_dir / f"predictions_{split}.parquet")
            idxs = df["idx"].tolist(); N = len(idxs)
            attn_dir = out_dir / "attention" / split
            cache_ripser = rec_dir / f"{split}_ripser.npy"
            cache_temp   = rec_dir / f"{split}_template.npy"
            cache_graph  = rec_dir / f"{split}_s_w_e_v_c_b0b1_m_k_lists_array_6.npy"
            if cache_ripser.exists() and cache_temp.exists() and cache_graph.exists() and not args.force:
                ripser_arr = np.load(cache_ripser); template_arr = np.load(cache_temp); graph_arr = np.load(cache_graph)
                print(f"  [m2 {split}] using cached recomputed/*.npy")
            else:
                t0 = time.time()
                print(f"  [m2 {split}] recompute from attention ({N} samples, {args.workers}w)")
                graph_arr, ripser_arr, template_arr = recompute_from_attention(
                    attn_dir, idxs, n_workers=args.workers)
                np.save(cache_ripser, ripser_arr); np.save(cache_temp, template_arr); np.save(cache_graph, graph_arr)
                print(f"  [m2 {split}] done in {time.time()-t0:.1f}s")
            (rip, rcols), (tem, tcols), (grp, gcols) = _split_topology_arrays(
                graph_arr, ripser_arr, template_arr, N)
            if "ripser" in missing:
                write_family_file(out_dir, cfg_name, "ripser", split, rip, rcols, idxs)
                print(f"    wrote ripser_{split}.npz  {rip.shape}")
            if "template" in missing:
                write_family_file(out_dir, cfg_name, "template", split, tem, tcols, idxs)
                print(f"    wrote template_{split}.npz  {tem.shape}")
            if "graph" in missing:
                write_family_file(out_dir, cfg_name, "graph", split, grp, gcols, idxs)
                print(f"    wrote graph_{split}.npz  {grp.shape}")

    # ------------------------- toktopo (PD + graph + xbc) ----------------
    TT_FAMS = ["toktopo_pd", "toktopo_graph", "toktopo_xbc"]
    if any(f in target_families for f in TT_FAMS):
        from src.extract_toktopo import compute_toktopo
        for split in args.splits:
            missing = _need(out_dir, cfg_name, split,
                            [f for f in TT_FAMS if f in target_families], args.force)
            if not missing: print(f"  [skip-toktopo {split}] all toktopo files exist"); continue
            df = pd.read_parquet(out_dir / f"predictions_{split}.parquet")
            idxs = df["idx"].tolist()
            attn_dir = out_dir / "attention" / split
            t0 = time.time()
            print(f"  [toktopo {split}] compute ({len(idxs)} samples, {args.workers}w)")
            arr, cols = compute_toktopo(attn_dir, idxs, n_workers=args.workers, max_dim=1)
            print(f"  [toktopo {split}] done in {time.time()-t0:.1f}s; raw shape={arr.shape}")
            sub = _split_by_prefix(arr, cols, {
                "toktopo_pd":    lambda c: c.startswith("toktopo_h"),
                "toktopo_graph": lambda c: (not c.startswith("toktopo_h")) and ("_xbc_" not in c),
                "toktopo_xbc":   lambda c: "_xbc_" in c,
            })
            for fam in missing:
                f_arr, f_cols = sub[fam]
                write_family_file(out_dir, cfg_name, fam, split, f_arr, f_cols, idxs)
                print(f"    wrote {fam}_{split}.npz  {f_arr.shape}")

    # ------------------------- intra_attn -------------------------------
    if "intra_attn" in target_families:
        from src.extract_intra_attn_features import compute_intra_attn_features
        for split in args.splits:
            if not _need(out_dir, cfg_name, split, ["intra_attn"], args.force):
                print(f"  [skip-intra {split}] exists"); continue
            df = pd.read_parquet(out_dir / f"predictions_{split}.parquet")
            idxs = df["idx"].tolist()
            t0 = time.time()
            arr, cols = compute_intra_attn_features(out_dir / "attention" / split, idxs, device=device)
            write_family_file(out_dir, cfg_name, "intra_attn", split, arr, cols, idxs)
            print(f"  [intra_attn {split}] {arr.shape}  ({time.time()-t0:.1f}s)")

    # ------------------------- punct ------------------------------------
    if "punct" in target_families:
        from src.extract_punct_dist import compute_punct_dist
        from src.load_model import load_classification_model
        # Need tokenizer
        _, 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"),
        )
        for split in args.splits:
            if not _need(out_dir, cfg_name, split, ["punct"], args.force):
                print(f"  [skip-punct {split}] exists"); continue
            df = pd.read_parquet(out_dir / f"predictions_{split}.parquet")
            idxs = df["idx"].tolist()
            # punct needs original text; we re-merge with the split df from load_splits
            raw = splits_data[split].reset_index(drop=True)
            raw_merged = raw.loc[raw["idx"].isin(idxs)].set_index("idx").loc[idxs].reset_index()
            t0 = time.time()
            arr, cols = compute_punct_dist(out_dir / "attention" / split, tokenizer,
                                              cfg["model"]["max_length"], raw_merged,
                                              cfg["data"]["text_col"], n_workers=args.workers)
            write_family_file(out_dir, cfg_name, "punct", split, arr, cols, idxs)
            print(f"  [punct {split}] {arr.shape}  ({time.time()-t0:.1f}s)")

    # ------------------------- cls_embed --------------------------------
    CLS_FAMS = ["cls_last", "cls_mid", "cls_begin"]
    if any(f in target_families for f in CLS_FAMS):
        from src.extract_cls_embeddings import compute_cls_features
        from src.load_model import load_classification_model, move
        from src.extract_attention import _build_dataloader  # tokenizer + dataloader builder
        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)
        for split in args.splits:
            missing = _need(out_dir, cfg_name, split,
                            [f for f in CLS_FAMS if f in target_families], args.force)
            if not missing: print(f"  [skip-cls {split}] all cls files exist"); continue
            df = pd.read_parquet(out_dir / f"predictions_{split}.parquet")
            idxs = df["idx"].tolist()
            raw = splits_data[split].reset_index(drop=True)
            raw_merged = raw.loc[raw["idx"].isin(idxs)].set_index("idx").loc[idxs].reset_index()
            loader = _build_dataloader(raw_merged, tokenizer, cfg["data"]["text_col"],
                                          cfg["data"]["label_col"], cfg["model"]["max_length"],
                                          cfg["inference"]["batch_size"])
            t0 = time.time()
            arr, cols = compute_cls_features(model, loader, device=str(device))
            print(f"  [cls {split}] raw shape={arr.shape}  ({time.time()-t0:.1f}s)")
            sub = _split_by_prefix(arr, cols, {
                "cls_last":  lambda c: c.startswith("cls_last_"),
                "cls_mid":   lambda c: c.startswith("cls_mid_"),
                "cls_begin": lambda c: c.startswith("cls_begin_"),
            })
            for fam in missing:
                f_arr, f_cols = sub[fam]
                write_family_file(out_dir, cfg_name, fam, split, f_arr, f_cols, idxs)
                print(f"    wrote {fam}_{split}.npz  {f_arr.shape}")

    # ------------------------- cross-attention families ---------------------
    from src.extract_cross_barcode_features import _resolve_pairs
    CROSS_EXTRACTORS = {
        "js_morepairs": ("src.extract_js_cross_attn", "compute_js_cross_attn_features"),
        "ai_morepairs": ("src.extract_attn_interaction_features", "compute_attn_interaction_features"),
        "ai_s4":        ("src.extract_attn_interaction_features", "compute_attn_interaction_features"),
        "plcross":      ("src.extract_pl_cross", "compute_pl_cross"),
        "swpd":         ("src.extract_sw_pd", "compute_sw_pd_features"),
        "cbh1":         ("src.extract_cross_barcode_h1", "compute_h1_cross_features"),
    }
    for fam in [f for f in target_families if f in CROSS_EXTRACTORS]:
        modname, fnname = CROSS_EXTRACTORS[fam]
        module = __import__(modname, fromlist=[fnname])
        fn = getattr(module, fnname)
        pair_strat = PAIR_STRATEGY[fam]
        pairs = _resolve_pairs(pair_strat)
        for split in args.splits:
            if not _need(out_dir, cfg_name, split, [fam], args.force):
                print(f"  [skip-{fam} {split}] exists"); continue
            df = pd.read_parquet(out_dir / f"predictions_{split}.parquet")
            idxs = df["idx"].tolist()
            attn_dir = out_dir / "attention" / split
            t0 = time.time()
            # All cross extractors take (attn_dir, indices, pairs, ...)
            extra = {}
            if fam == "plcross":  extra = {"n_workers": args.workers}
            if fam == "swpd":     extra = {"device": str(device)}
            if fam == "cbh1":     extra = {}  # uses default quantile
            if fam in {"js_morepairs", "ai_morepairs", "ai_s4"}:
                extra = {"device": torch.device(str(device))}
            arr, cols = fn(attn_dir, idxs, pairs, **extra)
            write_family_file(out_dir, cfg_name, fam, split, arr, cols, idxs)
            print(f"  [{fam} {split}] {arr.shape}  ({time.time()-t0:.1f}s)  strategy={pair_strat}")

    print(f"[{cfg_name}] DONE")


if __name__ == "__main__":
    main()