""" Stage 02 (v8b): Build per-layer direction subspaces (dense, no MoE). For each captured layer: - mean-difference vector (high-reflection minus low-reflection class) - PCA-denoise within the top-N PCs of all activations - orthogonalize against the layer's general mean No model load is needed here — Qwen3-8B is dense, so there is no expert weight mask to compute. We work directly off the stage-01 activations. Resume: skip if DIRECTIONS already exists. """ import argparse, os, sys sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import torch from configs import get_config from configs.paths import LOG_DIR, dim_paths, ensure_dirs from src.directions import build_layer_directions from src.utils import setup_logger, write_json def main(): ap = argparse.ArgumentParser() ap.add_argument("--dimension", default="monitoring") ap.add_argument("--n-pca-components", type=int, default=100) ap.add_argument("--min-residual-after-general", type=float, default=0.20) ap.add_argument("--disable-pca", action="store_true", help="Ablation: skip PCA denoising on mean-diff.") ap.add_argument("--disable-ortho", action="store_true", help="Ablation: skip orthogonalization vs general mean.") ap.add_argument("--force", action="store_true") args = ap.parse_args() ensure_dirs(args.dimension) cfg = get_config(args.dimension) p = dim_paths(args.dimension) log = setup_logger("02_directions", os.path.join(LOG_DIR, f"02_directions_{cfg.NAME}.log")) log.info("=" * 70) log.info(f"Stage 02 [{cfg.NAME}] (v8b dense) pca_n={args.n_pca_components}") log.info("=" * 70) if os.path.exists(p.DIRECTIONS) and not args.force: try: ex = torch.load(p.DIRECTIONS, map_location="cpu", weights_only=False) log.info(f" [resume] {p.DIRECTIONS} exists " f"({len(ex.get('directions', {}))} layers) — SKIP. " f"Use --force to recompute.") return except Exception as e: log.warning(f" [resume] unreadable ({e}); recomputing") if not os.path.exists(p.ACTIVATIONS): log.error(f"missing {p.ACTIVATIONS} — run stage 01 first") sys.exit(1) blob = torch.load(p.ACTIVATIONS, map_location="cpu", weights_only=False) per_layer = blob["per_layer"] log.info("PCA-denoised mean-diff + ortho-vs-general per layer...") per_layer_data = { L: {"acts": per_layer[L]["acts"], "labels": per_layer[L]["labels"]} for L in per_layer } directions, diagnostics = build_layer_directions( per_layer_data, n_pca_components=args.n_pca_components, min_residual_after_general=args.min_residual_after_general, disable_pca=args.disable_pca, disable_ortho=args.disable_ortho, logger=log, ) save = { "dimension": cfg.NAME, "n_pca_components": args.n_pca_components, "directions": directions, "diagnostics": diagnostics, "target_layers": cfg.TARGET_LAYERS, } tmp = p.DIRECTIONS + ".tmp" torch.save(save, tmp) os.replace(tmp, p.DIRECTIONS) log.info(f"Saved {p.DIRECTIONS} ({len(directions)} layers kept). Done.") write_json( {"kept": sorted(directions.keys()), "diagnostics": diagnostics}, p.DIRECTIONS.replace(".pt", "_summary.json"), ) if __name__ == "__main__": main()