File size: 3,713 Bytes
c647930
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import sys, time, numpy as np, torch, torch.nn.functional as F, onnx, onnxruntime as ort, os
sys.path.insert(0, "/tmp/claude-0/-home-user-HF-empty/1caca391-99c3-5a94-acbe-98cceb297ce3/scratchpad/res2/s")
from common import *
from PIL import Image
R = "/tmp/claude-0/-home-user-HF-empty/1caca391-99c3-5a94-acbe-98cceb297ce3/scratchpad/res2/"
torch.set_num_threads(4)
E = enc.Encoder(512, 512, 20).eval(); D = sd.Synthesis(512, 512, 20).eval()
sdict = torch.load(R + "w/motion_autoencoder.pth", map_location="cpu", weights_only=True)
E.load_state_dict({k[len("motion_autoencoder.enc."):]: v for k, v in sdict.items() if k.startswith("motion_autoencoder.enc.")}, strict=True)
D.load_state_dict({k[len("motion_autoencoder.dec."):]: v for k, v in sdict.items() if k.startswith("motion_autoencoder.dec.")}, strict=True)
def modconv(self, input, style):
    batch, in_channel, h, w = input.shape
    style = self.modulation(style); weight = self.scale * self.weight[0]
    xx = input * style.view(batch, in_channel, 1, 1)
    if self.upsample: out = F.conv_transpose2d(xx, weight.transpose(0, 1), padding=0, stride=2)
    elif self.downsample: out = F.conv2d(self.blur(xx), weight, padding=0, stride=2)
    else: out = F.conv2d(xx, weight, padding=self.padding)
    if self.demodulate:
        w2 = weight.pow(2).sum([2, 3]); demod = torch.rsqrt(style.pow(2) @ w2.t() + 1e-8); out = out * demod.view(batch, self.out_channel, 1, 1)
    if self.upsample: out = self.blur(out)
    return out
sd.ModulatedConv2d.forward = modconv
_gs = F.grid_sample
F.grid_sample = lambda inp, g, **k: _gs(inp.float(), g.float(), **k).to(inp.dtype)     # the warp stays fp32
img = Image.open("/tmp/claude-0/-home-user-HF-empty/1caca391-99c3-5a94-acbe-98cceb297ce3/scratchpad/av/repo/data/rumi.jpg").convert("RGB").resize((512, 512))
x = (torch.from_numpy(np.array(img)).float().permute(2, 0, 1)[None] / 255 - 0.5) / 0.5
z = np.load(R + "out/dec_in.npz"); ref = torch.from_numpy(z["ref_mv"]); r_d = torch.from_numpy(z["wa_mv"]) - E(x, input_target=None)[0].detach()
class WE(torch.nn.Module):
    def __init__(s, e): super().__init__(); s.e = e
    def forward(s, x): x_r, _, f = s.e(x, input_target=None); return (x_r, *f)
class WD(torch.nn.Module):
    def __init__(s, d): super().__init__(); s.d = d
    def forward(s, wa, *f): return s.d(wa, None, list(f))[0]
Eh = WE(E).half().eval(); Dh = WD(D).half().eval()
with torch.no_grad():
    outs = Eh(x.half()); x_r = outs[0]; feats = list(outs[1:])
    img16 = Dh((x_r + r_d.half()), *feats).float()
d = (img16 - ref).abs()
mse = float(((img16 - ref) ** 2).mean()); print("fp16 encoder -> fp16 decoder chain vs fp32: max abs %.3f mean abs %.5f PSNR %.1f dB" % (d.max(), d.mean(), 10 * np.log10(4 / mse)))
Image.fromarray(((img16[0].clamp(-1, 1) * 0.5 + 0.5) * 255).byte().permute(1, 2, 0).numpy()).save(R + "out/fp16_chain.png")
names_d = ["wa"] + [f"f{i}" for i in range(7)]
t = time.time()
with torch.no_grad():
    torch.onnx.export(Eh, (x.half(),), R + "pub/encoder_fp16.onnx", opset_version=19, dynamo=True, input_names=["img"], output_names=["x_r"] + [f"f{i}" for i in range(7)])
    torch.onnx.export(Dh, ((x_r + r_d.half()), *feats), R + "pub/decoder_fp16.onnx", opset_version=19, dynamo=True, input_names=names_d, output_names=["img"])
print("export %.1fs" % (time.time() - t))
for n in ["encoder_fp16", "decoder_fp16"]:
    m = onnx.load(R + f"pub/{n}.onnx", load_external_data=False)
    import collections; print(n, sorted(collections.Counter(nd.op_type for nd in m.graph.node).items()))
np.savez(R + "out/chain_in.npz", img=x.numpy(), xr_rd=(x_r + r_d.half()).numpy(), ref=ref.numpy())
print({f: round(os.path.getsize(R + "pub/" + f) / 1e6, 1) for f in os.listdir(R + "pub")})