File size: 9,159 Bytes
f6c2fe1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os, sys, json, re
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import torch
from tqdm import tqdm

from configs.paths import dim_paths
from src.utils import load_model_and_tokenizer, get_device, write_json


DIM = "monitoring"
LIMIT = 40
MAX_WINDOW_TOKENS = 4096

p = dim_paths(DIM)

ACT_PATH = p.ACTIVATIONS
FULL_PATH = p.DIRECTIONS
NO_ORTHO_PATH = os.path.join(p.CHECKPOINT_DIR, "directions_monitoring_noOrtho.pt")
NO_PCA_PATH = os.path.join(p.CHECKPOINT_DIR, "directions_monitoring_noPCA.pt")
SEL_PATH = os.path.join(p.CHECKPOINT_DIR, "selected_layers_monitoring_allmonoV2.json")

GPQA_BASELINE_CANDIDATES = [
    os.path.join(p.RESULTS_DIR, "run_gpqa_d_gpqa_d_s64.jsonl"),
    os.path.join(p.RESULTS_DIR, "run_gpqa_d_gpqa_d_s0.jsonl"),
]


def flat(v):
    if isinstance(v, dict):
        for k in ["direction", "vec", "vector", "v"]:
            if k in v:
                v = v[k]
                break
    if not torch.is_tensor(v):
        v = torch.tensor(v)
    return v.detach().float().view(-1)


def cos(a, b):
    if a is None or b is None:
        return None
    a = flat(a)
    b = flat(b)
    if a.numel() != b.numel():
        return None
    an = a.norm()
    bn = b.norm()
    if an < 1e-8 or bn < 1e-8:
        return None
    return float(torch.dot(a, b) / (an * bn))


def get_dir(blob, L):
    d = blob["directions"]
    if L in d:
        return flat(d[L])
    if str(L) in d:
        return flat(d[str(L)])
    return None


def resolve_layers(model):
    candidates = [
        ("model.layers", lambda m: m.model.layers),
        ("base_model.model.layers", lambda m: m.base_model.model.layers),
        ("transformer.h", lambda m: m.transformer.h),
        ("gpt_neox.layers", lambda m: m.gpt_neox.layers),
    ]
    for name, getter in candidates:
        try:
            layers = getter(model)
            if layers is not None and len(layers) > 0:
                return layers, name
        except Exception:
            pass
    raise RuntimeError("Cannot locate transformer layers.")


def load_gpqa_cots(limit):
    rows = []
    used_path = None

    for path in GPQA_BASELINE_CANDIDATES:
        if not os.path.exists(path):
            continue
        used_path = path
        for line in open(path, encoding="utf-8"):
            if not line.strip():
                continue
            try:
                r = json.loads(line)
            except Exception:
                continue

            try:
                alpha = float(r.get("alpha", -999))
            except Exception:
                alpha = -999

            if abs(alpha - 1.0) > 1e-6:
                continue

            cot = r.get("cot", "")
            if "</think>" not in cot:
                continue

            rows.append({
                "problem_idx": r.get("problem_idx"),
                "cot": cot,
            })

            if len(rows) >= limit:
                break

        if rows:
            break

    return rows, used_path


def avg(xs):
    xs = [x for x in xs if x is not None]
    return sum(xs) / len(xs) if xs else None


def group_summary(name, rs):
    return {
        "group": name,
        "n_layers": len(rs),
        "mean_abs_cos_raw_eos": avg([r["abs_cos_raw_eos"] for r in rs]),
        "mean_abs_cos_noOrtho_eos": avg([r["abs_cos_noOrtho_eos"] for r in rs]),
        "mean_abs_cos_noPCA_eos": avg([r["abs_cos_noPCA_eos"] for r in rs]),
        "mean_abs_cos_full_eos": avg([r["abs_cos_full_eos"] for r in rs]),
        "mean_ortho_overlap_reduction_eos": avg([r["ortho_overlap_reduction_eos"] for r in rs]),
    }


