MOSS-Image-SFT-OpenVINO / code /moss_pipeline.py
aqualaguna's picture
Add files using upload-large-folder tool
565b868 verified
Raw History Blame Contribute Delete
15.4 kB
"""MOSS-Image (OpenMOSS-Team, Apache-2.0) text-to-image on OpenVINO / Intel Arc: the sampler.
Mirrors MOSSImagePipeline.__call__ (pipeline_moss_image.py): chat-templated prompt -> Qwen3.5-9B language model
last_hidden_state -> 5B single-stream DiT, flow-matching Euler, CFG with the negative branch skipping block 22 -> FLUX.2
(small decoder) VAE. The networks are OpenVINO IRs (see te_export.py / dit_export.py / vae_export.py); everything else
(tokenizer, token-embedding gather, RoPE tables, time embedding, scheduler, noise, Euler/CFG update, BN + unpatchify) is
host code on numpy / torch-cpu.
GPU memory plan (24 GB card): DiT (3 segments) + VAE stay resident (~12 GB); the text encoder is 4 IRs of ~3.3 GB that are
compiled, run for all prompts of the request, and released one after the other (compile is ~3-6 s from the on-disk cache).
"""
import collections
import gc
import os
import sys
import threading
import time
import numpy as np
import openvino as ov
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from common import text_rope # noqa: E402
from dit_ops import rope_table, time_mod # noqa: E402
LATENT_CH = 128
MAX_TEXT_TOKENS = 4096
TE_PARTS = 4
# Selectable model variants of the same graph (`dit` / `te` are directories under models/). Both use the SFT flow-matching Euler loop with CFG (two forwards
# per step). default_steps 30 is the sweet spot (ricardo, 2026-10-20); 50 is the authors' reference setting and stays selectable (max_steps 100).
VARIANTS = {
"sft": dict(dit="dit_sft", te="te", sampler="cfg", max_steps=100, default_steps=30),
# int8 weights shrink the DiT from 9.7 to 6.1 GB (NNCF per-channel INT8_ASYM, the ffn_down projections kept in fp16: build recipe in int8_compress.py --keep-down):
# the card then holds 1536x1536 (peak measured in the release notes of MOSSIMAGE.md; fp16 needs 24.2 GB there)
"sft-int8": dict(dit="dit_sft_int8_keepdown", te="te", sampler="cfg", max_steps=100, default_steps=30, max_pixels=1536 * 1536),
}
def moss_sigmas(steps, shift=5.0, total=1000, training_shift=1.0):
"""The MOSSImageScheduler grid: shifted linspace snapped to the nearest training sigma (float32 torch maths, as the original)."""
import torch
def grid(count, sh):
lower = sh / (total + sh - 1)
values = torch.linspace(1, lower, count)
return sh * values / (1 + (sh - 1) * values)
sigmas = grid(steps, shift)
training = grid(total, training_shift).flip(0)
upper = torch.searchsorted(training, sigmas).clamp(max=total - 1)
lower = (upper - 1).clamp(min=0)
nearest = torch.where((sigmas - training[lower]).abs() <= (training[upper] - sigmas).abs(), lower, upper)
sigmas = torch.unique_consecutive(training[nearest]).numpy().astype(np.float32)
return sigmas # FlowMatchEuler: timesteps = sigmas * 1000, terminal sigma 0 appended
def gpu_stats(core, device):
if device != "GPU":
return {}
try:
st = core.get_property("GPU", "GPU_MEMORY_STATISTICS")
return {k: round(v / 2**20) for k, v in st.items()}
except Exception as e: # noqa: BLE001
return {"err": repr(e)[:80]}
def _first(res):
"""First output of an infer() result as an owned numpy array (the request reuses its output buffers)."""
return np.array(next(iter(res.values())))
class Cancelled(Exception):
pass
class MossImage:
def __init__(self, models_dir="/opt/mossimage/models", device="GPU", cache_dir="/opt/mossimage/cache", variant="sft",
log=print, te_resident=False, embed_cache=16, vae_resident=False, te_precision=None):
self.dir, self.device, self.log, self.te_resident = models_dir, device, log, te_resident
self.vae_resident = vae_resident
# None = the plugin default (f16 compute). "f32": the text encoder computes in f32 on the card (weights stay in the IR's precision).
self.te_precision = te_precision or None
self.core = ov.Core()
if cache_dir:
os.makedirs(cache_dir, exist_ok=True)
self.core.set_property({"CACHE_DIR": cache_dir})
from transformers import AutoTokenizer
self.tok = AutoTokenizer.from_pretrained(f"{models_dir}/tokenizer")
self.embed = np.load(f"{models_dir}/te/embed_tokens_f16.npy", mmap_mode="r")
bn = np.load(f"{models_dir}/vae/bn.npz")
self.bn_scale = np.sqrt(bn["var"] + bn["eps"]).reshape(1, -1, 1, 1).astype(np.float32)
self.bn_mean = bn["mean"].reshape(1, -1, 1, 1).astype(np.float32)
self.dit = None
self.vae = None
self.te_cm = {}
self.cache = collections.OrderedDict()
self.cache_max = embed_cache
self.lock = threading.Lock()
self.peak_gpu_mb = 0
self.variant = None
self.select_variant(variant)
# ------------------------------------------------------------------ variants
def installed_variants(self):
return [n for n, v in VARIANTS.items() if os.path.exists(f"{self.dir}/{v['dit']}/dit_c.xml") and os.path.exists(f"{self.dir}/{v['te']}/te_part3.xml")
and os.path.exists(f"{self.dir}/{v['dit']}/host_weights.npz")]
def select_variant(self, name):
"""Switch the model. The previous DiT is released first (two DiTs do not fit the card together); recompiling from the kernel cache takes seconds."""
if name == self.variant:
return
if name not in VARIANTS:
raise ValueError(f"unknown model variant {name!r}; known: {sorted(VARIANTS)}")
v = VARIANTS[name]
old_te = VARIANTS[self.variant]["te"] if self.variant else None
if self.dit is not None:
self.unload_dit()
if old_te != v["te"]:
self.te_cm.clear()
self.cache.clear()
self.cfg = v
self.dit_dir = f"{self.dir}/{v['dit']}"
self.te_dir = f"{self.dir}/{v['te']}"
self.hw = dict(np.load(f"{self.dit_dir}/host_weights.npz"))
self.variant = name
self.log(f"model variant {name}: dit {v['dit']}, text encoder {v['te']}, sampler {v['sampler']}")
# ------------------------------------------------------------------ helpers
def _compile(self, name, path, hint=None):
t = time.time()
cfg = {"INFERENCE_PRECISION_HINT": hint} if hint else {}
cm = self.core.compile_model(path, self.device, cfg)
self.log(f"compiled {name} on {self.device} in {time.time() - t:.1f} s")
return cm
def _note_mem(self):
st = gpu_stats(self.core, self.device)
if st and "usm_device" in st:
self.peak_gpu_mb = max(self.peak_gpu_mb, st["usm_device"])
return st
def load_dit(self):
if self.dit is None:
self.dit = {n: self._compile(n, f"{self.dit_dir}/{n}.xml") for n in ("text_refine", "dit_a", "dit_b", "dit_c")}
self.dit_req = {n: cm.create_infer_request() for n, cm in self.dit.items()}
self._note_mem()
return self.dit
def load_vae(self):
if self.vae is None:
self.vae = self._compile("vae", f"{self.dir}/vae/vae_decoder_f16.xml")
self.vae_req = self.vae.create_infer_request()
return self.vae
def unload_vae(self):
"""The decoder's scratch memory (GBs at 1024 px and up) lives as long as the compiled model; recompiling is ~0.2 s from the cache."""
self.vae = self.vae_req = None
gc.collect()
def unload_dit(self):
self.dit = self.dit_req = None
gc.collect()
def warm(self):
"""Compile everything that stays resident and run the text encoder once so the first request is fast."""
self.load_dit()
self.encode_prompts([""])
# ------------------------------------------------------------------ text encoder
def chat_ids(self, text):
formatted = self.tok.apply_chat_template([{"role": "user", "content": text}], tokenize=False, add_generation_prompt=True,
enable_thinking=True)
return self.tok(formatted, return_tensors="np")["input_ids"][0]
def token_count(self, text):
return int(len(self.chat_ids(text)))
def _te_part(self, k):
if k in self.te_cm:
return self.te_cm[k]
return self._compile(f"te_part{k}", f"{self.te_dir}/te_part{k}.xml", self.te_precision)
def encode_prompts(self, texts, max_len=MAX_TEXT_TOKENS):
"""texts -> list of [L,4096] float32 (last_hidden_state after the final norm), cached. Unpadded forwards, like the original."""
out = [None] * len(texts)
todo = []
for i, t in enumerate(texts):
if t in self.cache:
self.cache.move_to_end(t)
out[i] = self.cache[t]
else:
todo.append(i)
if todo:
t0 = time.time()
uniq = list(dict.fromkeys(texts[i] for i in todo))
ids = {t: self.chat_ids(t)[:max_len] for t in uniq}
hid = {t: self.embed[ids[t]].astype(np.float32)[None] for t in uniq}
rope = {t: text_rope(len(ids[t])) for t in uniq}
for k in range(TE_PARTS):
cm = self._te_part(k)
req = cm.create_infer_request()
for t in uniq:
cos, sin = rope[t]
r = req.infer({"hidden": hid[t], "cos": cos, "sin": sin})
hid[t] = _first(r)
self._note_mem()
del req
if self.te_resident:
self.te_cm[k] = cm
del cm
gc.collect()
for t in uniq:
self.cache[t] = hid[t][0]
while len(self.cache) > self.cache_max:
self.cache.popitem(last=False)
for i in todo:
out[i] = hid[texts[i]][0]
self.log(f"text encoder: {len(uniq)} prompt(s), {[len(ids[t]) for t in uniq]} tokens, {time.time() - t0:.1f} s")
return out
# ------------------------------------------------------------------ DiT
def _velocity(self, tokens, text, rope, mod, head, skip_b, n_marker):
r = self.dit_req
x = _first(r["dit_a"].infer({"tokens": tokens, "text": text, "rope": rope, "mod": mod}))
if not skip_b:
x = _first(r["dit_b"].infer({"x": x, "rope": rope, "mod": mod}))
return _first(r["dit_c"].infer({"x": x, "rope": rope, "mod": mod, "head": head, "n_img": n_marker}))
def generate(self, prompt, negative="", width=1024, height=1024, steps=None, guidance=3.0, seed=0, skip_uncond_block=True,
progress=None, cancel=None, embeds=None, return_latents=False, variant=None):
"""Returns (uint8 HxWx3 array, stats dict). Same maths as MOSSImagePipeline.__call__ (batch 1, uncond_skip_layers=(22,)); guidance 1 skips the negative
pass (one forward per step), as the original pipeline does (do_cfg = guidance_scale != 1.0)."""
import torch
if variant:
self.select_variant(variant)
if steps is None:
steps = self.cfg["default_steps"]
if not 1 <= steps <= self.cfg["max_steps"]:
raise ValueError(f"steps must be 1-{self.cfg['max_steps']} for model {self.variant}")
if width <= 0 or height <= 0 or width % 16 or height % 16:
raise ValueError("width and height must be positive multiples of 16")
t_start = time.time()
stats = {}
self.peak_gpu_mb = 0 # per call: the peak of the card's device memory seen by this process during this generation
self._note_mem()
h, w = height // 16, width // 16
N = h * w
do_cfg = guidance != 1.0
texts = [prompt] + ([negative] if do_cfg else [])
t0 = time.time()
embs = list(embeds) if embeds is not None else self.encode_prompts(texts) # embeds=(cond, uncond): [L,4096] float32 (tests)
stats["text_encoder_s"] = round(time.time() - t0, 2)
text_c = embs[0]
text_u = embs[1] if do_cfg else None
t0 = time.time()
self.load_dit()
stats["dit_load_s"] = round(time.time() - t0, 2)
d = self.dit_req
# text refiner once per prompt (does not depend on the latents or the timestep)
ropes, texts_r = {}, {}
for name, e in (("c", text_c), ("u", text_u)):
if e is None:
continue
L = e.shape[0]
rope = rope_table(h, w, L)
ropes[name] = rope
texts_r[name] = _first(d["text_refine"].infer({"ctx": e[None], "rope_t": rope[:, N:]}))
stats["tokens_prompt"] = int(text_c.shape[0])
stats["tokens_negative"] = int(text_u.shape[0]) if do_cfg else None
# noise: fp32 torch CPU generator, same stream as `randn_tensor(shape, generator=torch.Generator('cpu').manual_seed(seed))`
g = torch.Generator("cpu").manual_seed(int(seed))
lat = torch.randn((1, LATENT_CH, h, w), generator=g, dtype=torch.float32).numpy()
tokens = np.ascontiguousarray(lat.reshape(1, LATENT_CH, N).transpose(0, 2, 1))
n_marker = np.zeros((1, N, 1), np.float32)
t_dn = time.time()
step_times = []
sig = moss_sigmas(steps)
sigmas = np.concatenate([sig, np.zeros(1, np.float32)])
timesteps = (sig * 1000.0).astype(np.float32)
for i, ts in enumerate(timesteps):
if cancel is not None and cancel():
raise Cancelled()
t_s = time.time()
mod, head = time_mod(self.hw, float(ts))
v = self._velocity(tokens, texts_r["c"], ropes["c"], mod, head, False, n_marker)
if do_cfg:
vu = self._velocity(tokens, texts_r["u"], ropes["u"], mod, head, bool(skip_uncond_block), n_marker)
v = vu + np.float32(guidance) * (v - vu)
tokens = tokens + (sigmas[i + 1] - sigmas[i]) * v
step_times.append(time.time() - t_s)
if progress is not None:
progress(i + 1, len(timesteps))
stats["denoise_s"] = round(time.time() - t_dn, 2)
stats["steps"] = len(timesteps)
stats["model"] = self.variant
stats["s_per_step"] = round(float(np.median(step_times)), 3)
stats["step_first_s"] = round(step_times[0], 3)
self._note_mem()
# VAE: BN de-normalisation + unpatchify on the host, decode on the card
t0 = time.time()
self.load_vae()
lat = tokens.transpose(0, 2, 1).reshape(1, LATENT_CH, h, w)
z = lat * self.bn_scale + self.bn_mean
z = z.reshape(1, LATENT_CH // 4, 2, 2, h, w).transpose(0, 1, 4, 2, 5, 3).reshape(1, LATENT_CH // 4, 2 * h, 2 * w)
img = _first(self.vae_req.infer({"z": np.ascontiguousarray(z, dtype=np.float32)}))
stats["vae_s"] = round(time.time() - t0, 2)
self._note_mem()
if not self.vae_resident:
self.unload_vae()
img = np.clip(img, -1, 1)
stats["finite"] = bool(np.isfinite(tokens).all())
u8 = ((img[0].transpose(1, 2, 0) + 1) * 127.5).round().clip(0, 255).astype(np.uint8)
st = self._note_mem()
stats["gpu_mem_mb"] = st
stats["peak_gpu_usm_device_mb"] = self.peak_gpu_mb
stats["total_s"] = round(time.time() - t_start, 2)
if return_latents:
stats["latents"] = lat
return u8, stats