File size: 12,560 Bytes
a7c7152
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
"""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