File size: 9,791 Bytes
7853eeb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3db31c5
 
7853eeb
 
 
 
 
 
 
3db31c5
 
 
 
 
 
 
 
 
 
 
 
 
7853eeb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3db31c5
 
 
 
 
7853eeb
 
 
 
 
3db31c5
 
 
 
 
 
 
 
 
 
7853eeb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3db31c5
 
7853eeb
 
 
 
 
 
 
 
3db31c5
 
 
 
 
 
7853eeb
 
 
 
 
 
 
 
3db31c5
7853eeb
 
 
 
 
 
3db31c5
7853eeb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3db31c5
7853eeb
3db31c5
7853eeb
3db31c5
 
 
7853eeb
3db31c5
 
 
 
7853eeb
 
3db31c5
 
7853eeb
 
 
 
 
 
 
 
 
3db31c5
 
7853eeb
 
 
 
 
 
 
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
"""Monte-Carlo dropout passes, and the penultimate feature, for one configuration.

The fine-tuned classifier is run with its dropout layers active, ``--passes``
times, over the validation and test splits and over the shifted corpora of
data/ood_states/. Every pass keeps the logits; the first ``--save-states``
passes also keep the whole per-layer [CLS] stack, so the stochastic
trajectories are on disk for later work and never have to be regenerated.
One deterministic pass caches the input of the classifier's final linear
layer (the penultimate feature) and that layer's weights, which the ViM and
GradNorm baselines read.

Layout:

    data/mc_dropout/<cfg>/logits_<split>.npy          (T, N, C) float32
    data/mc_dropout/<cfg>/states_<split>_pass<t>.npy  (N, L+1, D) float16, t < save-states
    data/mc_dropout/<cfg>/meta_<split>.npz            idx, label, passes, saved_passes,
                                                      batch_size, seed_scheme
    data/mc_dropout/<cfg>/logits_ood_<ds>.npy         (T, n, C) float32
    data/mc_dropout/<cfg>/penult_<split>.npy          (N, P) float32, deterministic
    data/mc_dropout/<cfg>/penult_ood_<ds>.npy         (n, P) float32, deterministic
    data/mc_dropout/<cfg>/head.npz                    W (C, P), b (C,)

Row order follows predictions_<split>.parquet for the splits and
data/ood_states/<cfg>/<ds>_idx.npy for the shifted corpora, so every file
aligns with the deterministic caches without a join. ``meta_ood_<ds>.npz:label``
is the label of the shifted corpus in *its own* label space; it is kept for
bookkeeping only and never compared with this configuration's classes.

Pass t of input set number s (validation = 0, test = 1, the shifted corpora
after them in data/ood_states/ order) draws its dropout masks from torch seed
1000 + 1000 * t + s, so no two sets share a mask stream. The masks also depend
on the batch size, which meta_<split>.npz records. Cells written before this
seed scheme (seed 1000 + t for every set) carry ``seed_scheme='pass'`` in
their meta files, or no field at all.

The DONE marker records ``passes=`` and ``save_states=``; a request for more
passes, or for more saved passes, than the marker holds re-runs the cell.

    python extraction/scripts/10_mc_dropout.py --config extraction/configs/roberta_cola.yaml
"""
from __future__ import annotations

import argparse
import sys
import time
from pathlib import Path

import numpy as np
import pandas as pd
import torch
from tqdm import tqdm

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
from src.utils import load_config, seed_everything, device_from_cfg  # noqa: E402
from src.load_data import load_splits  # noqa: E402
from src.load_model import load_classification_model, move  # noqa: E402
from src.extract_attention import _build_dataloader  # noqa: E402

REPO = ROOT.parent
sys.path.insert(0, str(REPO))
from cct_reproduce.grids import datasets_from_env, split_cfg  # noqa: E402


def final_linear(model, num_labels):
    """The last nn.Linear that emits the logits; its input is the penultimate feature."""
    # skip the low-rank factors of an unmerged PEFT wrapper: lora_B has the
    # right out_features but is not the layer that emits the logits
    cands = [m for n, m in model.named_modules()
             if isinstance(m, torch.nn.Linear) and m.out_features == num_labels
             and not n.split(".")[-1].startswith(("lora_A", "lora_B"))]
    if not cands:
        raise RuntimeError("no final linear layer with out_features == num_labels")
    return cands[-1]


def done_marker(path):
    """passes / save_states recorded in a DONE marker (older markers without them: 20 / 0)."""
    have = {"passes": 20, "save_states": 0}
    for tok in path.read_text().split():
        key, _, val = tok.partition("=")
        if key in have and val.isdigit():
            have[key] = int(val)
    return have


@torch.no_grad()
def one_pass(model, loader, device, keep_states, penult_hook=None):
    lg, st, pen = [], [], []
    for batch in tqdm(loader, desc="pass", leave=False):
        o = model(input_ids=batch["input_ids"].to(device),
                  attention_mask=batch["attention_mask"].to(device),
                  output_hidden_states=keep_states)
        lg.append(o.logits.float().cpu())
        if keep_states:
            st.append(torch.stack([h[:, 0, :] for h in o.hidden_states], 1).half().cpu())
        if penult_hook is not None:
            pen.append(penult_hook.pop().float().cpu())
    return (torch.cat(lg).numpy(),
            torch.cat(st).numpy() if keep_states else None,
            torch.cat(pen).numpy() if penult_hook is not None else None)


