File size: 11,106 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
"""MOSS-Image EDIT DiT (Moss-Image-Edit LoRA contract "ref-prefix-only-t0__target-text-original-moss-v1") as OpenVINO segments.

The contract (github.com/Chenkin-x/Moss-Image-Edit, moss_edit/model.py; ComfyUI PR 17296 "index_timestep_zero_text_start"):
  * reference images are VAE-encoded latents, tokens at timestep 0 (their own modulation), RoPE coords (r=index+1, f=0, h, w) centred;
  * reference queries attend ONLY reference keys (refs see each other), so the reference branch never depends on text, target or t;
  * text + target queries attend text, target AND reference keys; text f = 0..L-1, target f = L (the plain t2i layout).
  Hence every block's reference K/V can be computed once per request and reused for all steps and both CFG branches.

One graph per segment does both jobs (same weights, no second copy on the card):
  inputs  x [1,T,3072] f32 (already embedded tokens: host does video_embedder + text_refine concat), rope [1,T,128], mod [1,6,3072],
          kv_in [nl,2,1,R,3072] f16 (cached reference K (post norm + RoPE) and V per block of the segment), kbias [1,1,1,R] f32 (0 = visible),
          n_kv [1,K,1] (marker: K = number of leading x tokens whose K/V are returned)
  outputs x (or velocity for segment C) and kv_out [nl,2,1,K,3072] f16
  * PREFILL: x = reference tokens, mod = mod(t=0), kv_in = EMPTY (R = 0), K = T -> kv_out = the reference cache
    (a ref query then sees only ref keys: exact contract, no mask needed; the shipped graphs have no kbias input).
  * STEP:    x = [target, text], mod = mod(t), kv_in = the cache, K = 1 (tiny unused output).
  The residual stream runs divided by RES_SCALE (8) inside the fp16 graph (see edit_block); x in/out are unscaled f32.
  Attention keys are [x tokens, ref tokens]; order does not matter for attention (RoPE is carried per token).
Weights: SFT transformer with the LoRA delta (alpha/rank * B @ A) merged in fp32 before the cast to the IR precision
(delta ~5 % of |W|; fp16 rounding of the merged weight loses ~0.5 % of the delta: lora_stats.py).
"""
import json
import os
import sys

import numpy as np
import torch
import torch.nn.functional as F

sys.path.insert(0, "/opt/mossimage/code")
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from dit_ops import DIM, HEADS, SEG_A, SEG_B, SEG_C, _meta_block, _small, dit_store, load_orig_module  # noqa: E402

LORA_DIR = os.environ.get("MOSS_EDIT_LORA", "/opt/mossimage/hf/edit_lora")
MASK_NEG = -30000.0


class LoraDelta:
    """Lazy reader of the Moss-Image-Edit adapter: delta(name) = alpha/rank * B @ A (fp32)."""

    def __init__(self, path=LORA_DIR):
        from safetensors import safe_open

        self.cfg = json.load(open(f"{path}/adapter_config.json"))
        if self.cfg.get("format") != "moss-edit-lora" or self.cfg.get("metadata", {}).get("edit_contract") != "ref-prefix-only-t0__target-text-original-moss-v1":
            raise ValueError("not a Moss-Image-Edit v1 adapter")
        self.f = safe_open(f"{path}/adapter_model.safetensors", "pt")
        self.used = set()

    def delta(self, name):
        spec = self.cfg["modules"].get(name)
        if spec is None:
            return None
        A = self.f.get_tensor(name + ".lora_A").float()
        B = self.f.get_tensor(name + ".lora_B").float()
        self.used.add(name)
        return (spec["alpha"] / spec["rank"]) * (B @ A)


def build_layers_merged(mod, st, idxs, dtype, lora):
    out = []
    for i in idxs:
        b = _meta_block(mod, dtype)
        prefix = f"layers.{i}."
        sd = {}
        for k in st.keys():
            if k.startswith(prefix):
                w = torch.from_numpy(st.get_f32(k))
                if lora is not None and k.endswith(".weight"):
                    d = lora.delta(k[: -len(".weight")])
                    if d is not None:
                        w = w + d
                sd[k[len(prefix):]] = w
        b.load_state_dict(sd, strict=True)
        out.append(b.eval())
    return out


