Download code/vae_export.py from aqualaguna/MOSS-Image-SFT-OpenVINO: direct link, hf CLI and curl.
- Browser
- Download file 2.07 kB
-
https://huggingface.co/aqualaguna/MOSS-Image-SFT-OpenVINO/resolve/main/code/vae_export.py
- Command line
-
hf download hf://aqualaguna/MOSS-Image-SFT-OpenVINO/code/vae_export.py
-
curl -L -o vae_export.py https://huggingface.co/aqualaguna/MOSS-Image-SFT-OpenVINO/resolve/main/code/vae_export.py
2.07 kB
| """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() | |