"""MOSS-Image inference engine for a ZeroGPU Space. This is the **full** pipeline: the 5.08 B DiT, the 8.39 B Qwen3.5-9B text encoder and the Flux2 VAE. It deliberately does *not* use the 4 GB NF4 path in ``../MOSSIMAGE-v0.2.0``. Why: ZeroGPU hands us an RTX Pro 6000 Blackwell (48 GB as ``large``, 96 GB as ``xlarge``). In bf16 the three components are 10.16 + 16.78 + 0.24 = **27.2 GB**, so everything fits and arbitrary prompts work. The 4 GB build exists to prove the arithmetic on a Pascal card with the encoder deleted; this one exists to be useful. Same weights, same upstream pipeline file, different constraint. Sizes are from ``../MOSSIMAGE-v0.2.0/README.md`` (measured, not estimated). Two traps carried over from that build, both load-bearing: 1. **The repo ships a tokenizer with no chat template.** ``apply_chat_template`` raises, and the template decides exactly which tokens the DiT was trained on (including the ``enable_thinking=True`` branch). We attach the template from ``Qwen/Qwen3.5-9B`` when the bundled one is missing. 2. **The pipeline class lives inside the model repo**, not in diffusers, so it is imported by path (``_vendor``). """ from __future__ import annotations import importlib.util import json import os import sys import threading import time from pathlib import Path from types import ModuleType import torch REPO_ID = "OpenMOSS-Team/MOSS-Image-SFT" CHAT_TEMPLATE_REPO = "Qwen/Qwen3.5-9B" VENDOR_MODULE = "moss_image_upstream" # Files the pipeline genuinely needs. Excluding the rest keeps the cold-start # download at ~27 GB instead of pulling every optional folder in the repo. ALLOW_PATTERNS = [ "pipeline_moss_image.py", "model_index.json", "transformer/*", "vae/*", "scheduler/*", "tokenizer/*", "text_encoder/*", ] _DTYPE = torch.bfloat16 # --------------------------------------------------------------------- paths def model_root() -> Path: """Where the weights live. ``/data`` is the only path that survives a Space restart (it needs the persistent-storage add-on). Without it we fall back to the HF cache, which is re-downloaded on a factory reboot — slower, but correct. """ override = os.environ.get("MOSS_MODEL_DIR") if override: return Path(override) if Path("/data").is_dir(): return Path("/data") / "MOSS-Image-SFT" return Path(os.environ.get("HF_HOME", Path.home() / ".cache" / "huggingface")) / "moss-image-sft" def ensure_model() -> Path: """Download the weights once, then reuse them.""" root = model_root() if (root / "transformer").is_dir() and (root / "pipeline_moss_image.py").is_file(): return root from huggingface_hub import snapshot_download root.mkdir(parents=True, exist_ok=True) print(f"[engine] downloading {REPO_ID} -> {root} (~27 GB on a cold cache)", flush=True) started = time.time() snapshot_download( repo_id=REPO_ID, local_dir=str(root), allow_patterns=ALLOW_PATTERNS, token=os.environ.get("HF_TOKEN") or None, ) print(f"[engine] download finished in {time.time() - started:.0f}s", flush=True) return root # -------------------------------------------------------------------- vendor def _vendor(model_dir: Path) -> ModuleType: """Import the upstream ``pipeline_moss_image.py`` from the model directory. It defines ``MOSSImageTransformer``, ``MOSSImageScheduler`` and ``MOSSImagePipeline``. Loaded unmodified: the transformer's dtype lookups and the pipeline's BatchNorm-fold decode are what make this model work at all, and a re-implementation would silently produce different images. """ if VENDOR_MODULE in sys.modules: return sys.modules[VENDOR_MODULE] path = model_dir / "pipeline_moss_image.py" if not path.is_file(): raise FileNotFoundError(f"{path} is missing; run ensure_model() first") spec = importlib.util.spec_from_file_location(VENDOR_MODULE, path) if spec is None or spec.loader is None: raise ImportError(f"cannot import {path}") module = importlib.util.module_from_spec(spec) sys.modules[VENDOR_MODULE] = module spec.loader.exec_module(module) return module # --------------------------------------------------------------- transformer def _state_dict(transformer_dir: Path) -> dict[str, torch.Tensor]: """Merge the (possibly sharded) safetensors checkpoint into one dict.""" from safetensors.torch import load_file index = transformer_dir / "diffusion_pytorch_model.safetensors.index.json" single = transformer_dir / "diffusion_pytorch_model.safetensors" if index.is_file(): weight_map = json.loads(index.read_text(encoding="utf-8"))["weight_map"] state: dict[str, torch.Tensor] = {} for shard in sorted(set(weight_map.values())): state.update(load_file(str(transformer_dir / shard))) return state if single.is_file(): return load_file(str(single)) raise FileNotFoundError(f"no safetensors checkpoint in {transformer_dir}") def _load_transformer(upstream: ModuleType, model_dir: Path): """Prefer diffusers' ``from_pretrained``; fall back to config + state dict. The class is defined in the vendored file rather than registered with diffusers, so ``from_pretrained`` is only available through the ``ConfigMixin``/``ModelMixin`` base classes it inherits. If that contract changes upstream, the fallback still builds the model. """ tdir = model_dir / "transformer" cls = upstream.MOSSImageTransformer try: transformer = cls.from_pretrained(str(tdir), torch_dtype=_DTYPE) print("[engine] transformer via from_pretrained", flush=True) except Exception as exc: # noqa: BLE001 - any failure means "do it by hand" print(f"[engine] from_pretrained unavailable ({type(exc).__name__}: {exc}); " "building from config", flush=True) config = json.loads((tdir / "config.json").read_text(encoding="utf-8")) config.pop("_class_name", None) config.pop("_diffusers_version", None) transformer = cls(**config) missing, unexpected = transformer.load_state_dict(_state_dict(tdir), strict=False) if missing: raise RuntimeError(f"{len(missing)} tensors missing, e.g. {missing[:3]}") if unexpected: print(f"[engine] {len(unexpected)} unexpected tensors ignored", flush=True) transformer = transformer.to(_DTYPE) return transformer.eval().requires_grad_(False) # ------------------------------------------------------------- text encoder def _load_text_encoder(model_dir: Path): """Qwen3.5-9B hidden states, which is what the DiT actually consumes. ``transformers>=5.3`` is required for ``Qwen3_5Model``; requirements.txt pins it. The tokenizer needs the Qwen3.5 chat template because the MOSS repo ships one without a template, and warning-free wrong conditioning is the worst failure mode here. """ from transformers import AutoModel, AutoTokenizer te_dir = model_dir / "text_encoder" tok_dir = te_dir if (te_dir / "tokenizer_config.json").is_file() else model_dir / "tokenizer" if not tok_dir.is_dir(): raise FileNotFoundError(f"no tokenizer under {te_dir} or {model_dir / 'tokenizer'}") tokenizer = AutoTokenizer.from_pretrained(str(tok_dir)) if getattr(tokenizer, "chat_template", None) is None: print("[engine] bundled tokenizer has no chat_template; attaching Qwen3.5's", flush=True) from huggingface_hub import hf_hub_download config = json.loads( Path(hf_hub_download(CHAT_TEMPLATE_REPO, "tokenizer_config.json")).read_text(encoding="utf-8") ) tokenizer.chat_template = config["chat_template"] encoder = AutoModel.from_pretrained( str(te_dir), torch_dtype=_DTYPE, low_cpu_mem_usage=True ) return encoder.eval().requires_grad_(False), tokenizer # --------------------------------------------------------------------- engine class Engine: """Holds the three components and turns a prompt into a PIL image.""" def __init__(self, pipe, model_dir: Path): self.pipe = pipe self.model_dir = model_dir self.lock = threading.Lock() def components(self) -> str: """Human-readable VRAM accounting, shown in the UI footer.""" def gb(n: int) -> str: return f"{n / 1e9:.2f} GB" parts = [] for name in ("transformer", "text_encoder", "vae"): module = getattr(self.pipe, name, None) if module is None: continue total = sum(p.numel() * p.element_size() for p in module.parameters()) parts.append(f"{name} {gb(total)}") if torch.cuda.is_available(): parts.append(f"allocated {gb(torch.cuda.memory_allocated())}") return " · ".join(parts) @torch.no_grad() def generate( self, prompt: str, negative_prompt: str = "", height: int = 1024, width: int = 1024, steps: int = 20, guidance_scale: float = 3.0, seed: int = 0, ): """Run one text-to-image generation and return (PIL image, metadata dict).""" if not prompt or not prompt.strip(): raise ValueError("prompt is empty") for label, value in (("height", height), ("width", width)): if value % 16 != 0: raise ValueError(f"{label} must be a multiple of 16, got {value}") if not 1 <= steps <= 50: raise ValueError(f"steps must be 1..50, got {steps}") generator = torch.Generator("cpu").manual_seed(int(seed)) started = time.time() # Serialise: one process owns the card, and a second concurrent call on # ZeroGPU would contend for the same 27 GB of weights. with self.lock: # negative_prompt must stay a string: upstream's signature defaults to # '' and routes it through encode_prompt, which raises on None. Passing # None for "no negative" fails the whole call whenever guidance != 1. image = self.pipe( prompt=prompt.strip(), negative_prompt=negative_prompt.strip(), height=int(height), width=int(width), num_inference_steps=int(steps), guidance_scale=float(guidance_scale), generator=generator, output_type="pil", ).images[0] elapsed = time.time() - started meta = { "prompt": prompt.strip(), "negative_prompt": negative_prompt.strip(), "height": int(height), "width": int(width), "steps": int(steps), "guidance_scale": float(guidance_scale), "seed": int(seed), "seconds": round(elapsed, 2), "seconds_per_step": round(elapsed / max(int(steps), 1), 3), "model": REPO_ID, "precision": "bfloat16", } return image, meta def load() -> Engine: """Build the whole pipeline and place it on the GPU. Called at import time, which is what ZeroGPU requires: parameters must be on ``cuda`` outside ``@spaces.GPU`` (CUDA emulation makes that legal), and moving them inside the decorated function instead is documented as "significantly less efficient". """ started = time.time() model_dir = ensure_model() upstream = _vendor(model_dir) from diffusers import AutoencoderKLFlux2 transformer = _load_transformer(upstream, model_dir) text_encoder, tokenizer = _load_text_encoder(model_dir) vae = AutoencoderKLFlux2.from_pretrained( str(model_dir / "vae"), torch_dtype=_DTYPE ).eval().requires_grad_(False) scheduler_path = model_dir / "scheduler" / "scheduler_config.json" scheduler = ( upstream.MOSSImageScheduler.from_config( json.loads(scheduler_path.read_text(encoding="utf-8")) ) if scheduler_path.is_file() else upstream.MOSSImageScheduler() ) pipe = upstream.MOSSImagePipeline( transformer=transformer, scheduler=scheduler, text_encoder=text_encoder, tokenizer=tokenizer, vae=vae, ) pipe = pipe.to("cuda") engine = Engine(pipe, model_dir) print(f"[engine] ready in {time.time() - started:.0f}s — {engine.components()}", flush=True) return engine