File size: 9,950 Bytes
d3c2835
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Surgical Diff-LoRA 5-Step `orth_sub` Auto-Loop (`methods/surgical_diff_lora.py`).

Standalone implementation of our 5-step capability-patching method for
isolated audio-pathway adaptation without regressing frozen LLM weights:

  Step 1. Freeze `W_base` (base LLM, audio frontend, projector, base audio MLPs).
  Step 2. Train two independent rank-r LoRAs (`ΔW_pos`, `ΔW_neg`) on the EXACT
          SAME audio inputs with symmetric contrastive text targets (`D_pos` vs
          `D_neg`, 0% eval overlap, full-batch, no weight decay).
  Step 3. Compute exact layer-wise cosine similarity `cos(ΔW_pos, ΔW_neg)` and
          Gram-Schmidt orthogonal subtraction (`orth_sub`, NEVER prune before
          subtract):
              ΔW_buf = ΔW_pos - (<ΔW_pos, ΔW_neg> / ||ΔW_neg||_F^2) * ΔW_neg
          guaranteeing `<ΔW_buf, ΔW_neg> == 0`.
  Step 4. Serialize `ΔW_buf` as a compact rank-`2r` SVD capability module so it
          can be applied or ablated at any `alpha` without retraining.
  Step 5. Sweep `alpha in {0.20, 0.30, 0.35}` against `alpha = 0.0` and report
          exact per-item Fix Set (`F_base \\ F_new`) and Regression Set
          (`F_new \\ F_base`).

Usage:
  python3 methods/surgical_diff_lora.py --self-test
