enginil commited on
Commit
15557f0
·
verified ·
1 Parent(s): 30add08

Upload 9 files

Browse files
.gitattributes CHANGED
@@ -1,36 +1,2 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
  *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
33
- *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
36
- ClearRealityV1_4x_CoreAI.aimodel/main.mlirb filter=lfs diff=lfs merge=lfs -text
 
1
+ *.aimodel filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  *.safetensors filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
01_convert_coreai.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3.11
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import asyncio
6
+ import json
7
+ from pathlib import Path
8
+
9
+ import numpy as np
10
+ import torch
11
+ import coreai_torch
12
+ from coreai.runtime import AIModel, NDArray
13
+
14
+ from spandrel_source import (
15
+ freeze_spandrel_reparameterized_convs,
16
+ load_spandrel_model,
17
+ )
18
+
19
+
20
+ def metrics(a: np.ndarray, b: np.ndarray) -> dict[str, float]:
21
+ aa = a.astype(np.float64, copy=False).ravel()
22
+ bb = b.astype(np.float64, copy=False).ravel()
23
+ d = aa - bb
24
+ denom = np.linalg.norm(aa) * np.linalg.norm(bb)
25
+ return {
26
+ "max_abs_diff": float(np.max(np.abs(d))),
27
+ "mean_abs_diff": float(np.mean(np.abs(d))),
28
+ "rmse": float(np.sqrt(np.mean(d * d))),
29
+ "cosine": float(np.dot(aa, bb) / denom) if denom else float("nan"),
30
+ }
31
+
32
+
33
+ async def run_coreai(path: Path, x: np.ndarray) -> np.ndarray:
34
+ model = await AIModel.load(str(path))
35
+ fn = model.load_function("main")
36
+ result = await fn({"image": NDArray(data=x.astype(np.float32, copy=False))})
37
+ return np.asarray(result["output"].numpy())
38
+
39
+
40
+ async def amain():
41
+ ap = argparse.ArgumentParser(
42
+ description="ClearRealityV1: exact Spandrel -> frozen static graph -> Core AI."
43
+ )
44
+ ap.add_argument("--weights", required=True)
45
+ ap.add_argument("--output", required=True)
46
+ ap.add_argument("--tile", type=int, default=512)
47
+ args = ap.parse_args()
48
+
49
+ weights = Path(args.weights).expanduser().resolve()
50
+ output = Path(args.output).expanduser().resolve()
51
+ output.parent.mkdir(parents=True, exist_ok=True)
52
+
53
+ torch.manual_seed(12345)
54
+ x = torch.rand(1, 3, args.tile, args.tile, dtype=torch.float32)
55
+
56
+ print("[1/8] Loading fresh REAL Spandrel oracle...")
57
+ oracle, _, info = load_spandrel_model(weights, device="cpu", dtype=torch.float32)
58
+ print(json.dumps(info, indent=2))
59
+ with torch.no_grad():
60
+ y_oracle = oracle(x).detach().cpu().numpy()
61
+
62
+ print("[2/8] Loading fresh Spandrel source and freezing its own fused eval convs...")
63
+ source, _, _ = load_spandrel_model(weights, device="cpu", dtype=torch.float32)
64
+ frozen, replaced = freeze_spandrel_reparameterized_convs(source)
65
+ print(f" replaced reparameterizing modules: {len(replaced)}")
66
+
67
+ with torch.no_grad():
68
+ y_frozen = frozen(x).detach().cpu().numpy()
69
+ mf = metrics(y_oracle, y_frozen)
70
+ print(" REAL Spandrel <-> frozen:")
71
+ for k, v in mf.items():
72
+ print(f" {k:15s}: {v:.12g}")
73
+ if mf["mean_abs_diff"] > 1e-7 or mf["cosine"] < 0.999999999:
74
+ raise RuntimeError("Refusing conversion: frozen model != real Spandrel.")
75
+
76
+ print("[3/8] torch.export static exact-Spandrel graph...")
77
+ exported = torch.export.export(frozen, args=(x,))
78
+ with torch.no_grad():
79
+ y_exported = exported.module()(x).detach().cpu().numpy()
80
+ me = metrics(y_oracle, y_exported)
81
+ print(" REAL Spandrel <-> ExportedProgram:")
82
+ for k, v in me.items():
83
+ print(f" {k:15s}: {v:.12g}")
84
+ if me["mean_abs_diff"] > 1e-7 or me["cosine"] < 0.999999999:
85
+ raise RuntimeError("Refusing conversion: ExportedProgram != real Spandrel.")
86
+
87
+ print("[4/8] Core AI decompositions...")
88
+ exported = exported.run_decompositions(coreai_torch.get_decomp_table())
89
+
90
+ print("[5/8] Torch -> Core AI...")
91
+ program = (
92
+ coreai_torch.TorchConverter()
93
+ .add_exported_program(
94
+ exported,
95
+ input_names=["image"],
96
+ output_names=["output"],
97
+ )
98
+ .to_coreai()
99
+ )
100
+
101
+ print("[6/8] Core AI optimize...")
102
+ program.optimize()
103
+
104
+ print("[7/8] Saving .aimodel...")
105
+ program.save_asset(output)
106
+ print(f" {output}")
107
+
108
+ print("[8/8] Immediate REAL Spandrel <-> saved Core AI validation...")
109
+ y_core = await run_coreai(output, x.cpu().numpy())
110
+ mc = metrics(y_oracle, y_core)
111
+ for k, v in mc.items():
112
+ print(f" {k:15s}: {v:.12g}")
113
+ print(f" spandrel min/max: {float(y_oracle.min())} / {float(y_oracle.max())}")
114
+ print(f" coreai min/max: {float(y_core.min())} / {float(y_core.max())}")
115
+
116
+ if mc["mean_abs_diff"] > 5e-4 or mc["cosine"] < 0.99999:
117
+ raise RuntimeError("FAIL: Core AI differs too much from REAL Spandrel.")
118
+
119
+ print("PASS: saved Core AI model matches the real Spandrel source.")
120
+
121
+
122
+ if __name__ == "__main__":
123
+ asyncio.run(amain())
02_validate_real_crop.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3.11
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import asyncio
6
+ from pathlib import Path
7
+
8
+ import numpy as np
9
+ from PIL import Image
10
+ import torch
11
+ from coreai.runtime import AIModel, NDArray
12
+
13
+ from spandrel_source import load_spandrel_model
14
+
15
+
16
+ def metrics(a: np.ndarray, b: np.ndarray):
17
+ aa = a.astype(np.float64, copy=False).ravel()
18
+ bb = b.astype(np.float64, copy=False).ravel()
19
+ d = aa - bb
20
+ denom = np.linalg.norm(aa) * np.linalg.norm(bb)
21
+ return {
22
+ "max_abs_diff": float(np.max(np.abs(d))),
23
+ "mean_abs_diff": float(np.mean(np.abs(d))),
24
+ "rmse": float(np.sqrt(np.mean(d*d))),
25
+ "cosine": float(np.dot(aa, bb)/denom) if denom else float("nan"),
26
+ }
27
+
28
+
29
+ def center_crop(path: Path, tile: int):
30
+ im = Image.open(path).convert("RGB")
31
+ if im.width < tile or im.height < tile:
32
+ raise ValueError(f"image smaller than tile: {im.size}")
33
+ x0 = (im.width-tile)//2
34
+ y0 = (im.height-tile)//2
35
+ im = im.crop((x0,y0,x0+tile,y0+tile))
36
+ arr = np.asarray(im, dtype=np.float32)/255.0
37
+ return torch.from_numpy(arr).permute(2,0,1).unsqueeze(0).contiguous()
38
+
39
+
40
+ async def amain():
41
+ ap = argparse.ArgumentParser()
42
+ ap.add_argument("--weights", required=True)
43
+ ap.add_argument("--aimodel", required=True)
44
+ ap.add_argument("--image", required=True)
45
+ ap.add_argument("--tile", type=int, default=512)
46
+ ap.add_argument("--source-mode", choices=["cpu-fp32","mps-fp16"], default="mps-fp16")
47
+ args = ap.parse_args()
48
+
49
+ x = center_crop(Path(args.image).expanduser().resolve(), args.tile)
50
+
51
+ if args.source_mode == "mps-fp16":
52
+ model, _, _ = load_spandrel_model(args.weights, device="mps", dtype=torch.float16)
53
+ with torch.no_grad():
54
+ ref = model(x.to("mps", dtype=torch.float16)).float().cpu().numpy()
55
+ else:
56
+ model, _, _ = load_spandrel_model(args.weights, device="cpu", dtype=torch.float32)
57
+ with torch.no_grad():
58
+ ref = model(x).cpu().numpy()
59
+
60
+ ai = await AIModel.load(str(Path(args.aimodel).expanduser().resolve()))
61
+ fn = ai.load_function("main")
62
+ result = await fn({"image": NDArray(data=x.numpy().astype(np.float32, copy=False))})
63
+ core = np.asarray(result["output"].numpy())
64
+
65
+ print(f"source_mode: {args.source_mode}")
66
+ for k,v in metrics(ref,core).items():
67
+ print(f"{k:16s}: {v:.12g}")
68
+ print(f"spandrel min/max: {float(ref.min())} / {float(ref.max())}")
69
+ print(f"coreai min/max: {float(core.min())} / {float(core.max())}")
70
+
71
+
72
+ if __name__ == "__main__":
73
+ asyncio.run(amain())
03_inference_coreai.py ADDED
@@ -0,0 +1,375 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3.11
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import asyncio
6
+ import math
7
+ from pathlib import Path
8
+ import time
9
+
10
+ import numpy as np
11
+ from PIL import Image
12
+ from coreai.runtime import AIModel, NDArray
13
+
14
+
15
+ # ClearRealityV1 Core AI contract for the model we converted:
16
+ # input : 1 x 3 x 512 x 512
17
+ # output : 1 x 3 x 2048 x 2048
18
+ #
19
+ # Tile size is therefore fixed for THIS .aimodel. Overlap and blending are
20
+ # inference-time choices and remain configurable.
21
+ MODEL_TILE = 512
22
+ NATIVE_SCALE = 4
23
+
24
+
25
+ def load_rgb01(path: str | Path) -> np.ndarray:
26
+ image = Image.open(Path(path).expanduser().resolve()).convert("RGB")
27
+ return np.asarray(image, dtype=np.float32) / 255.0
28
+
29
+
30
+ def save_rgb01(
31
+ arr: np.ndarray,
32
+ path: str | Path,
33
+ *,
34
+ jpeg_quality: int = 95,
35
+ jpeg_subsampling: int = 0,
36
+ ) -> None:
37
+ path = Path(path).expanduser().resolve()
38
+ path.parent.mkdir(parents=True, exist_ok=True)
39
+
40
+ u8 = np.rint(np.clip(arr, 0.0, 1.0) * 255.0).astype(np.uint8)
41
+ image = Image.fromarray(u8, mode="RGB")
42
+
43
+ suffix = path.suffix.lower()
44
+ if suffix == ".png":
45
+ image.save(path)
46
+ elif suffix in {".jpg", ".jpeg"}:
47
+ image.save(path, quality=jpeg_quality, subsampling=jpeg_subsampling)
48
+ else:
49
+ raise ValueError("output extension must be .png, .jpg, or .jpeg")
50
+
51
+
52
+ def balanced_tile_positions(
53
+ length: int,
54
+ tile: int,
55
+ min_overlap: int,
56
+ ) -> list[int]:
57
+ """Evenly distribute tile starts while guaranteeing >= min_overlap.
58
+
59
+ Example:
60
+ length=1024, tile=512, min_overlap=64
61
+ -> starts [0, 256, 512]
62
+ -> actual overlaps [256, 256]
63
+
64
+ This avoids the old asymmetric [0, 448, 512] layout.
65
+ """
66
+ if tile <= 0:
67
+ raise ValueError("tile must be > 0")
68
+ if min_overlap < 0 or min_overlap >= tile:
69
+ raise ValueError("overlap must satisfy 0 <= overlap < tile")
70
+ if length <= tile:
71
+ return [0]
72
+
73
+ distance = length - tile
74
+ max_stride = tile - min_overlap
75
+ intervals = max(1, math.ceil(distance / max_stride))
76
+
77
+ q, r = divmod(distance, intervals)
78
+ starts = [0]
79
+ pos = 0
80
+ for i in range(intervals):
81
+ pos += q + (1 if i < r else 0)
82
+ starts.append(pos)
83
+
84
+ return starts
85
+
86
+
87
+ def actual_overlaps(positions: list[int], tile: int) -> list[int]:
88
+ return [
89
+ positions[i] + tile - positions[i + 1]
90
+ for i in range(len(positions) - 1)
91
+ ]
92
+
93
+
94
+ def pad_tile_edge(
95
+ tile_arr: np.ndarray,
96
+ target_h: int,
97
+ target_w: int,
98
+ ) -> tuple[np.ndarray, int, int]:
99
+ h, w = tile_arr.shape[:2]
100
+ pad_h = max(0, target_h - h)
101
+ pad_w = max(0, target_w - w)
102
+
103
+ if pad_h or pad_w:
104
+ tile_arr = np.pad(
105
+ tile_arr,
106
+ ((0, pad_h), (0, pad_w), (0, 0)),
107
+ mode="edge",
108
+ )
109
+
110
+ return tile_arr, h, w
111
+
112
+
113
+ def fade_in(length: int, mode: str) -> np.ndarray:
114
+ """Return a 0 -> 1 feather ramp."""
115
+ if length <= 0:
116
+ return np.empty((0,), dtype=np.float32)
117
+ if length == 1:
118
+ return np.ones((1,), dtype=np.float32)
119
+
120
+ t = np.linspace(0.0, 1.0, length, dtype=np.float32)
121
+
122
+ if mode == "cosine":
123
+ # Raised cosine: smooth derivative at both ends.
124
+ return 0.5 - 0.5 * np.cos(np.pi * t)
125
+ if mode == "linear":
126
+ return t
127
+ if mode == "uniform":
128
+ return np.ones((length,), dtype=np.float32)
129
+
130
+ raise ValueError(f"unsupported blend mode: {mode}")
131
+
132
+
133
+ def axis_blend_weights(
134
+ positions: list[int],
135
+ index: int,
136
+ tile: int,
137
+ valid_length: int,
138
+ scale: int,
139
+ mode: str,
140
+ ) -> np.ndarray:
141
+ """1-D feather weights based on this tile's ACTUAL neighbor overlaps."""
142
+ p = positions[index]
143
+ valid_out = valid_length * scale
144
+ weights = np.ones((valid_out,), dtype=np.float32)
145
+
146
+ if index > 0:
147
+ prev = positions[index - 1]
148
+ left_overlap = max(0, prev + tile - p)
149
+ n = min(valid_out, left_overlap * scale)
150
+ if n > 0:
151
+ weights[:n] *= fade_in(n, mode)
152
+
153
+ if index + 1 < len(positions):
154
+ nxt = positions[index + 1]
155
+ right_overlap = max(0, p + tile - nxt)
156
+ n = min(valid_out, right_overlap * scale)
157
+ if n > 0:
158
+ weights[-n:] *= fade_in(n, mode)[::-1]
159
+
160
+ return weights
161
+
162
+
163
+ def downsample_4x_to_2x_float32(image_rgb01: np.ndarray) -> np.ndarray:
164
+ """Native 4x output -> optional final 2x without an 8-bit intermediate."""
165
+ h, w, c = image_rgb01.shape
166
+ if c != 3:
167
+ raise ValueError(f"expected RGB image, got {image_rgb01.shape}")
168
+
169
+ target = (w // 2, h // 2)
170
+ clipped = np.clip(image_rgb01, 0.0, 1.0)
171
+
172
+ channels = []
173
+ for channel in range(3):
174
+ plane = Image.fromarray(
175
+ clipped[..., channel].astype(np.float32),
176
+ mode="F",
177
+ )
178
+ plane = plane.resize(target, resample=Image.Resampling.LANCZOS)
179
+ channels.append(np.asarray(plane, dtype=np.float32))
180
+
181
+ return np.stack(channels, axis=-1)
182
+
183
+
184
+ async def amain() -> None:
185
+ parser = argparse.ArgumentParser(
186
+ description=(
187
+ "ClearRealityV1 Core AI upscaler with balanced tile placement "
188
+ "and weighted overlap blending."
189
+ )
190
+ )
191
+ parser.add_argument("--model", required=True, help="ClearRealityV1 .aimodel")
192
+ parser.add_argument("--input", required=True, help="Input image")
193
+ parser.add_argument("--output", required=True, help="Output .png/.jpg/.jpeg")
194
+ parser.add_argument(
195
+ "--overlap",
196
+ type=int,
197
+ default=64,
198
+ help=(
199
+ "Minimum overlap in INPUT pixels (default: 64). "
200
+ "Balanced placement may make the actual overlap larger."
201
+ ),
202
+ )
203
+ parser.add_argument(
204
+ "--blend",
205
+ choices=("cosine", "linear", "uniform"),
206
+ default="cosine",
207
+ help=(
208
+ "Overlap blending: cosine (default/recommended), linear, "
209
+ "or uniform averaging."
210
+ ),
211
+ )
212
+ parser.add_argument(
213
+ "--output-scale",
214
+ type=int,
215
+ choices=(2, 4),
216
+ default=4,
217
+ help=(
218
+ "4 = native model output (default); "
219
+ "2 = native 4x SR followed by Lanczos downsampling."
220
+ ),
221
+ )
222
+ parser.add_argument(
223
+ "--jpeg-quality",
224
+ type=int,
225
+ default=95,
226
+ help="JPEG quality (default: 95). PNG is lossless.",
227
+ )
228
+ parser.add_argument(
229
+ "--jpeg-subsampling",
230
+ type=int,
231
+ choices=(0, 1, 2),
232
+ default=0,
233
+ help="0=4:4:4 (default), 1=4:2:2, 2=4:2:0.",
234
+ )
235
+ args = parser.parse_args()
236
+
237
+ if not (0 <= args.overlap < MODEL_TILE):
238
+ raise SystemExit(
239
+ f"--overlap must satisfy 0 <= overlap < {MODEL_TILE}; "
240
+ f"got {args.overlap}"
241
+ )
242
+
243
+ image = load_rgb01(args.input)
244
+ h, w = image.shape[:2]
245
+ model_path = Path(args.model).expanduser().resolve()
246
+
247
+ ys = balanced_tile_positions(h, MODEL_TILE, args.overlap)
248
+ xs = balanced_tile_positions(w, MODEL_TILE, args.overlap)
249
+
250
+ print(f"input : {w}x{h}")
251
+ print(f"model tile : {MODEL_TILE}x{MODEL_TILE} (fixed by .aimodel)")
252
+ print(f"min overlap : {args.overlap}")
253
+ print(f"blend : {args.blend}")
254
+ print(f"model scale : {NATIVE_SCALE}x")
255
+ print(f"output scale: {args.output_scale}x")
256
+ print(f"x positions : {xs}")
257
+ print(f"y positions : {ys}")
258
+ if len(xs) > 1:
259
+ print(f"x overlaps : {actual_overlaps(xs, MODEL_TILE)}")
260
+ if len(ys) > 1:
261
+ print(f"y overlaps : {actual_overlaps(ys, MODEL_TILE)}")
262
+ print("loading Core AI model...")
263
+
264
+ model = await AIModel.load(str(model_path))
265
+ fn = model.load_function("main")
266
+
267
+ async def infer_one(tile_hwc: np.ndarray) -> np.ndarray:
268
+ x = np.ascontiguousarray(
269
+ tile_hwc.transpose(2, 0, 1)[None],
270
+ dtype=np.float32,
271
+ )
272
+ result = await fn({"image": NDArray(data=x)})
273
+ y = np.asarray(result["output"].numpy(), dtype=np.float32)
274
+ return np.ascontiguousarray(y[0].transpose(1, 2, 0))
275
+
276
+ out_h = h * NATIVE_SCALE
277
+ out_w = w * NATIVE_SCALE
278
+
279
+ # Instead of hard cuts, every overlapping prediction contributes to an
280
+ # accumulation buffer using a smooth 2-D feather mask.
281
+ accum = np.zeros((out_h, out_w, 3), dtype=np.float32)
282
+ weight_sum = np.zeros((out_h, out_w, 1), dtype=np.float32)
283
+
284
+ total = len(ys) * len(xs)
285
+ n = 0
286
+ t0 = time.perf_counter()
287
+
288
+ for yi, y in enumerate(ys):
289
+ for xi, x in enumerate(xs):
290
+ n += 1
291
+ print(
292
+ f"\rCore AI tile {n}/{total} @ x={x}, y={y}",
293
+ end="",
294
+ flush=True,
295
+ )
296
+
297
+ y1 = min(y + MODEL_TILE, h)
298
+ x1 = min(x + MODEL_TILE, w)
299
+ crop = image[y:y1, x:x1]
300
+ crop, valid_h, valid_w = pad_tile_edge(
301
+ crop,
302
+ MODEL_TILE,
303
+ MODEL_TILE,
304
+ )
305
+
306
+ pred = await infer_one(crop)
307
+
308
+ expected = (
309
+ MODEL_TILE * NATIVE_SCALE,
310
+ MODEL_TILE * NATIVE_SCALE,
311
+ 3,
312
+ )
313
+ if pred.shape != expected:
314
+ raise RuntimeError(
315
+ f"Core AI returned {pred.shape}, expected {expected}"
316
+ )
317
+
318
+ pred = pred[
319
+ : valid_h * NATIVE_SCALE,
320
+ : valid_w * NATIVE_SCALE,
321
+ ]
322
+
323
+ wy = axis_blend_weights(
324
+ ys, yi, MODEL_TILE, valid_h, NATIVE_SCALE, args.blend
325
+ )
326
+ wx = axis_blend_weights(
327
+ xs, xi, MODEL_TILE, valid_w, NATIVE_SCALE, args.blend
328
+ )
329
+ weight = (wy[:, None] * wx[None, :])[..., None]
330
+
331
+ oy0 = y * NATIVE_SCALE
332
+ ox0 = x * NATIVE_SCALE
333
+ oy1 = oy0 + pred.shape[0]
334
+ ox1 = ox0 + pred.shape[1]
335
+
336
+ accum[oy0:oy1, ox0:ox1] += pred * weight
337
+ weight_sum[oy0:oy1, ox0:ox1] += weight
338
+
339
+ print()
340
+
341
+ if np.any(weight_sum <= 0.0):
342
+ count = int(np.count_nonzero(weight_sum <= 0.0))
343
+ raise RuntimeError(
344
+ f"blending produced {count} pixels with zero total weight"
345
+ )
346
+
347
+ out4 = accum / weight_sum
348
+ out4 = np.clip(out4, 0.0, 1.0)
349
+
350
+ if args.output_scale == 2:
351
+ print("downsampling native 4x output -> final 2x with Lanczos...")
352
+ final = downsample_4x_to_2x_float32(out4)
353
+ else:
354
+ final = out4
355
+
356
+ save_rgb01(
357
+ final,
358
+ args.output,
359
+ jpeg_quality=args.jpeg_quality,
360
+ jpeg_subsampling=args.jpeg_subsampling,
361
+ )
362
+
363
+ elapsed = time.perf_counter() - t0
364
+ final_h, final_w = final.shape[:2]
365
+
366
+ print(f"output : {Path(args.output).expanduser().resolve()}")
367
+ print(f"output size : {final_w}x{final_h}")
368
+ print(f"elapsed : {elapsed:.2f}s")
369
+
370
+ if args.output_scale == 2:
371
+ print("note : 2x = native 4x SR -> Lanczos final downsample.")
372
+
373
+
374
+ if __name__ == "__main__":
375
+ asyncio.run(amain())
04_compare_full_image.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3.11
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import asyncio
6
+ from pathlib import Path
7
+ import time
8
+
9
+ import numpy as np
10
+ from PIL import Image
11
+ import torch
12
+ from coreai.runtime import AIModel, NDArray
13
+
14
+ from spandrel_source import load_spandrel_model
15
+ from tiling import (
16
+ keep_interval,
17
+ load_rgb01,
18
+ pad_tile_edge,
19
+ save_rgb01,
20
+ tile_positions,
21
+ )
22
+
23
+
24
+ def metrics(a: np.ndarray, b: np.ndarray) -> dict[str, float]:
25
+ aa = a.astype(np.float64, copy=False).ravel()
26
+ bb = b.astype(np.float64, copy=False).ravel()
27
+ d = aa - bb
28
+ denom = np.linalg.norm(aa) * np.linalg.norm(bb)
29
+ return {
30
+ "max_abs_diff": float(np.max(np.abs(d))),
31
+ "mean_abs_diff": float(np.mean(np.abs(d))),
32
+ "rmse": float(np.sqrt(np.mean(d * d))),
33
+ "cosine": float(np.dot(aa, bb) / denom) if denom else float("nan"),
34
+ }
35
+
36
+
37
+ def save_difference_x20(a: np.ndarray, b: np.ndarray, path: Path) -> None:
38
+ diff = np.clip(np.abs(a - b) * 20.0, 0.0, 1.0)
39
+ save_rgb01(diff, path)
40
+
41
+
42
+ async def amain():
43
+ ap = argparse.ArgumentParser(
44
+ description=(
45
+ "End-to-end full-image parity: real Spandrel MPS FP16 vs Core AI, "
46
+ "same 512/64 midpoint-discard tiling."
47
+ )
48
+ )
49
+ ap.add_argument("--weights", required=True)
50
+ ap.add_argument("--aimodel", required=True)
51
+ ap.add_argument("--image", required=True)
52
+ ap.add_argument("--output-dir", required=True)
53
+ ap.add_argument("--tile", type=int, default=512)
54
+ ap.add_argument("--overlap", type=int, default=64)
55
+ ap.add_argument("--scale", type=int, default=4)
56
+ ap.add_argument(
57
+ "--visual-format",
58
+ choices=["png", "jpg"],
59
+ default="jpg",
60
+ help="jpg is much smaller for large 4x photographs; metrics use raw tensors regardless.",
61
+ )
62
+ ap.add_argument("--jpeg-quality", type=int, default=95)
63
+ args = ap.parse_args()
64
+
65
+ output_dir = Path(args.output_dir).expanduser().resolve()
66
+ output_dir.mkdir(parents=True, exist_ok=True)
67
+
68
+ image = load_rgb01(args.image)
69
+ h, w = image.shape[:2]
70
+ ys = tile_positions(h, args.tile, args.overlap)
71
+ xs = tile_positions(w, args.tile, args.overlap)
72
+ total = len(ys) * len(xs)
73
+
74
+ print(f"input : {w}x{h}")
75
+ print(f"output : {w*args.scale}x{h*args.scale}")
76
+ print(f"tile/overlap: {args.tile}/{args.overlap}")
77
+ print(f"tiles : {total}")
78
+
79
+ print("\nLoading REAL Spandrel source on MPS FP16...")
80
+ spandrel, _, _ = load_spandrel_model(
81
+ args.weights, device="mps", dtype=torch.float16
82
+ )
83
+
84
+ print("Loading Core AI model...")
85
+ ai = await AIModel.load(str(Path(args.aimodel).expanduser().resolve()))
86
+ fn = ai.load_function("main")
87
+
88
+ # Full float32 arrays are intentional here because this is the final
89
+ # numerical parity test. For very large inputs they can use substantial RAM.
90
+ sp_out = np.empty((h * args.scale, w * args.scale, 3), dtype=np.float32)
91
+ ai_out = np.empty_like(sp_out)
92
+
93
+ async def coreai_tile(tile_hwc: np.ndarray) -> np.ndarray:
94
+ x = np.ascontiguousarray(tile_hwc.transpose(2, 0, 1)[None], dtype=np.float32)
95
+ result = await fn({"image": NDArray(data=x)})
96
+ y = np.asarray(result["output"].numpy(), dtype=np.float32)
97
+ return np.ascontiguousarray(y[0].transpose(1, 2, 0))
98
+
99
+ def spandrel_tile(tile_hwc: np.ndarray) -> np.ndarray:
100
+ x = torch.from_numpy(
101
+ np.ascontiguousarray(tile_hwc.transpose(2, 0, 1)[None])
102
+ ).to("mps", dtype=torch.float16)
103
+ # SPAN mutates its eval-time reparameterized conv state, so use
104
+ # no_grad rather than inference_mode for the exact reference runtime.
105
+ with torch.no_grad():
106
+ y = spandrel(x)
107
+ return np.ascontiguousarray(
108
+ y.float().cpu().numpy()[0].transpose(1, 2, 0)
109
+ )
110
+
111
+ t0 = time.perf_counter()
112
+ n = 0
113
+
114
+ for yi, y in enumerate(ys):
115
+ gy0, gy1 = keep_interval(ys, yi, args.tile, h)
116
+ for xi, x in enumerate(xs):
117
+ gx0, gx1 = keep_interval(xs, xi, args.tile, w)
118
+ n += 1
119
+ print(
120
+ f"\rComparing tile {n}/{total} @ x={x}, y={y}",
121
+ end="",
122
+ flush=True,
123
+ )
124
+
125
+ crop = image[y:min(y + args.tile, h), x:min(x + args.tile, w)]
126
+ crop, original_h, original_w = pad_tile_edge(
127
+ crop, args.tile, args.tile
128
+ )
129
+
130
+ sp = spandrel_tile(crop)
131
+ ca = await coreai_tile(crop)
132
+
133
+ expected = (args.tile * args.scale, args.tile * args.scale, 3)
134
+ if sp.shape != expected or ca.shape != expected:
135
+ raise RuntimeError(
136
+ f"unexpected tile outputs: Spandrel={sp.shape}, CoreAI={ca.shape}, "
137
+ f"expected={expected}"
138
+ )
139
+
140
+ sp = sp[: original_h * args.scale, : original_w * args.scale]
141
+ ca = ca[: original_h * args.scale, : original_w * args.scale]
142
+
143
+ ly0 = (gy0 - y) * args.scale
144
+ ly1 = (gy1 - y) * args.scale
145
+ lx0 = (gx0 - x) * args.scale
146
+ lx1 = (gx1 - x) * args.scale
147
+
148
+ dest = (
149
+ slice(gy0 * args.scale, gy1 * args.scale),
150
+ slice(gx0 * args.scale, gx1 * args.scale),
151
+ )
152
+ src = (slice(ly0, ly1), slice(lx0, lx1))
153
+
154
+ sp_out[dest] = sp[src]
155
+ ai_out[dest] = ca[src]
156
+
157
+ print()
158
+ elapsed = time.perf_counter() - t0
159
+
160
+ print("\n=== RAW full-image tensor parity ===")
161
+ raw = metrics(sp_out, ai_out)
162
+ for k, v in raw.items():
163
+ print(f"{k:16s}: {v:.12g}")
164
+
165
+ sp_clip = np.clip(sp_out, 0.0, 1.0)
166
+ ai_clip = np.clip(ai_out, 0.0, 1.0)
167
+
168
+ print("\n=== FINAL CLAMPED [0,1] image parity ===")
169
+ clipped = metrics(sp_clip, ai_clip)
170
+ for k, v in clipped.items():
171
+ print(f"{k:16s}: {v:.12g}")
172
+ print(f"mean_abs x255 : {clipped['mean_abs_diff']*255:.12g}")
173
+ print(f"rmse x255 : {clipped['rmse']*255:.12g}")
174
+ print(f"max_abs x255 : {clipped['max_abs_diff']*255:.12g}")
175
+
176
+ ext = ".png" if args.visual_format == "png" else ".jpg"
177
+ sp_path = output_dir / f"spandrel_mps_fp16{ext}"
178
+ ai_path = output_dir / f"coreai{ext}"
179
+ diff_path = output_dir / "difference_x20.png"
180
+
181
+ # For visual comparison, JPEG defaults here to high-quality 4:4:4 so the
182
+ # encoding does not create a fake difference. Both images use identical settings.
183
+ save_rgb01(
184
+ sp_clip, sp_path,
185
+ jpeg_quality=args.jpeg_quality,
186
+ jpeg_subsampling=0,
187
+ )
188
+ save_rgb01(
189
+ ai_clip, ai_path,
190
+ jpeg_quality=args.jpeg_quality,
191
+ jpeg_subsampling=0,
192
+ )
193
+ save_difference_x20(sp_clip, ai_clip, diff_path)
194
+
195
+ print("\nSaved:")
196
+ print(f" {sp_path}")
197
+ print(f" {ai_path}")
198
+ print(f" {diff_path}")
199
+ print(f"elapsed: {elapsed:.2f}s")
200
+
201
+
202
+ if __name__ == "__main__":
203
+ asyncio.run(amain())
requirements-conversion.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # Conversion / validation environment
2
+ # coreai-torch 0.4.2 reports official validation through torch 2.13.0.
3
+ torch==2.13.0
4
+ coreai-torch==0.4.2
5
+ spandrel==0.4.2
6
+ spandrel-extra-arches
7
+ numpy
8
+ Pillow
requirements-inference.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ coreai-core==1.0.0b2
2
+ numpy
3
+ Pillow
spandrel_source.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3.11
2
+ from __future__ import annotations
3
+
4
+ from copy import deepcopy
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ import torch
9
+ from spandrel import ModelLoader
10
+
11
+
12
+ def load_spandrel_model(
13
+ weights: str | Path,
14
+ *,
15
+ device: str = "cpu",
16
+ dtype: torch.dtype = torch.float32,
17
+ ):
18
+ """Load exactly the PyTorch module selected by Spandrel."""
19
+ weights = Path(weights).expanduser().resolve()
20
+ descriptor = ModelLoader().load_from_file(weights)
21
+ model = descriptor.model.eval().to(device=device, dtype=dtype)
22
+
23
+ arch = getattr(descriptor, "architecture", None)
24
+ arch_name = getattr(arch, "name", None) or type(arch).__name__
25
+
26
+ info = {
27
+ "architecture": arch_name,
28
+ "scale": int(getattr(descriptor, "scale", 4)),
29
+ "supports_half": bool(getattr(descriptor, "supports_half", False)),
30
+ "input_channels": int(getattr(descriptor, "input_channels", 3)),
31
+ "output_channels": int(getattr(descriptor, "output_channels", 3)),
32
+ }
33
+ return model, descriptor, info
34
+
35
+
36
+ def _get_parent_and_leaf(root: torch.nn.Module, qualified_name: str):
37
+ parts = qualified_name.split(".")
38
+ parent = root
39
+ for part in parts[:-1]:
40
+ parent = getattr(parent, part)
41
+ return parent, parts[-1]
42
+
43
+
44
+ def freeze_spandrel_reparameterized_convs(model: torch.nn.Module) -> tuple[torch.nn.Module, list[str]]:
45
+ """Freeze Spandrel's eval-time Conv3XC-style reparameterization.
46
+
47
+ SPAN's Conv3XC.forward() mutates module state during every eval forward:
48
+ update_params()
49
+ eval_conv(x)
50
+
51
+ torch.export should see a static inference graph. We therefore:
52
+ 1. deep-copy the exact Spandrel model;
53
+ 2. ask Spandrel's OWN update_params() implementation to materialize the
54
+ fused eval_conv weights;
55
+ 3. replace each reparameterizing wrapper module with that exact eval_conv.
56
+
57
+ No convolution fusion math is reimplemented here.
58
+ """
59
+ frozen = deepcopy(model).eval()
60
+
61
+ candidates: list[str] = []
62
+ # Snapshot names first because we replace modules afterwards.
63
+ for name, module in frozen.named_modules():
64
+ if not name:
65
+ continue
66
+ if callable(getattr(module, "update_params", None)) and isinstance(
67
+ getattr(module, "eval_conv", None), torch.nn.Conv2d
68
+ ):
69
+ candidates.append(name)
70
+
71
+ # IMPORTANT: no torch.inference_mode() here. Tensors created under
72
+ # inference_mode do not track version counters and break torch.export.
73
+ with torch.no_grad():
74
+ for name in candidates:
75
+ module = frozen.get_submodule(name)
76
+ module.update_params()
77
+
78
+ replaced: list[str] = []
79
+ # Replace deepest modules first.
80
+ for name in sorted(candidates, key=lambda s: s.count("."), reverse=True):
81
+ module = frozen.get_submodule(name)
82
+ static_conv = deepcopy(module.eval_conv).eval()
83
+ parent, leaf = _get_parent_and_leaf(frozen, name)
84
+ setattr(parent, leaf, static_conv)
85
+ replaced.append(name)
86
+
87
+ frozen.eval()
88
+ return frozen, sorted(replaced)
tiling.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3.11
2
+ from __future__ import annotations
3
+
4
+ from pathlib import Path
5
+ from typing import Callable
6
+ import numpy as np
7
+ from PIL import Image
8
+
9
+
10
+ def tile_positions(length: int, tile: int, overlap: int) -> list[int]:
11
+ if tile <= 0:
12
+ raise ValueError("tile must be > 0")
13
+ if overlap < 0 or overlap >= tile:
14
+ raise ValueError("overlap must satisfy 0 <= overlap < tile")
15
+ if length <= tile:
16
+ return [0]
17
+
18
+ stride = tile - overlap
19
+ last = length - tile
20
+ pos = list(range(0, last + 1, stride))
21
+ if pos[-1] != last:
22
+ pos.append(last)
23
+ return pos
24
+
25
+
26
+ def keep_interval(
27
+ positions: list[int], i: int, tile: int, full_length: int
28
+ ) -> tuple[int, int]:
29
+ """Return the global interval owned by tile i.
30
+
31
+ Adjacent tiles meet exactly at the midpoint of their actual overlap.
32
+ This also handles the shorter/non-standard final overlap correctly.
33
+ """
34
+ p = positions[i]
35
+
36
+ if i == 0:
37
+ start = 0
38
+ else:
39
+ prev = positions[i - 1]
40
+ # midpoint of overlap [p, prev + tile)
41
+ start = (p + (prev + tile)) // 2
42
+
43
+ if i == len(positions) - 1:
44
+ end = full_length
45
+ else:
46
+ nxt = positions[i + 1]
47
+ # midpoint of overlap [nxt, p + tile)
48
+ end = (nxt + (p + tile)) // 2
49
+
50
+ return start, end
51
+
52
+
53
+ def pad_tile_edge(
54
+ tile_arr: np.ndarray, target_h: int, target_w: int
55
+ ) -> tuple[np.ndarray, int, int]:
56
+ h, w = tile_arr.shape[:2]
57
+ pad_h = max(0, target_h - h)
58
+ pad_w = max(0, target_w - w)
59
+ if pad_h or pad_w:
60
+ tile_arr = np.pad(
61
+ tile_arr,
62
+ ((0, pad_h), (0, pad_w), (0, 0)),
63
+ mode="edge",
64
+ )
65
+ return tile_arr, h, w
66
+
67
+
68
+ def tiled_upscale(
69
+ image_rgb01: np.ndarray,
70
+ infer_tile: Callable[[np.ndarray], np.ndarray],
71
+ *,
72
+ scale: int,
73
+ tile: int = 512,
74
+ overlap: int = 64,
75
+ progress_prefix: str = "",
76
+ ) -> np.ndarray:
77
+ """Upscale HWC RGB [0,1] using fixed-size tiles and midpoint-discard stitching.
78
+
79
+ infer_tile receives exactly tile x tile x 3 float32 data and returns
80
+ (tile*scale) x (tile*scale) x 3.
81
+ """
82
+ if image_rgb01.ndim != 3 or image_rgb01.shape[2] != 3:
83
+ raise ValueError(f"expected HWC RGB image, got {image_rgb01.shape}")
84
+
85
+ h, w = image_rgb01.shape[:2]
86
+ ys = tile_positions(h, tile, overlap)
87
+ xs = tile_positions(w, tile, overlap)
88
+
89
+ out = np.empty((h * scale, w * scale, 3), dtype=np.float32)
90
+ total = len(ys) * len(xs)
91
+ n = 0
92
+
93
+ for yi, y in enumerate(ys):
94
+ gy0, gy1 = keep_interval(ys, yi, tile, h)
95
+ for xi, x in enumerate(xs):
96
+ gx0, gx1 = keep_interval(xs, xi, tile, w)
97
+ n += 1
98
+ if progress_prefix:
99
+ print(
100
+ f"\r{progress_prefix} tile {n}/{total} "
101
+ f"@ x={x}, y={y}",
102
+ end="",
103
+ flush=True,
104
+ )
105
+
106
+ crop = image_rgb01[y : min(y + tile, h), x : min(x + tile, w)]
107
+ crop, original_h, original_w = pad_tile_edge(crop, tile, tile)
108
+ pred = infer_tile(crop.astype(np.float32, copy=False))
109
+
110
+ expected = (tile * scale, tile * scale, 3)
111
+ if pred.shape != expected:
112
+ raise RuntimeError(
113
+ f"inference returned {pred.shape}, expected {expected}"
114
+ )
115
+
116
+ # Drop padded output before applying ownership interval.
117
+ pred = pred[: original_h * scale, : original_w * scale]
118
+
119
+ ly0 = (gy0 - y) * scale
120
+ ly1 = (gy1 - y) * scale
121
+ lx0 = (gx0 - x) * scale
122
+ lx1 = (gx1 - x) * scale
123
+
124
+ out[
125
+ gy0 * scale : gy1 * scale,
126
+ gx0 * scale : gx1 * scale,
127
+ ] = pred[ly0:ly1, lx0:lx1]
128
+
129
+ if progress_prefix:
130
+ print()
131
+ return out
132
+
133
+
134
+ def load_rgb01(path: str | Path) -> np.ndarray:
135
+ im = Image.open(Path(path).expanduser().resolve()).convert("RGB")
136
+ return np.asarray(im, dtype=np.float32) / 255.0
137
+
138
+
139
+ def save_rgb01(
140
+ arr: np.ndarray,
141
+ path: str | Path,
142
+ *,
143
+ jpeg_quality: int = 75,
144
+ jpeg_subsampling: int = 2,
145
+ ) -> None:
146
+ path = Path(path).expanduser().resolve()
147
+ path.parent.mkdir(parents=True, exist_ok=True)
148
+ u8 = np.rint(np.clip(arr, 0.0, 1.0) * 255.0).astype(np.uint8)
149
+ im = Image.fromarray(u8, mode="RGB")
150
+ suffix = path.suffix.lower()
151
+ if suffix in {".jpg", ".jpeg"}:
152
+ im.save(
153
+ path,
154
+ quality=jpeg_quality,
155
+ subsampling=jpeg_subsampling,
156
+ )
157
+ elif suffix == ".png":
158
+ im.save(path)
159
+ else:
160
+ raise ValueError("output extension must be .png, .jpg, or .jpeg")