def _rotate(x, rope):
    sin, cos = rope.chunk(2, -1)
    sin = torch.cat((sin, sin), -1).unsqueeze(-2)
    cos = torch.cat((cos, cos), -1).unsqueeze(-2)
    a, b = x.chunk(2, -1)
    return x * cos + torch.cat((-b, a), -1) * sin


def _situ(hidden, gate):
    return (4.0 * torch.tanh(gate / 4.0) * torch.sigmoid(gate)) * (25.0 * torch.tanh(hidden / 25.0))


RES_SCALE = float(os.environ.get("MOSS_EDIT_RES_SCALE", "8"))


def edit_block(layer, x, rope, mod, kr, vr, mask, n_kv, inv_s=1.0):
    """The original _Block.forward with external reference K/V appended to the keys. Returns x, k, v (k post norm+RoPE, flat).
    x may be the residual stream divided by s (inv_s = 1/s): both RMSNorms are scale invariant, so only the two branch gates are scaled.
    This keeps the fp16 residual far from the fp16 maximum (it reaches ~60k unscaled in late steps) and is exact up to the norm eps."""
    shift_a, scale_a, gate_a, shift_f, scale_f, gate_f = mod.unbind(1)
    if inv_s != 1.0:
        gate_a, gate_f = gate_a * inv_s, gate_f * inv_s
    dt = layer.proj["q"].weight.dtype
    y = (layer.norm1(x) * (1 + scale_a[:, None]) + shift_a[:, None]).to(dt)
    q = layer.q_norm(layer.proj["q"](y).unflatten(-1, (HEADS, -1)))
    k = layer.k_norm(layer.proj["k"](y).unflatten(-1, (HEADS, -1)))
    v = layer.proj["v"](y)
    q = _rotate(q, rope)
    k = _rotate(k, rope).flatten(2)
    kall = torch.cat((k, kr.to(dt)), 1)
    vall = torch.cat((v, vr.to(dt)), 1)
    qh = q.transpose(1, 2).to(dt)
    kh = kall.unflatten(-1, (HEADS, -1)).transpose(1, 2)
    vh = vall.unflatten(-1, (HEADS, -1)).transpose(1, 2)
    a = (F.scaled_dot_product_attention(qh, kh, vh, attn_mask=mask) if mask is not None else F.scaled_dot_product_attention(qh, kh, vh)).transpose(1, 2).flatten(2)
    x = x + layer.proj["o"](a) * gate_a[:, None]
    y = layer.norm2(x) * (1 + scale_f[:, None]) + shift_f[:, None]
    hidden, gate = layer.proj["ffn_up_gate"](y.to(dt)).chunk(2, -1)
    x = x + layer.proj["ffn_down"](_situ(hidden, gate)) * gate_f[:, None]
    n = n_kv.shape[1]
    return x, torch.stack((k[:, :n], v[:, :n]), 0)


class EditSeg(torch.nn.Module):
    def __init__(self, layers, dtype, norm=None, lin=None, res_scale=1.0):
        super().__init__()
        self.layers = torch.nn.ModuleList(layers)
        self.norm, self.lin, self.dtype = norm, lin, dtype
        self.res_scale = float(res_scale)

    def body(self, x, rope, mod, kv_in, kbias, n_kv):
        """Returns the residual stream DIVIDED by res_scale (callers scale back in f32; segment C only normalises it)."""
        dt = self.dtype
        inv_s = 1.0 / self.res_scale
        x = x * inv_s if inv_s != 1.0 else x
        x, rope, mod = x.to(dt), rope.to(dt), mod.to(dt)
        if kbias is None:
            mask = None                                              # unmasked graph: prefill passes an EMPTY cache (R = 0)
        else:
            zb = (x[:, :, :1] * 0).transpose(1, 2).unsqueeze(1)    # [1,1,1,T] zeros
            mask = torch.cat((zb, kbias.to(dt)), -1)                 # [1,1,1,T+R]
        kvs = []
        for i, layer in enumerate(self.layers):
            x, kv = edit_block(layer, x, rope, mod, kv_in[i, 0], kv_in[i, 1], mask, n_kv, inv_s)
            kvs.append(kv)
        return x, torch.stack(kvs, 0).to(torch.float16)