"""

from __future__ import annotations

import argparse
import hashlib
import math
import statistics
import tempfile
from pathlib import Path
from typing import Any, Dict, List, Sequence, Tuple

import torch
import torch.nn as nn
import torch.nn.functional as F


class LinearLoRA(nn.Module):
    """Lightweight rank-r LoRA wrapper (`W_base + B @ A`) for a frozen nn.Linear."""

    def __init__(self, base_linear: nn.Linear, r: int = 16):
        super().__init__()
        self.base = base_linear
        for p in self.base.parameters():
            p.requires_grad = False
        self.r = r
        self.lora_A = nn.Parameter(
            torch.randn(r, base_linear.in_features, device=base_linear.weight.device, dtype=torch.float32) * 0.02
        )
        self.lora_B = nn.Parameter(
            torch.zeros(base_linear.out_features, r, device=base_linear.weight.device, dtype=torch.float32)
        )

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        out = self.base(x)
        delta = F.linear(F.linear(x.float(), self.lora_A), self.lora_B)
        return out + delta.to(out.dtype)

    @torch.no_grad()
    def delta_weight(self) -> torch.Tensor:
        return (self.lora_B @ self.lora_A).detach().float().cpu()


def compute_orth_sub(
    d_pos: Dict[str, torch.Tensor],
    d_neg: Dict[str, torch.Tensor],
    eps: float = 1e-12,
) -> Tuple[Dict[str, torch.Tensor], Dict[str, Any]]:
    """
    Exact Gram-Schmidt orthogonal subtraction (NEVER prune before subtract):
      ΔW_buf = ΔW_pos - (<ΔW_pos, ΔW_neg> / ||ΔW_neg||_F^2) * ΔW_neg
    """
    d_buf: Dict[str, torch.Tensor] = {}
    layer_cos: Dict[str, float] = {}
    all_cos: List[float] = []
    max_orth_resid = 0.0

    for k in sorted(d_pos.keys()):
        p = d_pos[k].float()
        n = d_neg[k].float()
        dot = float((p * n).sum().item())
        p_norm = float(p.norm().item())
        n_norm_sq = float((n * n).sum().item())
        n_norm = math.sqrt(max(n_norm_sq, eps))
        cos_val = dot / max(p_norm * n_norm, eps)
        layer_cos[k] = round(cos_val, 5)
        all_cos.append(cos_val)

        proj_coeff = dot / max(n_norm_sq, eps)
        buf = p - proj_coeff * n
        resid = abs(float((buf * n).sum().item())) / max(float(buf.norm().item()) * n_norm, eps)
        max_orth_resid = max(max_orth_resid, resid)
        d_buf[k] = buf

    stats = {
        "n_tensors": len(d_buf),
        "mean_cos_pos_neg": round(statistics.mean(all_cos), 5) if all_cos else 0.0,
        "min_cos_pos_neg": round(min(all_cos), 5) if all_cos else 0.0,
        "max_cos_pos_neg": round(max(all_cos), 5) if all_cos else 0.0,
        "max_post_orth_cos_residual": round(max_orth_resid, 8),
        "layer_cos": layer_cos,
    }
    return d_buf, stats


def save_svd_diff_module(
    d_buf: Dict[str, torch.Tensor],
    out_path: Path,
    meta: Dict[str, Any],
    svd_rank: int = 32,
) -> Dict[str, Any]:
    """Serialize ΔW_buf as a compact rank-`svd_rank` SVD capability module."""
    factors: Dict[str, Dict[str, torch.Tensor]] = {}
    for k, w in d_buf.items():
        U, S, Vh = torch.linalg.svd(w.float(), full_matrices=False)
        rk = min(svd_rank, S.shape[0])
        factors[k] = {
            "U": (U[:, :rk] * S[:rk].unsqueeze(0)).to(torch.float16).cpu(),
            "Vh": Vh[:rk, :].to(torch.float16).cpu(),
        }
    out_path.parent.mkdir(parents=True, exist_ok=True)
    torch.save({"factors": factors, "meta": meta}, out_path)
    h = hashlib.sha256(out_path.read_bytes()).hexdigest()
    return {"path": out_path.name, "bytes": out_path.stat().st_size, "sha256": h}


def load_svd_diff_module(path: Path) -> Dict[str, torch.Tensor]:
    payload = torch.load(path, map_location="cpu", weights_only=True)
    return {k: (v["U"].float() @ v["Vh"].float()) for k, v in payload["factors"].items()}


def apply_alpha_patch(
    base_weights: Dict[str, torch.Tensor],
    d_buf: Dict[str, torch.Tensor],
    alpha: float,
) -> Dict[str, torch.Tensor]:
    """Return W_new = W_base + alpha * ΔW_buf without mutating `base_weights`."""
    out: Dict[str, torch.Tensor] = {}
    for k, w in base_weights.items():
        if k in d_buf:
            out[k] = (w.float() + alpha * d_buf[k].float()).to(w.dtype)
        else:
            out[k] = w.clone()
    return out


def compute_fix_regression_sets(
    base_results: Dict[str, bool],
    new_results: Dict[str, bool],
) -> Dict[str, Any]:
    """Compute exact Fix Set (`F_base \\ F_new`) and Regression Set (`F_new \\ F_base`)."""
    f_base = {k for k, ok in base_results.items() if not ok}
    f_new = {k for k, ok in new_results.items() if not ok}
    fixed = sorted(f_base - f_new)
    regressed = sorted(f_new - f_base)
    return {
        "n_total": len(base_results),
        "base_pass": sum(base_results.values()),
        "new_pass": sum(new_results.values()),
        "fixed_count": len(fixed),
        "regressed_count": len(regressed),
        "net_gain": len(fixed) - len(regressed),
        "fixed_ids": fixed,
        "regressed_ids": regressed,
    }


def select_best_alpha(
    alpha_sweep: Sequence[Tuple[float, Dict[str, Any], Dict[str, Any]]],
    max_guard_regressions: int = 0,
) -> Tuple[float, str]:
    """Auto-Loop selector: pick alpha with highest target net_gain subject to guard constraint."""
    best_alpha = 0.0
    best_gain = 0
    reason = "revert_to_base_no_safe_gain"
    for alpha, target_fr, guard_fr in alpha_sweep:
        if guard_fr["regressed_count"] > max_guard_regressions:
            continue
        if target_fr["net_gain"] > best_gain:
            best_gain = target_fr["net_gain"]
            best_alpha = alpha
            reason = f"selected_alpha_{alpha}_net_gain_{best_gain}"
    return best_alpha, reason


def run_self_test() -> Dict[str, Any]:
    torch.manual_seed(2026)

    # 1. Verify LinearLoRA freezes base weights and produces exact rank-r delta
    base_lin = nn.Linear(64, 48, bias=False)
    base_snap = base_lin.weight.detach().clone()
    lora_pos = LinearLoRA(base_lin, r=8)
    lora_neg = LinearLoRA(base_lin, r=8)

    x = torch.randn(8, 64)
    y_pos = torch.randn(8, 48)
    y_neg = -y_pos + 0.3 * torch.randn(8, 48)

    for mod, tgt in ((lora_pos, y_pos), (lora_neg, y_neg)):
        opt = torch.optim.Adam(mod.parameters(), lr=1e-2)
        for _ in range(15):
            loss = F.mse_loss(mod(x), tgt)
            opt.zero_grad()
            loss.backward()
            opt.step()

    assert float((base_lin.weight.detach() - base_snap).abs().max().item()) == 0.0

    # 2. Verify exact Gram-Schmidt orth_sub: <ΔW_buf, ΔW_neg> == 0
    d_pos = {"L0.gate_proj": lora_pos.delta_weight()}
    d_neg = {"L0.gate_proj": lora_neg.delta_weight()}
    d_buf, stats = compute_orth_sub(d_pos, d_neg)
    assert stats["max_post_orth_cos_residual"] < 1e-5, f"Orthogonality failed: {stats}"

    # 3. Verify compact SVD serialization round-trip (rank <= 2*r = 16)
    with tempfile.TemporaryDirectory() as tmp:
        mod_path = Path(tmp) / "diff_module.pt"
        save_svd_diff_module(d_buf, mod_path, meta={"r": 8}, svd_rank=16)
        loaded = load_svd_diff_module(mod_path)
        rec_err = float((loaded["L0.gate_proj"] - d_buf["L0.gate_proj"]).abs().max().item())
        assert rec_err < 1e-2, f"SVD round-trip error too large: {rec_err}"

    # 4. Verify Fix/Regression set algebra and Auto-Loop alpha selection
    base_res = {"c1": False, "c2": False, "c3": True, "c4": True}
    new_res = {"c1": True, "c2": False, "c3": True, "c4": True}
    guard_ok = {"g1": True, "g2": True}
    guard_bad = {"g1": True, "g2": False}
    fr_target = compute_fix_regression_sets(base_res, new_res)
    fr_guard_ok = compute_fix_regression_sets(guard_ok, guard_ok)
    fr_guard_bad = compute_fix_regression_sets(guard_ok, guard_bad)
    assert fr_target["fixed_ids"] == ["c1"] and fr_target["regressed_ids"] == []
    alpha, _ = select_best_alpha([(0.20, fr_target, fr_guard_ok), (0.35, fr_target, fr_guard_bad)], max_guard_regressions=0)
    assert alpha == 0.20

    print(
        f"SURGICAL_DIFF_LORA_SELF_TEST_PASS "
        f"(orth_resid={stats['max_post_orth_cos_residual']}, svd_err={rec_err:.5f}, best_alpha={alpha})"
    )
    return {"orth_resid": stats["max_post_orth_cos_residual"], "svd_err": round(rec_err, 5), "best_alpha": alpha}


def main() -> None:
    ap = argparse.ArgumentParser(description="Surgical Diff-LoRA 5-Step orth_sub Auto-Loop.")
    ap.add_argument("--self-test", action="store_true", help="Run offline orth_sub & alpha-sweep self-test.")
    args = ap.parse_args()
    if args.self_test:
        run_self_test()
    else:
        ap.print_help()


if __name__ == "__main__":
    main()