File size: 9,043 Bytes
565b868
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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)