class EditSegAB(EditSeg):
    def forward(self, x, rope, mod, kv_in, kbias, n_kv):
        x, kv = self.body(x, rope, mod, kv_in, kbias, n_kv)
        return x.float() * self.res_scale, kv


class EditSegABNoMask(EditSeg):
    def forward(self, x, rope, mod, kv_in, n_kv):
        x, kv = self.body(x, rope, mod, kv_in, None, n_kv)
        return x.float() * self.res_scale, kv


class EditSegCNoMask(EditSeg):
    def forward(self, x, rope, mod, kv_in, n_kv, head, n_img):
        x, kv = self.body(x, rope, mod, kv_in, None, n_kv)
        n = n_img.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]
        return self.lin(x.to(self.lin.weight.dtype)).float(), kv


class EditSegC(EditSeg):
    def forward(self, x, rope, mod, kv_in, kbias, n_kv, head, n_img):
        x, kv = self.body(x, rope, mod, kv_in, kbias, n_kv)
        n = n_img.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]
        return self.lin(x.to(self.lin.weight.dtype)).float(), kv


SEGS = {"edit_a": SEG_A, "edit_b": SEG_B, "edit_c": SEG_C}


def build_edit_segment(name, dtype, lora_dir=LORA_DIR, merge=True):
    mod = load_orig_module()
    st = dit_store("sft")
    lora = LoraDelta(lora_dir) if merge else None
    idxs = SEGS[name]
    nl = len(idxs)
    layers = build_layers_merged(mod, st, idxs, dtype, lora)
    T, R, K = 96, 32, 96
    ex = lambda *s: torch.randn(*s)  # noqa: E731
    # unmasked graphs (v2): the prefill passes an EMPTY cache (R = 0), so reference queries see only reference keys without any mask
    common_in = (ex(1, T, DIM), ex(1, T, 128), ex(1, 6, DIM) * 0.1, torch.randn(nl, 2, 1, R, DIM).half(), torch.zeros(1, K, 1))
    specs = [("x", [1, -1, DIM], "f32"), ("rope", [1, -1, 128], "f32"), ("mod", [1, 6, DIM], "f32"), ("kv_in", [nl, 2, 1, -1, DIM], "f16"),
             ("n_kv", [1, -1, 1], "f32")]
    if name == "edit_c":
        norm = _small(mod, mod._RMSNorm, st, "final_norm_video.", dtype, DIM)
        with torch.device("meta"):
            lin = torch.nn.Linear(DIM, 128, bias=False)
        lin = lin.to(dtype).to_empty(device="cpu")
        lin.load_state_dict({"weight": torch.from_numpy(st.get_f32("final_linear_video.weight"))})
        m = EditSegCNoMask(layers, dtype, norm, lin.eval(), res_scale=RES_SCALE).eval()
        ex_in = common_in + (ex(1, 2, DIM) * 0.1, torch.zeros(1, 64, 1))
        specs += [("head", [1, 2, DIM], "f32"), ("n_img", [1, -1, 1], "f32")]
        outs = ["v", "kv_out"]
    else:
        m = EditSegABNoMask(layers, dtype, res_scale=RES_SCALE).eval()
        ex_in = common_in
        outs = ["x_out", "kv_out"]
    used = sorted(lora.used) if lora is not None else []
    return m, ex_in, specs, outs, used


# ------------------------------------------------------------------ host glue (numpy)
def ref_rope(h, w, index, head_dim=128, base=10000.0):
    """RoPE [1, h*w, 128] for reference image `index` (0-based): coords (index+1, 0, row-centred, col-centred), as MossEditModel._reference_inputs."""
    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 edit_host_weights():
    st = dit_store("sft")
    return {"emb_w": st.get_f32("video_embedder.weight"), "emb_b": st.get_f32("video_embedder.bias")}