def main():
    print("Loading cached activation/directions...")

    acts_blob = torch.load(ACT_PATH, map_location="cpu", weights_only=False)
    full_blob = torch.load(FULL_PATH, map_location="cpu", weights_only=False)
    no_ortho_blob = torch.load(NO_ORTHO_PATH, map_location="cpu", weights_only=False)
    no_pca_blob = torch.load(NO_PCA_PATH, map_location="cpu", weights_only=False)

    selected = set(int(x) for x in json.load(open(SEL_PATH))["selected_layers"])

    cots, cot_path = load_gpqa_cots(LIMIT)
    if not cots:
        raise FileNotFoundError("No GPQA-D alpha=1 cot file found with </think>. Expected run_gpqa_d_gpqa_d_s64.jsonl.")

    print(f"Using cots from: {cot_path}")
    print(f"n_cots={len(cots)}")

    device = get_device()
    model, tokenizer = load_model_and_tokenizer(device=device)
    layers, layer_path = resolve_layers(model)

    layer_ids = sorted(int(L) for L in acts_blob["per_layer"].keys())
    eos_states = {L: [] for L in layer_ids}
    mean_states = {L: [] for L in layer_ids}

    cache = {}

    handles = []

    def make_hook(L):
        def hook(module, inputs, output):
            h = output[0] if isinstance(output, tuple) else output
            # h: [1, seq, hidden]
            if h.shape[1] < 2:
                return output
            eos_states[L].append(h[0, -1, :].detach().float().cpu())
            mean_states[L].append(h[0, :-1, :].mean(dim=0).detach().float().cpu())
            return output
        return hook

    for L in layer_ids:
        if L < len(layers):
            handles.append(layers[L].register_forward_hook(make_hook(L)))

    model.eval()

    for r in tqdm(cots, desc="forward_eos_windows"):
        cot = r["cot"]
        end = cot.find("</think>") + len("</think>")
        text = cot[:end]

        ids = tokenizer(text, add_special_tokens=False)["input_ids"]
        ids = ids[-MAX_WINDOW_TOKENS:]

        input_ids = torch.tensor([ids], device=device)

        with torch.no_grad():
            model(input_ids=input_ids, use_cache=False)

    for h in handles:
        h.remove()

    eos_dirs = {}
    for L in layer_ids:
        if not eos_states[L] or not mean_states[L]:
            continue
        eos_mean = torch.stack(eos_states[L]).mean(0)
        mean_mean = torch.stack(mean_states[L]).mean(0)
        eos_dirs[L] = eos_mean - mean_mean

    rows = []
    for L_raw, data in acts_blob["per_layer"].items():
        L = int(L_raw)
        acts = data["acts"].float()
        labels = data["labels"]

        pos = acts[labels == 1]
        neg = acts[labels == 0]
        if pos.shape[0] < 5 or neg.shape[0] < 5:
            continue

        raw_md = pos.mean(0) - neg.mean(0)
        eos_dir = eos_dirs.get(L)

        d_full = get_dir(full_blob, L)
        d_no_ortho = get_dir(no_ortho_blob, L)
        d_no_pca = get_dir(no_pca_blob, L)

        c_raw = cos(raw_md, eos_dir)
        c_no_ortho = cos(d_no_ortho, eos_dir)
        c_no_pca = cos(d_no_pca, eos_dir)
        c_full = cos(d_full, eos_dir)

        row = {
            "layer": L,
            "selected": L in selected,
            "n_cots": len(cots),
            "cos_raw_eos": c_raw,
            "cos_noOrtho_eos": c_no_ortho,
            "cos_noPCA_eos": c_no_pca,
            "cos_full_eos": c_full,
            "abs_cos_raw_eos": abs(c_raw) if c_raw is not None else None,
            "abs_cos_noOrtho_eos": abs(c_no_ortho) if c_no_ortho is not None else None,
            "abs_cos_noPCA_eos": abs(c_no_pca) if c_no_pca is not None else None,
            "abs_cos_full_eos": abs(c_full) if c_full is not None else None,
        }

        if row["abs_cos_noOrtho_eos"] is not None and row["abs_cos_full_eos"] is not None:
            row["ortho_overlap_reduction_eos"] = row["abs_cos_noOrtho_eos"] - row["abs_cos_full_eos"]
        else:
            row["ortho_overlap_reduction_eos"] = None

        rows.append(row)

    selected_rows = [r for r in rows if r["selected"]]
    rejected_rows = [r for r in rows if not r["selected"]]

    summary = {
        "note": "EOS / </think> termination-direction geometry diagnostic. termination_direction = mean hidden at </think> token minus mean hidden over preceding window.",
        "cot_path": cot_path,
        "n_cots": len(cots),
        "max_window_tokens": MAX_WINDOW_TOKENS,
        "activation_path": ACT_PATH,
        "full_direction_path": FULL_PATH,
        "no_ortho_path": NO_ORTHO_PATH,
        "no_pca_path": NO_PCA_PATH,
        "selected_layer_file": SEL_PATH,
        "groups": [
            group_summary("selected_layers", selected_rows),
            group_summary("rejected_or_unselected_layers", rejected_rows),
            group_summary("all_layers", rows),
        ],
        "rows": rows,
    }

    out = os.path.join(p.RESULTS_DIR, "orthogonalization_geometry_eos_summary.json")
    write_json(summary, out)

    print("Saved:", out)
    print()
    print("| group | n | raw cos EOS | noOrtho cos EOS | noPCA cos EOS | full cos EOS | ortho reduction |")
    print("|---|---:|---:|---:|---:|---:|---:|")
    for g in summary["groups"]:
        def f(x):
            return "NA" if x is None else f"{x:.4f}"
        print(
            f"| {g['group']} | {g['n_layers']} "
            f"| {f(g['mean_abs_cos_raw_eos'])} "
            f"| {f(g['mean_abs_cos_noOrtho_eos'])} "
            f"| {f(g['mean_abs_cos_noPCA_eos'])} "
            f"| {f(g['mean_abs_cos_full_eos'])} "
            f"| {f(g['mean_ortho_overlap_reduction_eos'])} |"
        )


if __name__ == "__main__":
    main()