File size: 29,118 Bytes
4a1ea7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
"""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),
    # image EDITING: MOSS-Image-SFT + the community Moss-Image-Edit LoRA (chinoll/Moss-Image-Edit, rank 64) merged into the weights, reference images as
    # timestep-0 prefix tokens whose K/V are computed once per request (edit_ops.py). Same text encoder; text_refine + host_weights are copies of the t2i ones.
    # max_pixels / default guidance: measured on the B60 (MOSSIMAGE.md "Editing").
    "edit": dict(dit="dit_sft_edit", te="te", sampler="edit", max_steps=100, default_steps=30, default_guidance=4.0, max_pixels=1024 * 1024),
    "edit-int8": dict(dit="dit_sft_edit_int8_keepdown", te="te", sampler="edit", max_steps=100, default_steps=30, default_guidance=4.0,
                      max_pixels=1024 * 1024),
}
EDIT_SEGS = ("text_refine", "edit_a", "edit_b", "edit_c")
T2I_SEGS = ("text_refine", "dit_a", "dit_b", "dit_c")
KV_DIM = 3072
MASK_NEG = -30000.0


def ref_rope(h, w, index, head_dim=128, base=10000.0):
    """RoPE [1, h*w, 128] of reference image `index` (0-based): coordinates (index+1, 0, row - centre, col - centre) (Moss-Image-Edit contract)."""
    nb = head_dim // 8
    bands = (1.0 / (base ** (np.arange(nb, dtype=np.float32) / nb))).astype(np.float32)
    hh, ww = np.meshgrid(np.arange(h), np.arange(w), indexing="ij")
    c = np.stack([np.full_like(hh, index + 1), np.zeros_like(hh), hh, ww], -1).reshape(-1, 4).astype(np.float32)
    c[:, 2] -= (h - 1) / 2
    c[:, 3] -= (w - 1) / 2
    phase = c[..., None] * bands
    return np.concatenate([np.sin(phase), np.cos(phase)], -2).reshape(c.shape[0], -1)[None].astype(np.float32)


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())))


def _run(req, feed, out=None):
    """Set host inputs, run, return output `out` as an owned array. Unlike infer(), never touches the other outputs (an edit request's
    K/V output lives on the card and cannot be read as numpy)."""
    keep = [np.ascontiguousarray(v) for v in feed.values()]
    for k, v in zip(feed, keep):
        req.set_tensor(k, ov.Tensor(v))
    req.start_async()
    req.wait()
    return np.array(req.get_tensor(out).data) if out else None


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._edit_sig = None     # token counts the loaded edit DiT has run at (see generate_edit)
        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):
        def ok(v):
            d = f"{self.dir}/{v['dit']}"
            segs = EDIT_SEGS if v["sampler"] == "edit" else T2I_SEGS
            need = [f"{d}/{s}.xml" for s in segs] + [f"{d}/host_weights.npz", f"{self.dir}/{v['te']}/te_part3.xml"]
            if v["sampler"] == "edit":
                need += [f"{d}/edit_host.npz", f"{d}/vae_encoder_f32.xml"]
            return all(os.path.exists(p) for p in need)

        return [n for n, v in VARIANTS.items() if ok(v)]

    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.emb = dict(np.load(f"{self.dit_dir}/edit_host.npz")) if v["sampler"] == "edit" else None
        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:
            segs = EDIT_SEGS if self.cfg["sampler"] == "edit" else T2I_SEGS
            self.dit = {n: self._compile(n, f"{self.dit_dir}/{n}.xml") for n in segs}
            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 encode_images(self, images):
        """images: list of uint8 HxWx3 arrays (sides multiples of 16) -> list of normalised packed latents [1,128,H/16,W/16] float32.
        FLUX.2 encoder + quant_conv on the card (posterior mode), then the 2x2 pack (c, dy, dx) and the BN normalisation on the host,
        as moss_edit.processing.encode_image. Compiled per request and released (its scratch memory is large at 1 MP)."""
        hint = os.environ.get("MOSSIMAGE_VAE_ENC_PRECISION", "f32")
        cm = self._compile("vae_encoder", f"{self.dit_dir}/vae_encoder_f32.xml", hint or None)
        req = cm.create_infer_request()
        out = []
        for im in images:
            x = (im.astype(np.float32) / 127.5 - 1.0).transpose(2, 0, 1)[None]
            z = _first(req.infer({"image": np.ascontiguousarray(x)}))
            b, c, h, w = z.shape
            z = z.reshape(b, c, h // 2, 2, w // 2, 2).transpose(0, 1, 3, 5, 2, 4).reshape(b, 4 * c, h // 2, w // 2)
            out.append(((z - self.bn_mean) / self.bn_scale).astype(np.float32))
        self._note_mem()
        del req, cm
        gc.collect()
        return out

    # ------------------------------------------------------------------ edit DiT (reference K/V cache on the card)
    def _kv_tensor(self, shape):
        """A device tensor for a K/V cache: the cache never leaves the card between prefill and the steps."""
        if self.device == "GPU":
            return self.core.get_default_context("GPU").create_tensor(ov.Type.f16, ov.Shape(shape), {})
        return ov.Tensor(ov.Type.f16, ov.Shape(shape))

    def _edit_prefill(self, ref_lat):
        """Reference latents -> per-segment K/V caches {seg: tensor [nl,2,1,R,3072]}. The reference tokens run once through all 42 blocks at timestep 0
        and attend only to themselves: the external cache passed in is EMPTY (R = 0), so no mask is needed."""
        toks, ropes = [], []
        for i, z in enumerate(ref_lat):
            _, c, h, w = z.shape
            toks.append(z.reshape(1, c, h * w).transpose(0, 2, 1))
            ropes.append(ref_rope(h, w, i))
        tok = np.concatenate(toks, 1)
        x = (tok @ self.emb["emb_w"].T + self.emb["emb_b"]).astype(np.float32)
        rope = np.ascontiguousarray(np.concatenate(ropes, 1))
        R = x.shape[1]
        mod0, head0 = time_mod(self.hw, 0.0)
        caches = {}
        n_kv = np.zeros((1, R, 1), np.float32)
        for seg in ("edit_a", "edit_b", "edit_c"):
            req = self.dit_req[seg]
            nl = self.dit[seg].input("kv_in").get_partial_shape()[0].get_length()
            kv = self._kv_tensor([nl, 2, 1, R, KV_DIM])
            req.set_tensor("kv_out", kv)
            feed = {"x": x, "rope": rope, "mod": mod0, "kv_in": np.zeros((nl, 2, 1, 0, KV_DIM), np.float16), "n_kv": n_kv}
            if seg == "edit_c":
                feed.update(head=head0, n_img=np.zeros((1, 1, 1), np.float32))
            _run(req, feed)
            if seg != "edit_c":
                x = np.array(req.get_tensor("x_out").data)
            caches[seg] = kv
        # fresh requests for the steps: the prefill's scratch memory (its own token count) is released with the old requests;
        # the caches are our own device tensors and survive
        self._fresh_requests()
        for seg, kv in caches.items():
            nl = kv.get_shape()[0]
            req = self.dit_req[seg]
            req.set_tensor("kv_in", kv)
            # the steps write a 1-token K/V (unused) into their own small buffer
            req.set_tensor("kv_out", self._kv_tensor([nl, 2, 1, 1, KV_DIM]))
        return caches, R

    def _fresh_requests(self, segs=("edit_a", "edit_b", "edit_c")):
        """Replace the segments' infer requests (frees their intermediate buffers; OpenVINO GPU keeps them per request)."""
        for seg in segs:
            self.dit_req[seg] = None
        gc.collect()
        for seg in segs:
            self.dit_req[seg] = self.dit[seg].create_infer_request()

    def _edit_velocity(self, x, rope, mod, head, n_one, n_marker, skip_b):
        r = self.dit_req
        x = _run(r["edit_a"], {"x": x, "rope": rope, "mod": mod, "n_kv": n_one}, "x_out")
        if not skip_b:
            x = _run(r["edit_b"], {"x": x, "rope": rope, "mod": mod, "n_kv": n_one}, "x_out")
        return _run(r["edit_c"], {"x": x, "rope": rope, "mod": mod, "n_kv": n_one, "head": head, "n_img": n_marker}, "v")

    def generate_edit(self, images, prompt, negative="", width=None, height=None, steps=None, guidance=None, seed=0, skip_uncond_block=True,
                      progress=None, cancel=None, embeds=None, return_latents=False, variant=None, ref_latents=None, keep_peak=False,
                      release_dit=False):
        """Edit: images = list of uint8 HxWx3 reference arrays (image 1 = the canvas; the caller sizes it to the output, multiples of 16).
        Returns (uint8 HxWx3, stats). Sampler as the Moss-Image-Edit authors' (flow-matching Euler on the MOSS grid, shift 5) with CFG whose negative
        branch skips block 22 for the target/text tokens; reference K/V (all 42 blocks) are shared by both branches and all steps."""
        import torch

        if variant:
            self.select_variant(variant)
        if self.cfg["sampler"] != "edit":
            raise ValueError(f"model {self.variant} is not an edit model")
        steps = steps or self.cfg["default_steps"]
        guidance = self.cfg.get("default_guidance", 4.0) if guidance is None else guidance
        if not 1 <= steps <= self.cfg["max_steps"]:
            raise ValueError(f"steps must be 1-{self.cfg['max_steps']} for model {self.variant}")
        if height is None or width is None:
            height, width = images[0].shape[:2] if images is not None else (ref_latents[0].shape[2] * 16, ref_latents[0].shape[3] * 16)
        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 = {}
        if not keep_peak:             # keep_peak: the caller reset it before encode_images, whose scratch memory counts too
            self.peak_gpu_mb = 0
        self._note_mem()
        h, w = height // 16, width // 16
        N = h * w
        do_cfg = guidance != 1.0
        t0 = time.time()
        embs = list(embeds) if embeds is not None else self.encode_prompts([prompt] + ([negative] if do_cfg else []))
        stats["text_encoder_s"] = round(time.time() - t0, 2)
        t0 = time.time()
        if ref_latents is None:
            ref_latents = self.encode_images(images)
        stats["vae_encode_s"] = round(time.time() - t0, 2)
        t0 = time.time()
        # OpenVINO GPU keeps the intermediate buffers of every token count a dynamic graph has run at: an edit DiT that ran at other
        # counts (another size or prompt length) grows by GBs (measured 22.8k -> 27.8k peak), so it is reloaded instead (a few seconds)
        sig = (N, sum(z.shape[2] * z.shape[3] for z in ref_latents), embs[0].shape[0], embs[1].shape[0] if do_cfg else 0)
        if self.dit is not None and self._edit_sig not in (None, sig):
            self.unload_dit()
        self.load_dit()
        self._edit_sig = sig
        stats["dit_load_s"] = round(time.time() - t0, 2)
        t0 = time.time()
        caches, R = self._edit_prefill(ref_latents)
        stats["prefill_s"] = round(time.time() - t0, 2)
        stats["ref_tokens"] = int(R)
        self._note_mem()
        d = self.dit_req
        ropes, texts_r = {}, {}
        for name, e in (("c", embs[0]), ("u", embs[1] if do_cfg else None)):
            if e is None:
                continue
            L = e.shape[0]
            ropes[name] = rope_table(h, w, L)
            texts_r[name] = _first(d["text_refine"].infer({"ctx": e[None], "rope_t": ropes[name][:, N:]}))
        stats["tokens_prompt"] = int(embs[0].shape[0])
        stats["tokens_negative"] = int(embs[1].shape[0]) if do_cfg else None
        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)
        n_one = np.zeros((1, 1, 1), np.float32)
        ew, eb = self.emb["emb_w"].T, self.emb["emb_b"]
        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_emb = (tokens @ ew + eb).astype(np.float32)
            x = np.concatenate([v_emb, texts_r["c"]], 1)
            v = self._edit_velocity(x, ropes["c"], mod, head, n_one, n_marker, False)
            if do_cfg:
                xu = np.concatenate([v_emb, texts_r["u"]], 1)
                vu = self._edit_velocity(xu, ropes["u"], mod, head, n_one, n_marker, bool(skip_uncond_block))
                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["guidance"] = guidance
        stats["s_per_step"] = round(float(np.median(step_times)), 3)
        stats["step_first_s"] = round(step_times[0], 3)
        self._note_mem()
        # drop the caches and the steps' scratch before the decoder takes its own. release_dit: unload the edit DiT altogether (the caller's
        # last image of a request): the decoder then runs beside the text encoder only, and the next request starts from a fresh DiT
        del caches, d
        if release_dit:
            self.unload_dit()
        else:
            self._fresh_requests()
        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

    def unload_dit(self):
        self.dit = self.dit_req = None
        self._edit_sig = 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