def main():
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("--config", required=True)
    ap.add_argument("--passes", type=int, default=20)
    ap.add_argument("--save-states", type=int, default=0,
                    help="passes whose per-layer states are written (validation and test)")
    ap.add_argument("--batch-size", type=int, default=128)
    ap.add_argument("--force", action="store_true")
    a = ap.parse_args()
    if a.save_states > a.passes:
        ap.error("--save-states cannot exceed --passes")

    cfg = load_config(a.config)
    seed_everything(cfg["seed"])
    name = cfg["run_name"]
    dest = REPO / "data" / "mc_dropout" / name
    dest.mkdir(parents=True, exist_ok=True)
    done = dest / "DONE"
    if done.exists() and not a.force:
        have = done_marker(done)
        if have["passes"] >= a.passes and have["save_states"] >= a.save_states:
            print(f"[{name}] mc-dropout present "
                  f"(passes={have['passes']} save_states={have['save_states']})"); return
        print(f"[{name}] mc-dropout present with passes={have['passes']} "
              f"save_states={have['save_states']}, requested {a.passes}/{a.save_states}: rerun")

    device = device_from_cfg(cfg)
    model, tok = 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.config.output_attentions = False   # never needed here; saves memory and time
    model = move(model, device).eval()
    num_labels = model.config.num_labels
    lin = final_linear(model, num_labels)
    np.savez(dest / "head.npz", W=lin.weight.detach().float().cpu().numpy(),
             b=lin.bias.detach().float().cpu().numpy())
    box = []
    hook = lin.register_forward_hook(lambda m, i, o: box.append(i[0].detach()))

    text_col, label_col = cfg["data"]["text_col"], cfg["data"]["label_col"]
    max_len, bs = cfg["model"]["max_length"], a.batch_size
    splits_data = load_splits(cfg)
    enc, own = split_cfg(name)

    # every input set, in the row order of its deterministic cache
    sets = {}
    for split in ("train", "validation", "test"):
        df = pd.read_parquet(REPO / "data" / "features" / name / f"predictions_{split}.parquet")
        idxs = df["idx"].tolist()
        raw = splits_data[split].reset_index(drop=True)
        raw = raw.loc[raw["idx"].isin(idxs)].set_index("idx").loc[idxs].reset_index()
        sets[split] = (raw, np.asarray(idxs, dtype=np.int64))
    ood_dir = REPO / "data" / "ood_states" / name
    for ds in datasets_from_env():
        if ds == own or not (ood_dir / f"{ds}_idx.npy").exists():
            continue
        oc = ROOT / "configs" / f"{enc}_{ds}.yaml"
        raw = load_splits(load_config(str(oc)))["test"].reset_index(drop=True)
        keep = np.load(ood_dir / f"{ds}_idx.npy")
        raw = raw.iloc[keep].reset_index(drop=True)
        sets[f"ood_{ds}"] = (raw, keep)

    loaders = {k: _build_dataloader(raw, tok, text_col, label_col, max_len, bs)
               for k, (raw, _) in sets.items()}

    # deterministic pass: the penultimate feature of every set
    model.eval()
    for k, loader in loaders.items():
        t0 = time.time()
        _, _, pen = one_pass(model, loader, device, False, box)
        np.save(dest / f"penult_{k}.npy", pen.astype(np.float32))
        print(f"  [penult {k}] {pen.shape}  ({time.time() - t0:.0f}s)", flush=True)
    box.clear()
    hook.remove()

    # stochastic passes; one mask stream per (pass, input set)
    model.train()
    stochastic = [k for k in loaders if k != "train"]
    for s_ix, k in enumerate(stochastic):
        loader = loaders[k]
        t0 = time.time()
        n_states = 0 if k.startswith("ood_") else a.save_states
        for old in dest.glob(f"states_{k}_pass*.npy"):   # stale passes of an earlier run
            if int(old.stem.rsplit("pass", 1)[1]) >= n_states:
                old.unlink()
        LG = []
        for t in range(a.passes):
            torch.manual_seed(1000 + 1000 * t + s_ix)
            keep_states = t < n_states
            lg, st, _ = one_pass(model, loader, device, keep_states)
            LG.append(lg)
            if keep_states:
                np.save(dest / f"states_{k}_pass{t:02d}.npy", st)
        LG = np.stack(LG)
        np.save(dest / f"logits_{k}.npy", LG.astype(np.float32))
        raw, idx = sets[k]
        np.savez(dest / f"meta_{k}.npz", idx=idx,
                 label=raw[label_col].to_numpy().astype(np.int64),
                 passes=np.int64(a.passes), saved_passes=np.int64(n_states),
                 batch_size=np.int64(bs), seed_scheme="pass_set")
        print(f"  [mc {k}] logits {LG.shape}  ({time.time() - t0:.0f}s)", flush=True)
    done.write_text(f"passes={a.passes} save_states={a.save_states}\n")
    print(f"[{name}] wrote {dest.relative_to(REPO)}")


if __name__ == "__main__":
    main()