| """Direction extraction — v8b (dense Qwen3-8B, no MoE mask). |
| |
| Per layer: |
| 1. mean-difference vector (positive class minus negative class) |
| 2. PCA-denoise it within the top-N principal components of all activations |
| 3. orthogonalize against the layer's general mean |
| |
| The MoE expert-coordinate mask from the 30B pipeline is dropped entirely |
| — Qwen3-8B is dense, so there are no experts to select or mask. |
| """ |
| from typing import Dict |
| import torch |
|
|
|
|
| def _pca_topk(X, k): |
| X = X.float() |
| if X.shape[0] < 2 or X.shape[1] < 2: |
| return (torch.zeros(0, X.shape[1] if X.dim() == 2 else 0), |
| torch.zeros(0)) |
| U, S, Vh = torch.linalg.svd(X, full_matrices=False) |
| k = min(k, Vh.shape[0]) |
| return Vh[:k], (S[:k] ** 2) / (X.shape[0] - 1) |
|
|
|
|
| def compute_pos_vs_neg_pca(acts, labels, n_pca_components): |
| pos = acts[labels == 1].float() |
| neg = acts[labels == 0].float() |
| info = {"n_pos": int(pos.shape[0]), "n_neg": int(neg.shape[0])} |
| h = acts.shape[1] |
| if pos.shape[0] < 10 or neg.shape[0] < 10: |
| info["error"] = "too_few_samples" |
| return torch.zeros(h), info |
|
|
| md_raw = pos.mean(0) - neg.mean(0) |
| md_raw_norm = float(md_raw.norm()) |
| info["mean_diff_norm_raw"] = md_raw_norm |
| if md_raw_norm < 1e-8: |
| return torch.zeros(h), info |
|
|
| all_acts = acts.float() |
| if n_pca_components <= 0: |
| info["var_explained_pca"] = [] |
| info["pca_n_returned"] = 0 |
| pca_components = torch.zeros(0, h) |
| else: |
| Xc = all_acts - all_acts.mean(0) |
| pca_components, var_exp = _pca_topk(Xc, n_pca_components) |
| info["var_explained_pca"] = var_exp.tolist() |
| info["pca_n_returned"] = int(pca_components.shape[0]) |
|
|
| if pca_components.shape[0] == 0: |
| md_filtered = md_raw |
| info["pca_denoise_applied"] = False |
| else: |
| Q = pca_components |
| md_filtered = ((Q @ md_raw).unsqueeze(0) @ Q).squeeze(0) |
| info["pca_denoise_applied"] = True |
|
|
| md_filt_norm = float(md_filtered.norm()) |
| info["mean_diff_norm_filtered"] = md_filt_norm |
| info["denoise_keep_ratio"] = ( |
| md_filt_norm / md_raw_norm if md_raw_norm > 1e-8 else 0.0 |
| ) |
| if md_filt_norm < 1e-8: |
| return torch.zeros(h), info |
|
|
| return md_filtered / md_filt_norm, info |
|
|
|
|
| def orthogonalize_against_general(direction, general, min_residual=0.20): |
| g = general.float() |
| gn = g.norm() |
| if gn < 1e-8: |
| return direction |
| g = g / gn |
| d = direction.float() |
| d = d - (d @ g) * g |
| dn = d.norm() |
| on = direction.float().norm() |
| if dn < 1e-8 or (on > 1e-8 and dn / on < min_residual): |
| return None |
| return (d / dn).to(direction.dtype) |
|
|
|
|
| def build_layer_directions(per_layer_data, |
| n_pca_components=100, |
| min_residual_after_general=0.20, |
| disable_pca=False, |
| disable_ortho=False, |
| logger=None): |
| directions = {} |
| diagnostics = {} |
| for L in sorted(per_layer_data.keys()): |
| acts = per_layer_data[L]["acts"] |
| labels = per_layer_data[L]["labels"] |
| eff_pca = 0 if disable_pca else n_pca_components |
| mean_diff, info = compute_pos_vs_neg_pca(acts, labels, eff_pca) |
| if "error" in info or mean_diff.norm() < 1e-8: |
| if logger: |
| logger.info(f" L{L}: SKIP ({info.get('error', 'low norm')})") |
| diagnostics[L] = info |
| continue |
| if disable_ortho: |
| md_n = mean_diff.float().norm() |
| final = (mean_diff.float() / md_n).to(mean_diff.dtype) if md_n > 1e-8 else None |
| else: |
| general = acts.float().mean(0) |
| final = orthogonalize_against_general( |
| mean_diff, general, min_residual_after_general |
| ) |
| if final is None: |
| if logger: |
| logger.info(f" L{L}: SKIP (low residual after general)") |
| info["skip_reason"] = "low_residual_after_general" |
| diagnostics[L] = info |
| continue |
| directions[L] = final.unsqueeze(0) |
| info["kept"] = True |
| diagnostics[L] = info |
| if logger: |
| logger.info( |
| f" L{L}: kept norm_raw={info['mean_diff_norm_raw']:.2f} " |
| f"keep_ratio={info['denoise_keep_ratio']:.3f}" |
| ) |
| return directions, diagnostics |
|
|