"""MOSS-Image DiT split into OpenVINO-friendly segments + host-side glue (numpy). The graph code (blocks, attention, situ activation, text refiner) is the ORIGINAL code of pipeline_moss_image.py (Apache-2.0, OpenMOSS-Team): this module imports the original classes and only wraps them. Segments (a model is split so that CFG's negative branch can skip block 22 without a second copy of the weights): text_refine : ctx [1,L,4096], rope_t [1,L,128] -> text [1,L,3072] (once per prompt) dit_a : tokens [1,N,128], text [1,L,3072], rope [1,N+L,128], mod [1,6,3072] -> x (embed + blocks 0..21) dit_b : x, rope, mod -> x (block 22) dit_c : x, rope, mod, head [1,2,3072] -> velocity tokens [1,N,128] (blocks 23..41 + final head) """ import json import os import sys import numpy as np import torch sys.path.insert(0, __import__("os").path.dirname(__import__("os").path.abspath(__file__))) from common import HF, ST # noqa: E402 NUM_LAYERS = 42 DIM = 3072 HEADS = 24 SEG_A = list(range(0, 22)) SEG_B = [22] SEG_C = list(range(23, 42)) def load_orig_module(): """Import the original pipeline file as a module (gives _Block, _TextProjection, _RoPE, MOSSImageScheduler ...).""" import importlib.util path = f"{HF['sft']}/pipeline_moss_image.py" spec = importlib.util.spec_from_file_location("pipeline_moss_image", path) mod = importlib.util.module_from_spec(spec) sys.modules["pipeline_moss_image"] = mod spec.loader.exec_module(mod) return mod def dit_store(which="sft"): return ST(f"{HF[which]}/transformer", "diffusion_pytorch_model.safetensors.index.json") def _load_into(module, st, prefix, dtype): sd = {} for k in st.keys(): if k.startswith(prefix): sd[k[len(prefix):]] = torch.from_numpy(st.get_f32(k)) module.load_state_dict(sd, strict=True) def _meta_block(mod, dtype): with torch.device("meta"): b = mod._Block(DIM, 8192, HEADS) return b.to(dtype).to_empty(device="cpu") def build_layers(mod, st, idxs, dtype): out = [] for i in idxs: b = _meta_block(mod, dtype) _load_into(b, st, f"layers.{i}.", dtype) out.append(b.eval()) return out def _small(mod, cls, st, prefix, dtype, *args): with torch.device("meta"): m = cls(*args) m = m.to(dtype).to_empty(device="cpu") _load_into(m, st, prefix, dtype) return m.eval() class TextRefine(torch.nn.Module): def __init__(self, tp, dtype): super().__init__() self.tp = tp self.dtype = dtype def forward(self, ctx, rope_t): return self.tp(ctx.to(self.dtype), rope_t.to(self.dtype)).float() class SegA(torch.nn.Module): def __init__(self, embedder, layers, dtype): super().__init__() self.embedder = embedder self.layers = torch.nn.ModuleList(layers) self.dtype = dtype def forward(self, tokens, text, rope, mod): rope = rope.to(self.dtype) mod = mod.to(self.dtype) v = self.embedder(tokens.to(self.dtype)) x = torch.cat((v, text.to(self.dtype)), 1) for layer in self.layers: x = layer(x, rope, mod) return x.float() class SegLayers(torch.nn.Module): def __init__(self, layers, dtype): super().__init__() self.layers = torch.nn.ModuleList(layers) self.dtype = dtype def forward(self, x, rope, mod): x = x.to(self.dtype) rope = rope.to(self.dtype) mod = mod.to(self.dtype) for layer in self.layers: x = layer(x, rope, mod) return x.float() class SegC(torch.nn.Module): """Blocks 23..41 + final norm/modulation/linear; returns velocity tokens for the first n_img tokens.""" def __init__(self, layers, norm, lin, dtype): super().__init__() self.layers = torch.nn.ModuleList(layers) self.norm = norm self.lin = lin self.dtype = dtype def forward(self, x, rope, mod, head, n_img_marker): # n_img_marker: [1,N,1] zeros, only carries the image-token count N as a dynamic shape x = x.to(self.dtype) rope = rope.to(self.dtype) mod = mod.to(self.dtype) for layer in self.layers: x = layer(x, rope, mod) n = n_img_marker.shape[1] x = self.norm(x[:, :n].to(self.norm.weight.dtype)) head = head.to(self.dtype) x = x * (1 + head[:, 1, None]) + head[:, 0, None] x = self.lin(x.to(self.lin.weight.dtype)) return x.float() def build_segments(which, dtype, only=None): """Yield (name, module, example_inputs, input_specs) for the DiT segments.""" mod = load_orig_module() st = dit_store(which) segs = {} N, L = 256, 24 # example sizes for tracing (16x16 latent tokens + 24 text tokens) cfg_dim = DIM def ex(*shape): return torch.randn(*shape) if only in (None, "text_refine"): tp = _small(mod, mod._TextProjection, st, "text_embedder.", dtype, 4096, DIM, 8192, HEADS) segs["text_refine"] = ( TextRefine(tp, dtype).eval(), (ex(1, L, 4096), ex(1, L, 128)), [("ctx", [1, -1, 4096]), ("rope_t", [1, -1, 128])], ["text"], ) if only in (None, "dit_a"): emb = _small(mod, torch.nn.Linear, st, "video_embedder.", dtype, 128, DIM) segs["dit_a"] = ( SegA(emb, build_layers(mod, st, SEG_A, dtype), dtype).eval(), (ex(1, N, 128), ex(1, L, DIM), ex(1, N + L, 128), ex(1, 6, DIM)), [("tokens", [1, -1, 128]), ("text", [1, -1, DIM]), ("rope", [1, -1, 128]), ("mod", [1, 6, DIM])], ["x"], ) if only in (None, "dit_b"): segs["dit_b"] = ( SegLayers(build_layers(mod, st, SEG_B, dtype), dtype).eval(), (ex(1, N + L, DIM), ex(1, N + L, 128), ex(1, 6, DIM)), [("x", [1, -1, DIM]), ("rope", [1, -1, 128]), ("mod", [1, 6, DIM])], ["xo"], ) if only in (None, "dit_c"): norm = _small(mod, mod._RMSNorm, st, "final_norm_video.", dtype, DIM) # final_linear_video has bias=False in the original with torch.device("meta"): lin = torch.nn.Linear(DIM, 128, bias=False) lin = lin.to(dtype).to_empty(device="cpu") _load_into(lin, st, "final_linear_video.", dtype) segs["dit_c"] = ( SegC(build_layers(mod, st, SEG_C, dtype), norm, lin.eval(), dtype).eval(), (ex(1, N + L, DIM), ex(1, N + L, 128), ex(1, 6, DIM), ex(1, 2, DIM), torch.zeros(1, N, 1)), [("x", [1, -1, DIM]), ("rope", [1, -1, 128]), ("mod", [1, 6, DIM]), ("head", [1, 2, DIM]), ("n_img", [1, -1, 1])], ["v"], ) return segs # ------------------------------------------------------------------ host glue (numpy only) def host_weights(which="sft"): """Small weights used on the host: time embedding MLP + modulation heads. float32 numpy.""" st = dit_store(which) w = {} for name, key in [ ("te0_w", "time_embedding.0.weight"), ("te0_b", "time_embedding.0.bias"), ("te2_w", "time_embedding.2.weight"), ("te2_b", "time_embedding.2.bias"), ("mod_w", "shared_block_modulation.weight"), ("mod_b", "shared_block_modulation.bias"), ("head_w", "video_head_modulation.weight"), ("head_b", "video_head_modulation.bias"), ]: w[name] = st.get_f32(key) return w def time_mod(w, timestep, freq_dim=256): """timestep: float (0..1000 scale as passed to the original transformer). Returns mod [1,6,3072], head [1,2,3072].""" half = freq_dim // 2 freq = 10000.0 ** (-np.arange(half, dtype=np.float64) / half) phase = np.float64(timestep) * freq emb = np.concatenate([np.cos(phase), np.sin(phase)]).astype(np.float32)[None] h = emb @ w["te0_w"].T + w["te0_b"] h = h / (1.0 + np.exp(-h)) # SiLU t = h @ w["te2_w"].T + w["te2_b"] mod = (t @ w["mod_w"].T + w["mod_b"]).reshape(1, 6, -1).astype(np.float32) head = (t @ w["head_w"].T + w["head_b"]).reshape(1, 2, -1).astype(np.float32) return mod, head def rope_table(height, width, text_len, head_dim=128, base=10000.0): """Joint rope [1, h*w + L, head_dim] float32 for image tokens followed by text tokens (matches _RoPE.forward).""" nb = head_dim // 8 bands = (1.0 / (base ** (np.arange(nb, dtype=np.float32) / nb))).astype(np.float32) hh, ww = np.meshgrid(np.arange(height), np.arange(width), indexing="ij") img = np.stack([np.zeros_like(hh), np.full_like(hh, text_len), hh, ww], -1).reshape(-1, 4).astype(np.float32) img[:, 2] -= (height - 1) / 2 img[:, 3] -= (width - 1) / 2 txt = np.zeros((text_len, 4), np.float32) txt[:, 1] = np.arange(text_len, dtype=np.float32) coords = np.concatenate([img, txt], 0) phase = coords[..., None] * bands # [N,4,nb] rope = np.concatenate([np.sin(phase), np.cos(phase)], -2).reshape(coords.shape[0], -1) return rope[None].astype(np.float32)