File size: 2,073 Bytes
4a1ea7b | 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 | """Export the FLUX.2 (small decoder) VAE decoder of MOSS-Image: z [1,32,h,w] -> image [1,3,8h,8w] (range -1..1).
The BatchNorm de-normalisation + unpatchify happen on the host (numpy); bn stats are written to bn.npz.
Usage: python vae_export.py [--dtype f16|f32]
"""
import argparse
import os
import sys
import numpy as np
import torch
_orig_trace = torch.jit.trace
torch.jit.trace = lambda *a, **k: _orig_trace(*a, **{**k, "check_trace": False})
sys.path.insert(0, __import__("os").path.dirname(__import__("os").path.abspath(__file__)))
from common import MODELS, VAE_DIR, Timer # noqa: E402
class VAEDec(torch.nn.Module):
def __init__(self, vae, dtype):
super().__init__()
self.pqc = vae.post_quant_conv
self.decoder = vae.decoder
self.dtype = dtype
def forward(self, z):
return self.decoder(self.pqc(z.to(self.dtype))).float()
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--dtype", default="f16", choices=["f16", "f32"])
args = ap.parse_args()
import openvino as ov
from diffusers import AutoencoderKLFlux2
# Trace in fp32 (fast CPU kernels); the f16 IR is the same graph with weights compressed to fp16 on save.
dtype = torch.float32
vae = AutoencoderKLFlux2.from_pretrained(VAE_DIR, torch_dtype=torch.float32).eval()
out = f"{MODELS}/vae"
os.makedirs(out, exist_ok=True)
np.savez(f"{out}/bn.npz", mean=vae.bn.running_mean.numpy(), var=vae.bn.running_var.numpy(), eps=np.float32(vae.config.batch_norm_eps))
wrap = VAEDec(vae, dtype).to(dtype).eval()
z = torch.randn(1, 32, 32, 32)
with Timer("convert vae"):
m = ov.convert_model(wrap, example_input=(z,), input=[([1, 32, -1, -1], ov.Type.f32)])
m.inputs[0].get_tensor().set_names({"z"})
m.outputs[0].get_tensor().set_names({"image"})
name = "vae_decoder_f16" if args.dtype == "f16" else "vae_decoder_f32"
ov.save_model(m, f"{out}/{name}.xml", compress_to_fp16=(args.dtype == "f16"))
print("[saved]", f"{out}/{name}.xml")
if __name__ == "__main__":
main()
|