Spaces:
Running on Zero
Running on Zero
File size: 2,178 Bytes
78b616e | 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 | """Local validation: vendored RRDBNet + real checkpoint + inference logic.
Run before pushing to the Space: python test_valid.py
"""
import numpy as np
import torch
from huggingface_hub import hf_hub_download
from rrdbnet import RRDBNet
MODEL_REPO = "ai-forever/Real-ESRGAN"
MODEL_FILE = "RealESRGAN_x4.pth"
def main() -> None:
path = hf_hub_download(repo_id=MODEL_REPO, filename=MODEL_FILE)
raw = torch.load(path, map_location="cpu", weights_only=True)
wrapped = "params" in raw or "params_ema" in raw
state = raw.get("params_ema", raw.get("params", raw))
print(f"checkpoint keys: {len(state)} | wrapped: {wrapped}")
model = RRDBNet(num_in_ch=3, num_out_ch=3, scale=4, num_feat=64, num_block=23, num_grow_ch=32)
model.load_state_dict(state, strict=True) # raises if arch/keys mismatch
model.eval()
print("strict state_dict load: OK")
x = torch.rand(1, 3, 32, 32)
with torch.no_grad():
y = model(x)
assert tuple(y.shape) == (1, 3, 128, 128), f"unexpected output shape {tuple(y.shape)}"
print("forward pass: OK ->", tuple(y.shape))
# exercise the pad/crop inference path used by app._upscale
def fake_upscale(rgb_np: np.ndarray) -> np.ndarray:
h, w = rgb_np.shape[:2]
pad = max(0, min(8, h // 2, w // 2))
img = torch.from_numpy(rgb_np.astype(np.float32).transpose(2, 0, 1))[None] / 255.0
if pad:
img = torch.nn.functional.pad(img, (pad, pad, pad, pad), mode="reflect")
with torch.no_grad():
out = model(img)
if pad:
out = out[..., pad * 4 : -pad * 4, pad * 4 : -pad * 4]
out = out.float().clamp_(0.0, 1.0).squeeze(0).permute(1, 2, 0).detach().numpy()
return (np.clip(out * 255.0, 0, 255).astype(np.uint8))
for size in (16, 64, 257):
src = np.random.randint(0, 256, (size, size, 3), dtype=np.uint8)
out = fake_upscale(src)
assert out.shape == (size * 4, size * 4, 3), f"pad/crop size bug at {size}: {out.shape}"
assert out.dtype == np.uint8
print("pad/crop inference (16, 64, 257 px): OK")
print("ALL CHECKS PASSED")
if __name__ == "__main__":
main()
|