Download code/ref_e2e.py from aqualaguna/MOSS-Image-Edit-OpenVINO: direct link, hf CLI and curl.
- Browser
- Download file 4.72 kB
-
https://huggingface.co/aqualaguna/MOSS-Image-Edit-OpenVINO/resolve/main/code/ref_e2e.py
- Command line
-
hf download hf://aqualaguna/MOSS-Image-Edit-OpenVINO/code/ref_e2e.py
-
curl -L -o ref_e2e.py https://huggingface.co/aqualaguna/MOSS-Image-Edit-OpenVINO/resolve/main/code/ref_e2e.py
4.72 kB
| """Glue check: the ORIGINAL MOSSImagePipeline.__call__ (scheduler, noise, Euler, CFG with skipped block 22, BN + unpatchify, | |
| VAE, postprocess) on CPU float32 with the streamed fp32 DiT, from fixed prompt embeddings, versus moss_pipeline.MossImage | |
| (OpenVINO) fed the SAME embeddings. | |
| Usage: python ref_e2e.py ref [--size 256 --steps 4 --seed 7] -> work/e2e_ref_<size>_<steps>.npz (CPU, ~4 min) | |
| python ref_e2e.py ov [--size 256 --steps 4 --seed 7 --device GPU] -> compares against that file | |
| """ | |
| import argparse | |
| import sys | |
| import types | |
| import numpy as np | |
| import torch | |
| sys.path.insert(0, __import__("os").path.dirname(__import__("os").path.abspath(__file__))) | |
| from common import VAE_DIR, WORK, Timer, psnr # noqa: E402 | |
| def run_ref(a): | |
| from diffusers import AutoencoderKLFlux2 | |
| from dit_ops import load_orig_module | |
| from ref_dit import LazyDiT, forward_ref | |
| torch.set_num_threads(8) | |
| mod = load_orig_module() | |
| te = np.load(f"{WORK}/te_ref.npz") | |
| pos = torch.from_numpy(te["scene_f32_part3"])[None] | |
| neg = torch.from_numpy(te["empty_f32_part3"])[None] | |
| net = LazyDiT("sft") | |
| class Stub(torch.nn.Module): | |
| def __init__(self): | |
| super().__init__() | |
| self.layers = torch.nn.ModuleList([torch.nn.Identity() for _ in range(42)]) | |
| self.config = types.SimpleNamespace(latent_channels=128) | |
| self.calls = [] | |
| def forward(self, latents, timestep, embeds, mask, skip_layers=()): | |
| self.calls.append((float(timestep), tuple(skip_layers))) | |
| v = forward_ref(net, latents.float(), float(timestep), embeds.float(), tuple(skip_layers)) | |
| return types.SimpleNamespace(sample=v) | |
| vae = AutoencoderKLFlux2.from_pretrained(VAE_DIR, torch_dtype=torch.float32).eval() | |
| stub = Stub() | |
| mod.MOSSImagePipeline._execution_device = torch.device("cpu") # absent in this diffusers version's DiffusionPipeline | |
| pipe = mod.MOSSImagePipeline(stub, mod.MOSSImageScheduler(), None, None, vae) | |
| g = torch.Generator("cpu").manual_seed(a.seed) | |
| with Timer("original pipeline __call__ (fp32 cpu)"): | |
| img = pipe(prompt_embeds=pos, negative_prompt_embeds=neg, height=a.size, width=a.size, num_inference_steps=a.steps, | |
| guidance_scale=a.guidance, generator=g, output_type="np").images[0] | |
| lat = pipe(prompt_embeds=pos, negative_prompt_embeds=neg, height=a.size, width=a.size, num_inference_steps=a.steps, | |
| guidance_scale=a.guidance, generator=torch.Generator("cpu").manual_seed(a.seed), output_type="latent").images | |
| print("calls:", stub.calls[: 4], "... total", len(stub.calls)) | |
| sig = pipe.scheduler.timesteps.numpy() | |
| np.savez(f"{WORK}/e2e_ref_{a.size}_{a.steps}.npz", img=img, lat=lat.numpy(), timesteps=sig) | |
| print("saved; img", img.shape, img.min(), img.max()) | |
| def run_ov(a): | |
| from moss_pipeline import MossImage, moss_sigmas | |
| ref = np.load(f"{WORK}/e2e_ref_{a.size}_{a.steps}.npz") | |
| te = np.load(f"{WORK}/te_ref.npz") | |
| sg = moss_sigmas(a.steps) | |
| print("timesteps equal to scheduler:", np.array_equal((sg * 1000).astype(np.float32), ref["timesteps"]), "max diff", float(np.abs(sg * 1000 - ref["timesteps"]).max())) | |
| pipe = MossImage(device=a.device, log=lambda *x: print("[pipe]", *x, flush=True), variant=a.variant, te_precision=a.te_precision or None) | |
| img, st = pipe.generate("x", "", a.size, a.size, a.steps, a.guidance, a.seed, embeds=(te["scene_f32_part3"], te["empty_f32_part3"]), return_latents=True) | |
| ref_u8 = (np.clip(ref["img"], 0, 1) * 255).round().astype(np.uint8) | |
| print(f"final image PSNR OV({a.device}) vs original-pipeline fp32 CPU: {psnr(ref_u8, img):.2f} dB ; mean abs pixel diff {np.abs(ref_u8.astype(float) - img).mean():.3f}") | |
| lat_ref = ref["lat"] | |
| lat_ov = st["latents"] | |
| from common import cmp | |
| cmp(lat_ref, lat_ov, "final latents OV vs original pipeline") | |
| print("stats", {k: v for k, v in st.items() if k != "latents"}) | |
| from PIL import Image | |
| Image.fromarray(img).save(f"{WORK}/e2e_ov_{a.variant}_{a.device}_{a.size}_{a.steps}.png") | |
| Image.fromarray(ref_u8).save(f"{WORK}/e2e_ref_{a.size}_{a.steps}.png") | |
| if __name__ == "__main__": | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("mode", choices=["ref", "ov"]) | |
| ap.add_argument("--size", type=int, default=256) | |
| ap.add_argument("--steps", type=int, default=4) | |
| ap.add_argument("--seed", type=int, default=7) | |
| ap.add_argument("--guidance", type=float, default=3.0) | |
| ap.add_argument("--device", default="GPU") | |
| ap.add_argument("--variant", default="sft") | |
| ap.add_argument("--te-precision", default="") | |
| a = ap.parse_args() | |
| run_ref(a) if a.mode == "ref" else run_ov(a) | |