| 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 |
| |
| 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() |
|
|