enginil commited on
Commit
829ebb9
·
verified ·
1 Parent(s): 15557f0

Upload 00_probe_freeze_and_export.py

Browse files
Files changed (1) hide show
  1. 00_probe_freeze_and_export.py +113 -0
00_probe_freeze_and_export.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3.11
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import json
6
+ from pathlib import Path
7
+
8
+ import numpy as np
9
+ import torch
10
+ from PIL import Image
11
+
12
+ from spandrel_source import (
13
+ freeze_spandrel_reparameterized_convs,
14
+ load_spandrel_model,
15
+ )
16
+
17
+
18
+ def metrics(a: np.ndarray, b: np.ndarray) -> dict[str, float]:
19
+ aa = a.astype(np.float64, copy=False).ravel()
20
+ bb = b.astype(np.float64, copy=False).ravel()
21
+ d = aa - bb
22
+ denom = np.linalg.norm(aa) * np.linalg.norm(bb)
23
+ return {
24
+ "max_abs_diff": float(np.max(np.abs(d))),
25
+ "mean_abs_diff": float(np.mean(np.abs(d))),
26
+ "rmse": float(np.sqrt(np.mean(d * d))),
27
+ "cosine": float(np.dot(aa, bb) / denom) if denom else float("nan"),
28
+ }
29
+
30
+
31
+ def make_input(image: str, tile: int) -> torch.Tensor:
32
+ if not image:
33
+ torch.manual_seed(12345)
34
+ return torch.rand(1, 3, tile, tile, dtype=torch.float32)
35
+
36
+ im = Image.open(Path(image).expanduser().resolve()).convert("RGB")
37
+ if im.width < tile or im.height < tile:
38
+ raise ValueError(f"image smaller than {tile}x{tile}: {im.size}")
39
+ x0 = (im.width - tile) // 2
40
+ y0 = (im.height - tile) // 2
41
+ im = im.crop((x0, y0, x0 + tile, y0 + tile))
42
+ arr = np.asarray(im, dtype=np.float32) / 255.0
43
+ return torch.from_numpy(arr).permute(2, 0, 1).unsqueeze(0).contiguous()
44
+
45
+
46
+ def print_metrics(title: str, m: dict[str, float]) -> None:
47
+ print(f"\n=== {title} ===")
48
+ for k, v in m.items():
49
+ print(f"{k:16s}: {v:.12g}")
50
+
51
+
52
+ def main():
53
+ ap = argparse.ArgumentParser(
54
+ description="Freeze Spandrel's own eval-time reparameterization, prove parity, then torch.export."
55
+ )
56
+ ap.add_argument("--weights", required=True)
57
+ ap.add_argument("--image", default="")
58
+ ap.add_argument("--tile", type=int, default=512)
59
+ args = ap.parse_args()
60
+
61
+ x = make_input(args.image, args.tile)
62
+
63
+ print("[1/5] Loading fresh REAL Spandrel oracle...")
64
+ oracle, _, info = load_spandrel_model(
65
+ args.weights, device="cpu", dtype=torch.float32
66
+ )
67
+ print(json.dumps(info, indent=2))
68
+
69
+ print("[2/5] Running real Spandrel oracle with torch.no_grad()...")
70
+ # Deliberately NOT torch.inference_mode(): SPAN mutates eval_conv state.
71
+ with torch.no_grad():
72
+ y_oracle = oracle(x).detach().cpu().numpy()
73
+ print(f"oracle shape : {y_oracle.shape}")
74
+ print(f"oracle min/max : {float(y_oracle.min())} / {float(y_oracle.max())}")
75
+
76
+ print("[3/5] Loading a second fresh Spandrel model and freezing Spandrel's OWN fused eval convs...")
77
+ source, _, _ = load_spandrel_model(
78
+ args.weights, device="cpu", dtype=torch.float32
79
+ )
80
+ frozen, replaced = freeze_spandrel_reparameterized_convs(source)
81
+ print(f"replaced modules: {len(replaced)}")
82
+ for name in replaced:
83
+ print(f" - {name}")
84
+
85
+ with torch.no_grad():
86
+ y_frozen = frozen(x).detach().cpu().numpy()
87
+
88
+ m1 = metrics(y_oracle, y_frozen)
89
+ print_metrics("REAL Spandrel vs frozen Spandrel", m1)
90
+ if m1["mean_abs_diff"] > 1e-7 or m1["cosine"] < 0.999999999:
91
+ raise SystemExit(
92
+ "FAIL: freezing changed the Spandrel model. Do NOT convert."
93
+ )
94
+
95
+ print("\n[4/5] torch.export frozen exact-Spandrel graph...")
96
+ exported = torch.export.export(frozen, args=(x,))
97
+ with torch.no_grad():
98
+ y_exported = exported.module()(x).detach().cpu().numpy()
99
+
100
+ m2 = metrics(y_oracle, y_exported)
101
+ print_metrics("REAL Spandrel vs ExportedProgram", m2)
102
+ if m2["mean_abs_diff"] > 1e-7 or m2["cosine"] < 0.999999999:
103
+ raise SystemExit(
104
+ "FAIL: torch.export changed the model. Do NOT convert."
105
+ )
106
+
107
+ print("\n[5/5] PASS")
108
+ print("The exportable graph is numerically the real Spandrel model.")
109
+ print("Safe to proceed to Core AI conversion.")
110
+
111
+
112
+ if __name__ == "__main__":
113
+ main()