amarck's picture
Add files using upload-large-folder tool
e9a2b5d verified
Raw History Blame Contribute Delete
15.1 kB
"""Ming-Image single-stream DiT (Z-Image family) in MLX.
Transcribed from diffusion/transformer.py + diffusion/generator.py
(ConditionedTransformer / ToClipMLP). Module attribute names mirror the
PyTorch state-dict keys so convert.py is (almost) an identity mapping.
Precision follows upstream: timestep embedding, RoPE and all norms are
computed in float32; matmuls run in the weight dtype (bf16).
"""
from __future__ import annotations
import math
import os
import mlx.core as mx
import mlx.nn as nn
import numpy as np
from . import kernels
# Debug switches (defaults are the fast paths; outputs match the reference paths):
# MING_FUSED_ROPE=0 -> unfused qk-norm/RoPE, MING_DROP_PAD=0 -> mask padding instead of dropping it
# fused qk-norm + RoPE Metal kernel
FUSED = os.environ.get("MING_FUSED_ROPE", "1") != "0"
# drop zero_masked alignment padding instead of masking it (MING_DROP_PAD=0: reference path)
DROP_PAD = os.environ.get("MING_DROP_PAD", "1") != "0"
ADALN_EMBED_DIM = 256
SEQ_MULTI_OF = 32
class RMSNorm(nn.Module):
def __init__(self, dim, eps):
super().__init__()
self.weight = mx.ones((dim,))
self.eps = eps
def __call__(self, x):
return mx.fast.rms_norm(x, self.weight, self.eps)
class LayerNorm(nn.Module):
"""nn.LayerNorm with optional affine; statistics in float32."""
def __init__(self, dim, eps=1e-5, affine=True):
super().__init__()
self.eps = eps
if affine:
self.weight = mx.ones((dim,))
self.bias = mx.zeros((dim,))
def __call__(self, x):
w = self.weight if "weight" in self else None
b = self.bias if "bias" in self else None
return mx.fast.layer_norm(x, w, b, self.eps)
def timestep_embedding(t, dim, max_period=10000):
half = dim // 2
freqs = mx.exp(-math.log(max_period) * mx.arange(0, half, dtype=mx.float32) / half)
args = t[:, None].astype(mx.float32) * freqs[None]
return mx.concatenate([mx.cos(args), mx.sin(args)], axis=-1)
class TimestepEmbedder(nn.Module):
def __init__(self, out_size, mid_size, freq_size=256):
super().__init__()
self.mlp = [nn.Linear(freq_size, mid_size), nn.SiLU(), nn.Linear(mid_size, out_size)]
self.freq_size = freq_size
def __call__(self, t):
x = timestep_embedding(t, self.freq_size).astype(self.mlp[0].weight.dtype)
for m in self.mlp:
x = m(x)
return x
def rope_cos_sin(pos_ids: np.ndarray, axes_dims, theta):
"""pos_ids: [L, n_axes] int. Returns cos, sin: [L, head_dim/2] float32.
Matches RopeEmbedder.precompute_freqs_cis (float64 freqs, float32 angles).
"""
angles = []
for i, d in enumerate(axes_dims):
freqs = 1.0 / (theta ** (np.arange(0, d, 2, dtype=np.float64) / d))
ang = np.outer(pos_ids[:, i].astype(np.float64), freqs).astype(np.float32)
angles.append(ang)
ang = np.concatenate(angles, axis=-1)
return mx.array(np.cos(ang)), mx.array(np.sin(ang))
def apply_rope(x, cos, sin):
"""x: [B, H, L, D]; interleaved complex pairs (view_as_complex layout)."""
dt = x.dtype
B, H, L, D = x.shape
xf = x.astype(mx.float32).reshape(B, H, L, D // 2, 2)
xr, xi = xf[..., 0], xf[..., 1]
c, s = cos[None, None], sin[None, None]
out = mx.stack([xr * c - xi * s, xr * s + xi * c], axis=-1)
return out.reshape(B, H, L, D).astype(dt)
class Attention(nn.Module):
def __init__(self, dim, n_heads, qk_norm=True, eps=1e-5):
super().__init__()
self.n_heads = n_heads
self.head_dim = dim // n_heads
self.to_q = nn.Linear(dim, dim, bias=False)
self.to_k = nn.Linear(dim, dim, bias=False)
self.to_v = nn.Linear(dim, dim, bias=False)
self.to_out = [nn.Linear(dim, dim, bias=False)]
if qk_norm:
self.norm_q = RMSNorm(self.head_dim, eps)
self.norm_k = RMSNorm(self.head_dim, eps)
def __call__(self, x, mask, cos, sin):
B, L, _ = x.shape
q = self.to_q(x).reshape(B, L, self.n_heads, self.head_dim)
k = self.to_k(x).reshape(B, L, self.n_heads, self.head_dim)
v = self.to_v(x).reshape(B, L, self.n_heads, self.head_dim)
if FUSED and "norm_q" in self and kernels.supported(q, self.norm_q.weight):
q = kernels.qk_norm_rope(q, self.norm_q.weight, cos, sin, self.norm_q.eps)
k = kernels.qk_norm_rope(k, self.norm_k.weight, cos, sin, self.norm_k.eps)
o = mx.fast.scaled_dot_product_attention(q, k, v.transpose(0, 2, 1, 3), scale=self.head_dim**-0.5, mask=mask)
return self.to_out[0](o.transpose(0, 2, 1, 3).reshape(B, L, -1))
if "norm_q" in self:
q = self.norm_q(q)
k = self.norm_k(k)
q, k, v = (t.transpose(0, 2, 1, 3) for t in (q, k, v))
q = apply_rope(q, cos, sin)
k = apply_rope(k, cos, sin)
o = mx.fast.scaled_dot_product_attention(q, k, v, scale=self.head_dim**-0.5, mask=mask)
o = o.transpose(0, 2, 1, 3).reshape(B, L, -1)
return self.to_out[0](o)
class FeedForward(nn.Module):
def __init__(self, dim, hidden):
super().__init__()
self.w1 = nn.Linear(dim, hidden, bias=False)
self.w2 = nn.Linear(hidden, dim, bias=False)
self.w3 = nn.Linear(dim, hidden, bias=False)
def __call__(self, x):
return self.w2(nn.silu(self.w1(x)) * self.w3(x))
class TransformerBlock(nn.Module):
def __init__(self, dim, n_heads, norm_eps, qk_norm, modulation=True):
super().__init__()
self.attention = Attention(dim, n_heads, qk_norm)
self.feed_forward = FeedForward(dim, int(dim / 3 * 8))
self.attention_norm1 = RMSNorm(dim, norm_eps)
self.ffn_norm1 = RMSNorm(dim, norm_eps)
self.attention_norm2 = RMSNorm(dim, norm_eps)
self.ffn_norm2 = RMSNorm(dim, norm_eps)
self.modulation = modulation
if modulation:
self.adaLN_modulation = [nn.Linear(min(dim, ADALN_EMBED_DIM), 4 * dim)]
def __call__(self, x, mask, cos, sin, adaln=None):
if self.modulation:
mod = self.adaLN_modulation[0](adaln)[:, None, :]
scale_msa, gate_msa, scale_mlp, gate_mlp = mx.split(mod, 4, axis=-1)
gate_msa, gate_mlp = mx.tanh(gate_msa), mx.tanh(gate_mlp)
scale_msa, scale_mlp = 1.0 + scale_msa, 1.0 + scale_mlp
a = self.attention(self.attention_norm1(x) * scale_msa, mask, cos, sin)
x = x + gate_msa * self.attention_norm2(a)
x = x + gate_mlp * self.ffn_norm2(self.feed_forward(self.ffn_norm1(x) * scale_mlp))
else:
a = self.attention(self.attention_norm1(x), mask, cos, sin)
x = x + self.attention_norm2(a)
x = x + self.ffn_norm2(self.feed_forward(self.ffn_norm1(x)))
return x
class FinalLayer(nn.Module):
def __init__(self, dim, out_ch):
super().__init__()
self.norm_final = LayerNorm(dim, eps=1e-6, affine=False)
self.linear = nn.Linear(dim, out_ch)
self.adaLN_modulation = [nn.SiLU(), nn.Linear(min(dim, ADALN_EMBED_DIM), dim)]
def __call__(self, x, c):
scale = 1.0 + self.adaLN_modulation[1](nn.silu(c))
return self.linear(self.norm_final(x) * scale[:, None, :])
class ToClipMLP(nn.Module):
def __init__(self, in_dim, out_dim):
super().__init__()
self.fc1 = nn.Linear(in_dim, 2048)
self.layer_norm1 = LayerNorm(2048)
self.fc2 = nn.Linear(2048, out_dim)
self.layer_norm2 = LayerNorm(out_dim)
def __call__(self, x):
x = nn.relu(self.layer_norm1(self.fc1(x)))
return self.layer_norm2(self.fc2(x))
class DiT(nn.Module):
def __init__(self, cfg: dict, mlp_cfg: dict):
super().__init__()
self.cfg = cfg
dim, n_heads, eps = cfg["dim"], cfg["n_heads"], cfg["norm_eps"]
qk_norm = cfg.get("qk_norm", True)
self.patch, self.fpatch = cfg["all_patch_size"][0], cfg["all_f_patch_size"][0]
assert len(cfg["all_patch_size"]) == 1
self.in_channels = cfg["in_channels"]
self.t_scale = cfg.get("t_scale", 1000.0)
self.axes_dims = cfg["axes_dims"]
self.theta = cfg.get("rope_theta", 256.0)
self.padding_mode = cfg.get("alignment_padding_mode")
key = f"{self.patch}-{self.fpatch}"
pdim = self.fpatch * self.patch * self.patch * self.in_channels
self.all_x_embedder = {key: nn.Linear(pdim, dim)}
self.all_final_layer = {key: FinalLayer(dim, pdim)}
n_ref = cfg.get("n_refiner_layers", 2)
self.noise_refiner = [TransformerBlock(dim, n_heads, eps, qk_norm, True) for _ in range(n_ref)]
self.context_refiner = [TransformerBlock(dim, n_heads, eps, qk_norm, False) for _ in range(n_ref)]
self.t_embedder = TimestepEmbedder(min(dim, ADALN_EMBED_DIM), 1024)
cap_dim = cfg["cap_feat_dim"]
self.cap_embedder = [RMSNorm(cap_dim, eps), nn.Linear(cap_dim, dim)]
if self.padding_mode == "learned":
self.x_pad_token = mx.zeros((1, dim))
self.cap_pad_token = mx.zeros((1, dim))
self.layers = [TransformerBlock(dim, n_heads, eps, qk_norm, True) for _ in range(cfg["n_layers"])]
# condition MLP (ConditionedTransformer.mlp)
self.use_identity_mlp = mlp_cfg.get("use_identity_mlp", False)
self.text_encoder_norm = mlp_cfg.get("text_encoder_norm", False)
if not self.use_identity_mlp:
self.mlp = ToClipMLP(mlp_cfg.get("diffusion_c_input_dim", 2048), cap_dim)
self._rope_cache = {}
# ---------------------------------------------------------------- helpers
def encode_condition(self, cond):
"""cond: [B, Lc, c_in] (connector output). Returns mlp features."""
if self.text_encoder_norm:
n = mx.sqrt(mx.sum(cond.astype(mx.float32) ** 2, axis=-1, keepdims=True))
cond = (cond / mx.maximum(n, 1e-12) * 1000.0).astype(cond.dtype)
return cond if self.use_identity_mlp else self.mlp(cond)
def _layout(self, H, W, cap_len):
"""Position ids + padding exactly as patchify_and_embed (F=1)."""
key = (H, W, cap_len)
if key in self._rope_cache:
return self._rope_cache[key]
p = self.patch
cap_pad = (-cap_len) % SEQ_MULTI_OF
cap_pos = np.stack([np.arange(1, 1 + cap_len + cap_pad), np.zeros(cap_len + cap_pad), np.zeros(cap_len + cap_pad)], -1)
Ht, Wt = H // p, W // p
n_img = Ht * Wt
img_pad = (-n_img) % SEQ_MULTI_OF
f0 = cap_len + cap_pad + 1
hh, ww = np.meshgrid(np.arange(Ht), np.arange(Wt), indexing="ij")
img_pos = np.stack([np.full(n_img, f0), hh.ravel(), ww.ravel()], -1)
if img_pad:
img_pos = np.concatenate([img_pos, np.zeros((img_pad, 3))], 0)
img_pos = img_pos.astype(np.int64)
cap_pos = cap_pos.astype(np.int64)
if self.padding_mode == "zero_masked" and DROP_PAD:
# Pad rows are masked as keys in every layer and never reach the
# output, so removing them is exact -- provided the image keeps its
# padded position offset f0 (computed above). No mask => faster SDPA.
img_pos, cap_pos = img_pos[:n_img], cap_pos[:cap_len]
img_pad = cap_pad = 0
xc, xs = rope_cos_sin(img_pos, self.axes_dims, self.theta)
cc, cs = rope_cos_sin(cap_pos, self.axes_dims, self.theta)
uc, us = mx.concatenate([xc, cc], 0), mx.concatenate([xs, cs], 0)
out = dict(n_img=n_img, img_pad=img_pad, cap_pad=cap_pad, x=(xc, xs), cap=(cc, cs), uni=(uc, us))
if self.padding_mode == "zero_masked" and (img_pad or cap_pad):
# boolean key masks (True = attend); only for streams with padding
def m(valid):
return mx.array(valid)[None, None, None, :]
vx = np.r_[np.ones(n_img, bool), np.zeros(img_pad, bool)]
vc = np.r_[np.ones(cap_len, bool), np.zeros(cap_pad, bool)]
out["mask_x"] = m(vx) if img_pad else None
out["mask_cap"] = m(vc) if cap_pad else None
out["mask_uni"] = m(np.r_[vx, vc])
self._rope_cache[key] = out
return out
# ---------------------------------------------------------------- forward
def __call__(self, latents, t, cap_feats, cap_feats_2=None):
"""latents: [B, C, H, W] float32; t: [B] in [0,1] (pipeline-normalised);
cap_feats: [B, L1, cap_feat_dim] (output of encode_condition) or None;
cap_feats_2: [B, L2, dim] (proj_directvlm output) or None.
Returns raw model output [B, C, H, W] float32 (pipeline negates it)."""
B, C, H, W = latents.shape
p = self.patch
key = f"{p}-{self.fpatch}"
dtype = self.all_x_embedder[key].weight.dtype
cap_len = (0 if cap_feats is None else cap_feats.shape[1]) + (0 if cap_feats_2 is None else cap_feats_2.shape[1])
lay = self._layout(H, W, cap_len)
adaln = self.t_embedder(t * self.t_scale)
# patchify: c (h ph) (w pw) -> (h w) (ph pw c) [F = pF = 1]
x = latents.reshape(B, C, H // p, p, W // p, p).transpose(0, 2, 4, 3, 5, 1)
x = x.reshape(B, lay["n_img"], p * p * C)
if lay["img_pad"]:
x = mx.concatenate([x, mx.repeat(x[:, -1:], lay["img_pad"], axis=1)], 1)
x = self.all_x_embedder[key](x.astype(dtype))
adaln = adaln.astype(x.dtype)
if lay["img_pad"]:
pad_val = self.x_pad_token if self.padding_mode == "learned" else mx.zeros((1, x.shape[-1]), x.dtype)
x = mx.concatenate([x[:, : lay["n_img"]], mx.broadcast_to(pad_val[None], (B, lay["img_pad"], x.shape[-1])).astype(x.dtype)], 1)
mx_, mc, mu = lay.get("mask_x"), lay.get("mask_cap"), lay.get("mask_uni")
for layer in self.noise_refiner:
x = layer(x, mx_, *lay["x"], adaln)
# caption = [cap_embedder(cap_feats), cap_feats_2] + alignment pad.
# Pad rows are overwritten after embedding (zero or learned token), so
# their pre-embedding values never matter.
parts = []
if cap_feats is not None:
parts.append(self.cap_embedder[1](self.cap_embedder[0](cap_feats.astype(dtype))))
if cap_feats_2 is not None:
parts.append(cap_feats_2.astype(dtype))
c = mx.concatenate(parts, axis=1) if len(parts) > 1 else parts[0]
if lay["cap_pad"]:
pad_val = self.cap_pad_token if self.padding_mode == "learned" else mx.zeros((1, c.shape[-1]), c.dtype)
c = mx.concatenate([c, mx.broadcast_to(pad_val[None], (B, lay["cap_pad"], c.shape[-1])).astype(c.dtype)], 1)
for layer in self.context_refiner:
c = layer(c, mc, *lay["cap"])
u = mx.concatenate([x, c], axis=1)
for layer in self.layers:
u = layer(u, mu, *lay["uni"], adaln)
u = self.all_final_layer[key](u, adaln)
u = u[:, : lay["n_img"]].astype(mx.float32)
u = u.reshape(B, H // p, W // p, p, p, C).transpose(0, 5, 1, 3, 2, 4)
return u.reshape(B, C, H, W)