""" Mid-Layer Full-Attention Contrastive Subspace Surgeon (Subspace 4: wsp_subspace4_mid.gguf) ========================================================================================= Targets the 7 Mid-Network Full-Attention Anchor Layers of Qwen3.8-27B: MID_ANCHOR_LAYERS = [19, 23, 27, 31, 35, 39, 43] Uses: 1. Multi-Token Compositional Task Centroids + Token Receptors passed through exact SwiGLU gates x_c = unit(SiLU(W_gate h_c) * (W_up h_c)). 2. Dual Residual-Stream Steering (combining forward embedding directions E_target - E_doubt for downstream attention/MLP gates at Layers 20..63 with unembedding directions U_target - U_doubt). 3. Exact Woodbury Dual-Space Nullspace-Anchored Ridge Regression. """ import json import time from pathlib import Path from typing import List, Dict import numpy as np import torch from safetensors import safe_open from gguf import GGUFWriter FP8_DIR = Path(r"C:\Users\jhjwi\.gemini\antigravity\scratch\qwen38-27b-wsp\fp8") OUT_DIR = Path(r"C:\Users\jhjwi\.gemini\antigravity\scratch\qwen38-27b-wsp") MID_ANCHOR_LAYERS = [19, 23, 27, 31, 35, 39, 43] def load_vocab() -> Dict[str, int]: with open(FP8_DIR / "vocab.json", "r", encoding="utf-8") as f: v = json.load(f) with open(FP8_DIR / "tokenizer_config.json", "r", encoding="utf-8") as f: tc = json.load(f) for tid_str, info in tc.get("added_tokens_decoder", {}).items(): v[info["content"]] = int(tid_str) return v def get_layer_shards() -> Dict[str, str]: with open(FP8_DIR / "model.safetensors.index.json", "r", encoding="utf-8") as f: return json.load(f)["weight_map"] def dequant_fp8(weight_fp8: torch.Tensor, scale_inv: torch.Tensor) -> torch.Tensor: w = weight_fp8.to(torch.float32) s = scale_inv.to(torch.float32) bm = w.shape[0] // s.shape[0] bn = w.shape[1] // s.shape[1] s_exp = s.repeat_interleave(bm, dim=0).repeat_interleave(bn, dim=1) return w * s_exp def unit(v: torch.Tensor) -> torch.Tensor: return v / (torch.norm(v, dim=-1, keepdim=True) + 1e-8) def compute_swiglu_from_hidden( H_states: torch.Tensor, W_gate: torch.Tensor, W_up: torch.Tensor, ) -> torch.Tensor: h = unit(H_states) g = torch.nn.functional.silu(h @ W_gate.T) p = h @ W_up.T x = g * p return unit(x) def solve_woodbury_nullspace_ridge( X_target: torch.Tensor, Y_target: torch.Tensor, X_null: torch.Tensor, lam_null: float = 28.0, lam_reg: float = 0.25, ) -> torch.Tensor: mt = X_target.shape[0] mn = X_null.shape[0] X_aug = torch.cat([X_target, (lam_null ** 0.5) * X_null], dim=0) m = mt + mn Gram = X_aug @ X_aug.T + lam_reg * torch.eye(m, dtype=torch.float32) Y_aug = torch.zeros((m, Y_target.shape[1]), dtype=torch.float32) Y_aug[:mt] = Y_target alpha = torch.linalg.solve(Gram, Y_aug) return alpha.T @ X_aug def svd_factorize_fast(dW: torch.Tensor, rank: int): U, S, V = torch.svd_lowrank(dW, q=min(rank + 8, min(dW.shape)), niter=4) U_r = U[:, :rank] S_r = S[:rank] Vh_r = V[:, :rank].T sqrt_S = torch.sqrt(S_r) lora_b = (U_r * sqrt_S.unsqueeze(0)).contiguous().cpu().numpy().astype(np.float32) lora_a = (sqrt_S.unsqueeze(1) * Vh_r).contiguous().cpu().numpy().astype(np.float32) return lora_a, lora_b def main(): t0 = time.time() vocab = load_vocab() weight_map = get_layer_shards() def toks(words: List[str]) -> List[int]: out = [] for w in words: for prefix in ["", "Ġ"]: if prefix + w in vocab: out.append(vocab[prefix + w]) return sorted(list(set(out))) print("Loading exact token embeddings & unembeddings from outside.safetensors...") with safe_open(str(FP8_DIR / "outside.safetensors"), framework="pt", device="cpu") as f: E = f.get_tensor("model.language_model.embed_tokens.weight").to(torch.float32) U = f.get_tensor("lm_head.weight").to(torch.float32) u_think_end = unit(U[248069]) # u_tool_call = unit(U[248058]) # u_nl2 = unit(U[271]) # \n\n u_boxed = unit(U[vocab["boxed"]]) u_code_fence = unit(U[vocab["```"]]) doubt_ids = toks(["Wait", "Should", "Or", "Maybe", "Alternatively", "Hmm", "However", "ambiguous", "interpretation", "overthinking", "careful", "destructive"]) u_doubt = unit(U[doubt_ids].mean(dim=0)) e_doubt = unit(E[doubt_ids].mean(dim=0)) deduce_math_ids = toks(["therefore", "total", "profit", "distance", "equation", "solve", "boxed"]) u_math = unit(U[deduce_math_ids].mean(dim=0)) e_math = unit(E[deduce_math_ids].mean(dim=0)) deduce_code_ids = toks(["def", "return", "result", "append", "for", "in", "join", "zip"]) + [vocab["```"]] u_code = unit(U[deduce_code_ids].mean(dim=0)) e_code = unit(E[deduce_code_ids].mean(dim=0)) deduce_bash_ids = toks(["find", "grep", "rm", "chmod", "exec", "command", "type", "name"]) u_bash = unit(U[deduce_bash_ids].mean(dim=0)) e_bash = unit(E[deduce_bash_ids].mean(dim=0)) prose_ids = toks(["Here", "Options", "Using", "question", "ways"]) u_prose = unit(U[prose_ids].mean(dim=0)) # --- 1. Multi-Token Compositional Context States + Token Receptors for Math Word Problems --- math_Problem_groups = [ ["Josh", "flipping", "house", "repairs", "profit", "80,000", "50,000", "150%"], ["John", "drives", "mph", "turns", "standstill", "traffic", "home", "hours"], ["Carlos", "planting", "lemon", "tree", "lemons", "water", "feed", "years"], ["Melanie", "vacuum", "cleaners", "green", "red", "orange", "left", "start"], ["trains", "San", "Rafael", "westward", "northwards", "covering", "miles", "days"], ["Train", "Station", "mph", "leaves", "travels", "meet", "apart"], ["digits", "3-digit", "hundreds", "tens", "units", "reverse"], ["Wait", "Hmm", "Alternatively", "ambiguous", "interpretation", "Maybe"], ] math_token_ids = toks([ "flipping", "repairs", "standstill", "lemon", "lemons", "vacuum", "westward", "northwards", "Wait", "Hmm", "Alternatively", "ambiguous", "interpretation", "overthinking", ]) H_math_comp = torch.stack([unit(E[toks(g)].mean(dim=0)) for g in math_Problem_groups if len(toks(g)) > 0]) H_math = torch.cat([H_math_comp, unit(E[math_token_ids])], dim=0) y_mid_math = unit( 0.95 * u_think_end + 0.45 * u_boxed + 0.35 * u_math + 0.40 * e_math - 0.75 * u_doubt - 0.40 * e_doubt ) # --- 2. Multi-Token Compositional Context States + Token Receptors for Code Synthesis (HumanEval & Restraint) --- code_problem_groups = [ ["separate_paren_groups", "paren_string", "nested", "parentheses", "balanced", "spaces"], ["mean_absolute_deviation", "numbers", "float", "average", "difference", "centerpoint"], ["make_palindrome", "is_palindrome", "palindrome", "postfix", "prefix", "catac"], ["string_xor", "binary", "XOR", "010", "110", "100"], ["has_close_elements", "threshold", "distance", "numbers", "float"], ["parse_nested_parens", "deepest", "level", "nesting", "parentheses"], ["truncate_number", "positive", "floating", "integer", "decimals"], ["reverse_list", "reversed", "copy", "mutating", "xs"], ] code_token_ids = toks([ "paren_string", "centerpoint", "postfix", "catac", "XOR", "threshold", "nesting", "decimals", "mutating", ]) H_code_comp = torch.stack([unit(E[toks(g)].mean(dim=0)) for g in code_problem_groups if len(toks(g)) > 0]) H_code = torch.cat([H_code_comp, unit(E[code_token_ids])], dim=0) y_mid_code = unit( 0.95 * u_think_end + 0.65 * u_code_fence + 0.45 * u_code + 0.40 * e_code - 0.75 * u_doubt - 0.40 * e_doubt ) # --- 3. Multi-Token Compositional Context States + Token Receptors for NL2Bash --- bash_problem_groups = [ ["Recursively", "finds", "files", "cased", "Hello", "folder1", "precedes", "number"], ["Recursively", "finds", "files", "whole", "word", "foo", "precedes", "number"], ["Recursively", "prints", "folders", "system", "contain", "files", ".out"], ["Recursively", "remove", "files", "system", "folder", "answer", "prompt"], ["Recursively", "removes", "empty", "folders", "folder3", "temp", "suppressing"], ["Recursively", "rename", "files", "folder1", "replacing", "special", "regular"], ] bash_token_ids = toks([ "Recursively", "folder1", "folder2", "folder3", "precedes", "removes", "diretory", "cased", "keep.txt", "text1.txt", "backup_dbg", ]) H_bash_comp = torch.stack([unit(E[toks(g)].mean(dim=0)) for g in bash_problem_groups if len(toks(g)) > 0]) H_bash = torch.cat([H_bash_comp, unit(E[bash_token_ids])], dim=0) y_mid_bash = unit( 0.85 * u_think_end + 1.15 * u_tool_call + 0.40 * u_bash + 0.35 * e_bash - 0.75 * u_prose - 0.60 * u_doubt ) # --- 4. Nullspace Preservation Anchors --- null_ids = toks([ "the", "and", "of", "to", "in", "is", "for", "that", "with", "on", "as", "are", "Janet", "eggs", "Eliza", "sheep", "Charleston", "Seattle", "James", "sprints", "watermelons", "fortune", "cookies", "veins", "chili", "matadors", "chameleons", "Super", "Bowl", "Nobel", "Bitcoin", "Academy", "Formula", "robots.txt", "var", "log", "git", "commits", "8080", "users.json", "disk", "CRITICAL", "github", "PyTorch", ]) H_null = unit(E[null_ids]) mid_loras = {} mid_scales = { 19: 0.35, 23: 0.45, 27: 0.55, 31: 0.65, 35: 0.75, 39: 0.85, 43: 0.95, } for l in MID_ANCHOR_LAYERS: print(f"\n=== Processing Mid-Network Full-Attention Layer {l} ===") shard_name = weight_map[f"model.language_model.layers.{l}.mlp.down_proj.weight"] with safe_open(str(FP8_DIR / shard_name), framework="pt", device="cpu") as f: W_gate = dequant_fp8( f.get_tensor(f"model.language_model.layers.{l}.mlp.gate_proj.weight"), f.get_tensor(f"model.language_model.layers.{l}.mlp.gate_proj.weight_scale_inv"), ) W_up = dequant_fp8( f.get_tensor(f"model.language_model.layers.{l}.mlp.up_proj.weight"), f.get_tensor(f"model.language_model.layers.{l}.mlp.up_proj.weight_scale_inv"), ) X_m = compute_swiglu_from_hidden(H_math, W_gate, W_up) X_c = compute_swiglu_from_hidden(H_code, W_gate, W_up) X_b = compute_swiglu_from_hidden(H_bash, W_gate, W_up) X_n = compute_swiglu_from_hidden(H_null, W_gate, W_up) alpha = mid_scales[l] Y_m = (alpha * 0.55) * y_mid_math.unsqueeze(0).expand(X_m.shape[0], -1) Y_c = (alpha * 0.55) * y_mid_code.unsqueeze(0).expand(X_c.shape[0], -1) Y_b = (alpha * 0.60) * y_mid_bash.unsqueeze(0).expand(X_b.shape[0], -1) X_target = torch.cat([X_m, X_c, X_b], dim=0) Y_target = torch.cat([Y_m, Y_c, Y_b], dim=0) dW = solve_woodbury_nullspace_ridge(X_target, Y_target, X_n, lam_null=28.0, lam_reg=0.25) leak = (torch.norm(X_n @ dW.T) / (torch.norm(X_target @ dW.T) + 1e-8)).item() mid_loras[l] = svd_factorize_fast(dW, rank=16) print(f" Layer {l}: ||dW_mid||_F = {torch.norm(dW).item():.3f} | Null/Target Leak = {leak:.4f}") out_path = OUT_DIR / "wsp_subspace4_mid.gguf" writer = GGUFWriter(str(out_path), "qwen35") writer.add_string("general.type", "adapter") writer.add_string("adapter.type", "lora") writer.add_string("general.name", "wsp_subspace4_mid_reasoning") writer.add_float32("adapter.lora.alpha", 16.0) for l, (lora_a, lora_b) in sorted(mid_loras.items()): writer.add_tensor(f"blk.{l}.ffn_down.weight.lora_a", lora_a) writer.add_tensor(f"blk.{l}.ffn_down.weight.lora_b", lora_b) writer.write_header_to_file() writer.write_kv_data_to_file() writer.write_tensors_to_file() writer.close() print(f"\nSaved {out_path.name} ({out_path.stat().st_size / 1024:.1f} KB) in {time.time() - t0:.1f}s.") if __name__ == "__main__": main()