Download code/edit_export.py from aqualaguna/MOSS-Image-Edit-OpenVINO: direct link, hf CLI and curl.
- Browser
- Download file 4.33 kB
-
https://huggingface.co/aqualaguna/MOSS-Image-Edit-OpenVINO/resolve/main/code/edit_export.py
- Command line
-
hf download hf://aqualaguna/MOSS-Image-Edit-OpenVINO/code/edit_export.py
-
curl -L -o edit_export.py https://huggingface.co/aqualaguna/MOSS-Image-Edit-OpenVINO/resolve/main/code/edit_export.py
4.33 kB
| """Export the MOSS-Image EDIT model pieces as OpenVINO IRs. CPU only. | |
| edit_a / edit_b / edit_c : DiT segments with the Moss-Image-Edit LoRA merged and the reference K/V cache in/out (edit_ops.py) | |
| edit_host.npz : video_embedder weight/bias (the host embeds latent tokens, so prefill and steps share one graph) | |
| vae_encoder_<dtype>.xml : FLUX.2 VAE encoder + quant_conv -> posterior MEAN (= mode) [1,32,H/8,W/8]; patchify + BN on the host | |
| text_refine / host_weights.npz / VAE decoder are untouched by the LoRA and reused from the t2i build. | |
| usage: python edit_export.py OUTDIR [--segs edit_a,edit_b,edit_c,host,vae] [--dtype f16] [--vae-dtype f32] [--no-merge] | |
| """ | |
| import argparse | |
| import json | |
| import os | |
| import sys | |
| import numpy as np | |
| import torch | |
| sys.path.insert(0, "/opt/mossimage/code") | |
| sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) | |
| from common import VAE_DIR, Timer, hwm_gb # noqa: E402 | |
| TYPES = None | |
| class VAEEnc(torch.nn.Module): | |
| def __init__(self, vae): | |
| super().__init__() | |
| self.encoder, self.qc = vae.encoder, vae.quant_conv | |
| def forward(self, image): | |
| h = self.encoder(image) | |
| if self.qc is not None: | |
| h = self.qc(h) | |
| return h[:, : h.shape[1] // 2].float() # DiagonalGaussianDistribution: mean, logvar = chunk(2, dim=1); mode() = mean | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("out") | |
| ap.add_argument("--segs", default="edit_a,edit_b,edit_c,host,vae") | |
| ap.add_argument("--dtype", default="f16", choices=["f16", "f32"]) | |
| ap.add_argument("--vae-dtype", default="f32", choices=["f16", "f32"]) | |
| ap.add_argument("--no-merge", action="store_true", help="export the plain SFT weights (for A/B of the LoRA)") | |
| a = ap.parse_args() | |
| import openvino as ov | |
| from edit_ops import LORA_DIR, build_edit_segment, edit_host_weights | |
| T = {"f32": ov.Type.f32, "f16": ov.Type.f16} | |
| os.makedirs(a.out, exist_ok=True) | |
| torch.set_num_threads(8) | |
| dtype = torch.float16 if a.dtype == "f16" else torch.float32 | |
| info = {"lora": LORA_DIR, "merged": not a.no_merge, "dtype": a.dtype} | |
| for name in a.segs.split(","): | |
| if name.startswith("edit_"): | |
| with Timer(f"build {name}"): | |
| m, ex, specs, outs, used = build_edit_segment(name, dtype, merge=not a.no_merge) | |
| print(f"[lora] {name}: {len(used)} merged linears", flush=True) | |
| info[f"{name}_lora_merged"] = len(used) | |
| with torch.no_grad(), Timer(f"convert {name}"): | |
| om = ov.convert_model(m, example_input=ex, input=[(shape, T[t]) for _, shape, t in specs]) | |
| print(f"[mem] hwm after convert: {hwm_gb():.1f} GB", flush=True) | |
| for i, (nm, _, _) in enumerate(specs): | |
| om.inputs[i].get_tensor().set_names({nm}) | |
| for i, nm in enumerate(outs): | |
| om.outputs[i].get_tensor().set_names({nm}) | |
| path = f"{a.out}/{name}.xml" | |
| with Timer(f"save {name}"): | |
| ov.save_model(om, path, compress_to_fp16=(a.dtype == "f16")) | |
| print("[saved]", path, os.path.getsize(path[:-4] + ".bin") / 1e9, "GB", flush=True) | |
| del om, m | |
| elif name == "host": | |
| np.savez(f"{a.out}/edit_host.npz", **edit_host_weights()) | |
| print("[saved] edit_host.npz", flush=True) | |
| elif name == "vae": | |
| _orig = torch.jit.trace | |
| torch.jit.trace = lambda *x, **k: _orig(*x, **{**k, "check_trace": False}) | |
| from diffusers import AutoencoderKLFlux2 | |
| vae = AutoencoderKLFlux2.from_pretrained(VAE_DIR, torch_dtype=torch.float32).eval() | |
| enc = VAEEnc(vae).eval() | |
| with torch.no_grad(), Timer("convert vae encoder"): | |
| om = ov.convert_model(enc, example_input=(torch.rand(1, 3, 256, 256) * 2 - 1,), input=[([1, 3, -1, -1], ov.Type.f32)]) | |
| om.inputs[0].get_tensor().set_names({"image"}) | |
| om.outputs[0].get_tensor().set_names({"z"}) | |
| path = f"{a.out}/vae_encoder_{a.vae_dtype}.xml" | |
| ov.save_model(om, path, compress_to_fp16=(a.vae_dtype == "f16")) | |
| print("[saved]", path, flush=True) | |
| json.dump(info, open(f"{a.out}/export_info_{'_'.join(a.segs.split(','))}.json", "w"), indent=1) | |
| if __name__ == "__main__": | |
| main() | |