HiDream-O1-Image-MLX / 4bit /mlx_model.py
jennyxue's picture
4bit build of HiDream-O1-Image
b29215d verified
Raw History Blame Contribute Delete
29.3 kB
"""HiDream-O1-Image (HiDream-ai, MIT) in MLX: text-to-image and instruction editing in pixel space.
The model is a Qwen3-VL-8B whose sequence ends with generation tokens: a timestep token (the `<|tms_token|>` slot,
filled with a timestep embedding) and the picture itself as 32x32x3 pixel patches (x_embedder in, final_layer2
out; no VAE). Text tokens attend causally among themselves; generation tokens attend to everything. So the text
prefix (with the Qwen3-VL vision tower's features of reference pictures, DeepStack included) is run once and its
keys / values are reused at every step: each step runs only the timestep token and the patches. The sampler is the
original's: FlowUniPCMultistepScheduler (bh2, order 2), 50 steps, shift 3, classifier-free guidance 5 against the
prompt " ", the starting noise scaled by 8 (models/pipeline.py, full model).
import mlx_model
model, processor = mlx_model.load("8bit")
img = mlx_model.generate(model, processor, "a red fox in the snow") # PIL image, 2048x2048
img = mlx_model.generate(model, processor, "make it night", ref_images=[Image.open("in.png")])
Needs `transformers` (tokenizer, chat template and Qwen3-VL image processor; the processor files sit in each folder).
"""
from __future__ import annotations
import json
import math
import os
from pathlib import Path
# The vision tower runs in float32 (see UNQUANTIZED); with MLX's default TF32 matmuls it drifts 2.5% from true float32
# over its 27 blocks. Read by MLX at the first float32 matmul, so set before any: only float32 matmuls are affected.
os.environ.setdefault("MLX_ENABLE_TF32", "0")
import mlx.core as mx
import mlx.nn as nn
import numpy as np
from mlx.utils import tree_map
GROUP = 64
PATCH = 32
TIMESTEP_TOKEN_NUM = 1
NOISE_SCALE = 8.0
T_EPS = 0.001
CONDITION_IMAGE_SIZE = 384
PREDEFINED_RESOLUTIONS = [(2048, 2048), (2304, 1728), (1728, 2304), (2560, 1440), (1440, 2560), (2496, 1664),
(1664, 2496), (3104, 1312), (1312, 3104), (2304, 1792), (1792, 2304)]
# Kept in 16-bit in every build: the pixel-space input / output layers and the timestep embedding (small, and every
# pixel goes through them), and the vision tower, which load() casts to float32: in bf16 its 27 blocks drift 12-15%
# from float32 (the original's bf16 run as much as this port's), and it runs once per reference picture.
UNQUANTIZED = ("x_embedder", "final_layer2", "t_embedder1", "visual")
def quantizable(path: str, module) -> bool:
if any(path.startswith(p) for p in UNQUANTIZED):
return False
if isinstance(module, nn.Embedding):
return True
return isinstance(module, nn.Linear) and module.weight.shape[-1] % GROUP == 0
def rotate_half(x):
h = x.shape[-1] // 2
return mx.concatenate([-x[..., h:], x[..., :h]], axis=-1)
# ------------------------------------------------------------------------------------------------ text model
class RMSNorm(nn.Module):
def __init__(self, dim, eps=1e-6):
super().__init__()
self.weight = mx.ones((dim,))
self.eps = eps
def __call__(self, x):
y = x.astype(mx.float32)
y = y * mx.rsqrt(mx.mean(y * y, axis=-1, keepdims=True) + self.eps)
return self.weight * y.astype(x.dtype)
class Attention(nn.Module):
def __init__(self, c):
super().__init__()
d, self.h, self.kv, self.hd = c["hidden_size"], c["num_attention_heads"], c["num_key_value_heads"], c["head_dim"]
self.q_proj = nn.Linear(d, self.h * self.hd, bias=False)
self.k_proj = nn.Linear(d, self.kv * self.hd, bias=False)
self.v_proj = nn.Linear(d, self.kv * self.hd, bias=False)
self.o_proj = nn.Linear(self.h * self.hd, d, bias=False)
self.q_norm = RMSNorm(self.hd, c["rms_norm_eps"])
self.k_norm = RMSNorm(self.hd, c["rms_norm_eps"])
def __call__(self, x, cos, sin, cache=None, causal=False):
b, n, _ = x.shape
q = self.q_norm(self.q_proj(x).reshape(b, n, self.h, self.hd)).transpose(0, 2, 1, 3)
k = self.k_norm(self.k_proj(x).reshape(b, n, self.kv, self.hd)).transpose(0, 2, 1, 3)
v = self.v_proj(x).reshape(b, n, self.kv, self.hd).transpose(0, 2, 1, 3)
q = q * cos + rotate_half(q) * sin
k = k * cos + rotate_half(k) * sin
kv = (k, v)
if cache is not None:
k, v = mx.concatenate([cache[0], k], axis=2), mx.concatenate([cache[1], v], axis=2)
y = mx.fast.scaled_dot_product_attention(q, k, v, scale=self.hd ** -0.5, mask="causal" if causal else None)
return self.o_proj(y.transpose(0, 2, 1, 3).reshape(b, n, -1)), kv
class MLP(nn.Module):
def __init__(self, d, f):
super().__init__()
self.gate_proj = nn.Linear(d, f, bias=False)
self.up_proj = nn.Linear(d, f, bias=False)
self.down_proj = nn.Linear(f, d, bias=False)
def __call__(self, x):
return self.down_proj(nn.silu(self.gate_proj(x)) * self.up_proj(x))
class DecoderLayer(nn.Module):
def __init__(self, c):
super().__init__()
self.self_attn = Attention(c)
self.mlp = MLP(c["hidden_size"], c["intermediate_size"])
self.input_layernorm = RMSNorm(c["hidden_size"], c["rms_norm_eps"])
self.post_attention_layernorm = RMSNorm(c["hidden_size"], c["rms_norm_eps"])
def __call__(self, x, cos, sin, cache=None, causal=False):
a, kv = self.self_attn(self.input_layernorm(x), cos, sin, cache, causal)
x = x + a
return x + self.mlp(self.post_attention_layernorm(x)), kv
class TextModel(nn.Module):
def __init__(self, c):
super().__init__()
self.embed_tokens = nn.Embedding(c["vocab_size"], c["hidden_size"])
self.layers = [DecoderLayer(c) for _ in range(c["num_hidden_layers"])]
self.norm = RMSNorm(c["hidden_size"], c["rms_norm_eps"])
def mrope_cos_sin(pos: np.ndarray, c: dict, dtype):
"""pos: (3, n) T/H/W positions -> cos, sin (n, head_dim): interleaved MRoPE (Qwen3VLTextRotaryEmbedding)."""
hd, theta = c["head_dim"], c["rope_theta"]
sec = c["rope_scaling"]["mrope_section"]
inv = 1.0 / (theta ** (np.arange(0, hd, 2, dtype=np.int64).astype(np.float32) / hd))
f = pos.astype(np.float32)[:, :, None] * inv[None, None] # (3, n, hd/2), float32 like the original
ft = f[0].copy()
for dim, off in ((1, 1), (2, 2)):
idx = slice(off, sec[dim] * 3, 3)
ft[:, idx] = f[dim][:, idx]
emb = np.concatenate([ft, ft], axis=-1)
return mx.array(np.cos(emb)).astype(dtype), mx.array(np.sin(emb)).astype(dtype)
# ------------------------------------------------------------------------------------------------ vision tower
class VisionBlock(nn.Module):
def __init__(self, v):
super().__init__()
d = v["hidden_size"]
self.heads = v["num_heads"]
self.norm1 = nn.LayerNorm(d, eps=1e-6)
self.norm2 = nn.LayerNorm(d, eps=1e-6)
self.qkv = nn.Linear(d, 3 * d)
self.proj = nn.Linear(d, d)
self.linear_fc1 = nn.Linear(d, v["intermediate_size"])
self.linear_fc2 = nn.Linear(v["intermediate_size"], d)
def __call__(self, x, cos, sin, lengths):
n, d = x.shape
hd = d // self.heads
qkv = self.qkv(self.norm1(x)).reshape(n, 3, self.heads, hd)
q, k, v = qkv[:, 0], qkv[:, 1], qkv[:, 2]
qf, kf = q.astype(mx.float32), k.astype(mx.float32)
q = (qf * cos[:, None] + rotate_half(qf) * sin[:, None]).astype(x.dtype)
k = (kf * cos[:, None] + rotate_half(kf) * sin[:, None]).astype(x.dtype)
outs, s = [], 0
for L in lengths: # attention within each picture (cu_seqlens)
qi, ki, vi = (t[s:s + L].transpose(1, 0, 2)[None] for t in (q, k, v))
outs.append(mx.fast.scaled_dot_product_attention(qi, ki, vi, scale=hd ** -0.5)[0].transpose(1, 0, 2))
s += L
x = x + self.proj(mx.concatenate(outs, axis=0).reshape(n, d))
return x + self.linear_fc2(nn.gelu_approx(self.linear_fc1(self.norm2(x))))
class Merger(nn.Module):
def __init__(self, v, postshuffle):
super().__init__()
m = v["spatial_merge_size"] ** 2
self.width = v["hidden_size"] * m
self.postshuffle = postshuffle
self.norm = nn.LayerNorm(self.width if postshuffle else v["hidden_size"], eps=1e-6)
self.linear_fc1 = nn.Linear(self.width, self.width)
self.linear_fc2 = nn.Linear(self.width, v["out_hidden_size"])
def __call__(self, x):
x = self.norm(x.reshape(-1, self.width)) if self.postshuffle else self.norm(x).reshape(-1, self.width)
return self.linear_fc2(nn.gelu(self.linear_fc1(x)))
class VisionModel(nn.Module):
def __init__(self, v):
super().__init__()
self.v = v
p, t = v["patch_size"], v["temporal_patch_size"]
self.patch_embed = nn.Linear(v["in_channels"] * t * p * p, v["hidden_size"]) # the Conv3d, flattened
self.pos_embed = nn.Embedding(v["num_position_embeddings"], v["hidden_size"])
self.blocks = [VisionBlock(v) for _ in range(v["depth"])]
self.merger = Merger(v, False)
self.deepstack_merger_list = [Merger(v, True) for _ in v["deepstack_visual_indexes"]]
def _pos(self, grid):
side, m = int(self.v["num_position_embeddings"] ** 0.5), self.v["spatial_merge_size"]
idx, wts = [[] for _ in range(4)], [[] for _ in range(4)]
for t, h, w in grid:
hi = np.linspace(0, side - 1, h, dtype=np.float32)
wi = np.linspace(0, side - 1, w, dtype=np.float32)
hf, wf = hi.astype(np.int64), wi.astype(np.int64)
hc, wc = np.minimum(hf + 1, side - 1), np.minimum(wf + 1, side - 1)
dh, dw = hi - hf, wi - wf
for j, (a, b, wa, wb) in enumerate([(hf, wf, 1 - dh, 1 - dw), (hf, wc, 1 - dh, dw),
(hc, wf, dh, 1 - dw), (hc, wc, dh, dw)]):
ii = (a[:, None] * side + b[None]).reshape(-1)
ww = (wa[:, None] * wb[None]).reshape(-1)
order = np.arange(h * w).reshape(h // m, m, w // m, m).transpose(0, 2, 1, 3).reshape(-1)
idx[j].append(np.tile(ii[order], t))
wts[j].append(np.tile(ww[order], t))
dt = self.pos_embed.weight.dtype
out = 0
for j in range(4):
e = self.pos_embed(mx.array(np.concatenate(idx[j])))
out = out + e * mx.array(np.concatenate(wts[j]))[:, None].astype(dt)
return out
def _rope(self, grid):
hd = self.v["hidden_size"] // self.v["num_heads"]
dim = hd // 2
inv = 1.0 / (10000.0 ** (np.arange(0, dim, 2, dtype=np.float32) / dim))
m = self.v["spatial_merge_size"]
coords = []
for t, h, w in grid:
r = (np.arange(h // m)[:, None, None, None] * m + np.arange(m)[None, None, :, None])
c = (np.arange(w // m)[None, :, None, None] * m + np.arange(m)[None, None, None, :])
r = np.broadcast_to(r, (h // m, w // m, m, m)).reshape(-1)
c = np.broadcast_to(c, (h // m, w // m, m, m)).reshape(-1)
coords.append(np.tile(np.stack([r, c], -1), (t, 1)))
coords = np.concatenate(coords)
f = np.concatenate([coords[:, :1] * inv[None], coords[:, 1:] * inv[None]], axis=-1).astype(np.float32)
emb = np.concatenate([f, f], axis=-1)
return mx.array(np.cos(emb)), mx.array(np.sin(emb))
def __call__(self, pixels, grid):
"""pixels: (N, 1536) from the Qwen3-VL image processor, grid: [(t, h, w)] -> (merged tokens, deepstack)."""
if self.patch_embed.weight.dtype != mx.float32: # float32 from the first use on (UNQUANTIZED)
self.update(tree_map(lambda a: a.astype(mx.float32), self.parameters()))
x = self.patch_embed(pixels.astype(self.patch_embed.weight.dtype)) + self._pos(grid)
cos, sin = self._rope(grid)
lengths = [t * h * w for t, h, w in grid]
ds = []
for i, blk in enumerate(self.blocks):
x = blk(x, cos, sin, lengths)
if i in self.v["deepstack_visual_indexes"]:
ds.append(self.deepstack_merger_list[self.v["deepstack_visual_indexes"].index(i)](x))
return self.merger(x), ds
# ------------------------------------------------------------------------------------------------ the generator
class TimestepEmbedder(nn.Module):
def __init__(self, d, freq=256):
super().__init__()
self.freq = freq
self.fc1 = nn.Linear(freq, d)
self.fc2 = nn.Linear(d, d)
def __call__(self, t):
half = self.freq // 2
freqs = mx.exp(-math.log(10000) * mx.arange(half, dtype=mx.float32) / half)
a = (t.astype(mx.float32) * 1000)[:, None] * freqs[None]
e = mx.concatenate([mx.cos(a), mx.sin(a)], axis=-1).astype(self.fc1.weight.dtype)
return self.fc2(nn.silu(self.fc1(e)))
class Model(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
c, v = config["text_config"], config["vision_config"]
d = c["hidden_size"]
self.visual = VisionModel(v)
self.language_model = TextModel(c)
self.t_embedder1 = TimestepEmbedder(d)
self.x_embedder_proj1 = nn.Linear(PATCH * PATCH * 3, d // 4, bias=False)
self.x_embedder_proj2 = nn.Linear(d // 4, d)
self.final_layer2 = nn.Linear(d, PATCH * PATCH * 3)
def prefix(self, ids, pos, image_embeds=None, deepstack=None):
"""The causal text part (everything before the timestep token) -> per-layer keys / values."""
lm, c = self.language_model, self.config["text_config"]
x = lm.embed_tokens(mx.array(np.asarray(ids, dtype=np.int32))[None])
vis = np.nonzero(np.asarray(ids) == self.config["image_token_id"])[0]
if image_embeds is not None:
x[:, mx.array(vis)] = image_embeds.astype(x.dtype)[None]
cos, sin = mrope_cos_sin(pos, c, x.dtype)
caches = []
for i, layer in enumerate(lm.layers):
x, kv = layer(x, cos, sin, causal=True)
caches.append(kv)
if deepstack is not None and i < len(deepstack):
x[:, mx.array(vis)] = x[:, mx.array(vis)] + deepstack[i].astype(x.dtype)[None]
mx.eval(x, kv)
return caches
def step(self, caches, pos, t, patches):
"""One pass of the generation tokens: [timestep token] + pixel patches (target, then references) ->
predicted clean patches for every patch token, float32."""
lm, c = self.language_model, self.config["text_config"]
dt = self.x_embedder_proj2.weight.dtype
te = self.t_embedder1(mx.array([t], dtype=mx.float32))[:, None]
pe = self.x_embedder_proj2(self.x_embedder_proj1(patches.astype(dt)))
x = mx.concatenate([te.astype(dt), pe], axis=1)
cos, sin = mrope_cos_sin(pos, c, dt)
for layer, kv in zip(lm.layers, caches):
x, _ = layer(x, cos, sin, cache=kv)
return self.final_layer2(lm.norm(x[:, 1:])).astype(mx.float32)
def load(folder):
"""-> (model, processor)."""
from transformers import AutoProcessor
folder = Path(folder)
config = json.loads((folder / "config.json").read_text())
model = Model(config)
q = config.get("quantization")
if q:
nn.quantize(model, group_size=q["group_size"], bits=q["bits"], class_predicate=quantizable)
model.load_weights(str(folder / "model.safetensors"), strict=True)
mx.eval(model.parameters())
return model, AutoProcessor.from_pretrained(str(folder))
# ------------------------------------------------------------------------------------------------ positions
def rope_index(spatial_merge_size, image_token_id, video_token_id, vision_start_token_id, input_ids, image_grid_thw,
skip_vision_start_token, fix_point=4096):
"""models/utils.py get_rope_index_fix_point for one sequence (numpy) -> (3, n) positions."""
ids = list(int(i) for i in input_ids)
arr = np.asarray(ids)
starts = np.nonzero(arr == vision_start_token_id)[0]
image_nums = int(np.sum(arr[starts + 1] == image_token_id))
out, st, image_index = [], 0, 0
for _ in range(image_nums):
ed = ids.index(image_token_id, st)
t, h, w = (int(x) for x in image_grid_thw[image_index])
image_index += 1
gt, gh, gw = t, h // spatial_merge_size, w // spatial_merge_size
text_len = max(0, ed - st - skip_vision_start_token[image_index - 1])
st_idx = out[-1].max() + 1 if out else 0
out.append(np.broadcast_to(np.arange(text_len)[None], (3, text_len)) + st_idx)
ti = np.repeat(np.arange(gt), gh * gw)
hi = np.tile(np.repeat(np.arange(gh), gw), gt)
wi = np.tile(np.arange(gw), gt * gh)
grid = np.stack([ti, hi, wi])
if skip_vision_start_token[image_index - 1]:
if fix_point > 0:
fix_point = fix_point - st_idx
out.append(grid + fix_point + st_idx)
fix_point = 0
else:
out.append(grid + text_len + st_idx)
st = ed + gt * gh * gw
if st < len(ids):
st_idx = out[-1].max() + 1 if out else 0
n = len(ids) - st
out.append(np.broadcast_to(np.arange(n)[None], (3, n)) + st_idx)
return np.concatenate(out, axis=1)
# ------------------------------------------------------------------------------------------------ sampler
class UniPC:
"""FlowUniPCMultistepScheduler (models/fm_solvers_unipc.py) with the pipeline's settings: solver_order 2,
flow_prediction, predict_x0, bh2, lower_order_final, final sigma 0. numpy float32."""
def __init__(self, steps, shift):
alphas = np.linspace(1, 1 / 1000, 1000)[::-1].copy()
s = (1.0 - alphas).astype(np.float32)
s = shift * s / (1 + (shift - 1) * s)
smax, smin = float(s[0]), float(s[-1])
sig = np.linspace(smax, smin, steps + 1).copy()[:-1]
sig = shift * sig / (1 + (shift - 1) * sig)
self.timesteps = (sig * 1000).astype(np.int64)
self.sigmas = np.concatenate([sig, [0]]).astype(np.float32)
self.n = len(self.timesteps)
self.outputs, self.lower, self.last, self.i, self.order = [None, None], 0, None, 0, 1
def _lam(self, s):
s = np.float32(s)
return np.log(np.float32(1) - s) - np.log(s)
def _coeffs(self, h, order, rks):
hh = -h
h_phi_1 = np.expm1(hh)
h_phi_k = h_phi_1 / hh - 1
B_h = np.expm1(hh)
R, b, fact = [], [], 1
for i in range(1, order + 1):
R.append(np.power(rks, i - 1))
b.append(h_phi_k * fact / B_h)
fact *= i + 1
h_phi_k = h_phi_k / hh - 1 / fact
return h_phi_1, B_h, np.stack(R).astype(np.float32), np.array(b, np.float32)
def step(self, model_output, sample):
sig = self.sigmas
x0 = sample - sig[self.i] * model_output
if self.i > 0 and self.last is not None: # UniC corrector
m0, x = self.outputs[-1], self.last
st, s0 = sig[self.i], sig[self.i - 1]
h = self._lam(st) - self._lam(s0)
rks, D1s = [], []
for k in range(1, self.order):
rk = (self._lam(sig[self.i - (k + 1)]) - self._lam(s0)) / h
rks.append(rk); D1s.append((self.outputs[-(k + 1)] - m0) / rk)
rks.append(1.0)
h_phi_1, B_h, R, b = self._coeffs(h, self.order, np.array(rks, np.float32))
rhos = np.array([0.5], np.float32) if self.order == 1 else np.linalg.solve(R, b).astype(np.float32)
xt_ = st / s0 * x - (1 - st) * h_phi_1 * m0
corr = sum(r * d for r, d in zip(rhos[:-1], D1s)) if D1s else 0
sample = (xt_ - (1 - st) * B_h * (corr + rhos[-1] * (x0 - m0))).astype(np.float32)
self.outputs = [self.outputs[1], x0]
order = min(2, self.n - self.i)
self.order = min(order, self.lower + 1)
self.last = sample
m0 = self.outputs[-1] # UniP predictor
st, s0 = sig[self.i + 1], sig[self.i]
if st == 0:
prev = m0.copy() # the original's limit at sigma 0: h = inf, h_phi_1 = B_h = -1, order 1
else:
h = self._lam(st) - self._lam(s0)
rks, D1s = [], []
for k in range(1, self.order):
rk = (self._lam(sig[self.i - k]) - self._lam(s0)) / h
rks.append(rk); D1s.append((self.outputs[-(k + 1)] - m0) / rk)
rks.append(1.0)
h_phi_1, B_h, R, b = self._coeffs(h, self.order, np.array(rks, np.float32))
xt_ = st / s0 * sample - (1 - st) * h_phi_1 * m0
pred = 0.5 * D1s[0] if D1s else 0
prev = xt_ - (1 - st) * B_h * pred
self.lower = min(self.lower + 1, 2)
self.i += 1
return prev.astype(np.float32)
# ------------------------------------------------------------------------------------------------ pipeline
def _bf16(x: np.ndarray) -> np.ndarray:
return np.array(mx.array(x).astype(mx.bfloat16).astype(mx.float32))
def to_patches(img: np.ndarray) -> np.ndarray:
"""(H, W, 3) float in [-1, 1] -> (H/32 * W/32, 3*32*32) in the original's (C p1 p2) order."""
h, w, _ = img.shape
x = img.reshape(h // PATCH, PATCH, w // PATCH, PATCH, 3).transpose(0, 2, 4, 1, 3)
return x.reshape(-1, 3 * PATCH * PATCH)
def from_patches(x: np.ndarray, h: int, w: int) -> np.ndarray:
x = x.reshape(h // PATCH, w // PATCH, 3, PATCH, PATCH).transpose(0, 3, 1, 4, 2)
return x.reshape(h, w, 3)
def resize_pilimage(pil, image_size, patch_size=16):
from PIL import Image
while min(*pil.size) >= 2 * image_size:
pil = pil.resize(tuple(x // 2 for x in pil.size), resample=Image.BOX)
m, (width, height) = patch_size, pil.size
S_max = image_size * image_size
scale = math.sqrt(S_max / (width * height))
sizes = sorted([(round(width * scale) // m * m, round(height * scale) // m * m),
(round(width * scale) // m * m, math.floor(height * scale) // m * m),
(math.floor(width * scale) // m * m, round(height * scale) // m * m),
(math.floor(width * scale) // m * m, math.floor(height * scale) // m * m)],
key=lambda x: x[0] * x[1], reverse=True)
for new in sizes:
if new[0] * new[1] <= S_max:
break
s1, s2 = width / new[0], height / new[1]
if s1 < s2:
pil = pil.resize([new[0], round(height / s1)], resample=Image.BICUBIC)
top = (round(height / s1) - new[1]) // 2
return pil.crop((0, top, new[0], top + new[1]))
pil = pil.resize([round(width / s2), new[1]], resample=Image.BICUBIC)
left = (round(width / s2) - new[0]) // 2
return pil.crop((left, 0, left + new[0], new[1]))
def _samples(model, processor, prompt, refs, height, width, guidance):
"""The pipeline's cond / uncond samples: (prefix ids, prefix positions, generation positions, vision inputs)."""
from PIL import Image
cfg = model.config
tok = processor.tokenizer
img_id, vid_id, vs_id = cfg["image_token_id"], cfg["video_token_id"], cfg["vision_start_token_id"]
tgt_len = (height // PATCH) * (width // PATCH)
tail = "<|boi_token|>" + "<|tms_token|>" * TIMESTEP_TOKEN_NUM
captions = [prompt] + ([" "] if guidance > 1.0 else [])
out, ref_patches, vlm = [], None, None
if refs:
K = len(refs)
mx_ = max(height, width)
max_size = (mx_ if K == 1 else mx_ * 48 // 64 if K == 2 else mx_ // 2 if K <= 4 else mx_ * 24 // 64 if K <= 8
else mx_ // 4)
rs = [resize_pilimage(p.convert("RGB"), max_size, PATCH) for p in refs]
ref_patches = np.concatenate([to_patches(np.asarray(r, np.float32) / 255 * 2 - 1) for r in rs])
ref_lens = [(r.height // PATCH) * (r.width // PATCH) for r in rs]
cs = CONDITION_IMAGE_SIZE if K <= 4 else CONDITION_IMAGE_SIZE * 48 // 64 if K <= 8 else CONDITION_IMAGE_SIZE // 2
vlm = []
for r in rs:
wq = math.sqrt(cs * cs * r.width / r.height); hq = wq / (r.width / r.height)
vlm.append(r.resize((int(wq / 32) * 32, int(hq / 32) * 32), resample=Image.LANCZOS))
tgt_grid = [[1, height // PATCH, width // PATCH]]
ref_grid = [[1, r.height // PATCH, r.width // PATCH] for r in rs]
for cap in captions:
if not refs:
text = processor.apply_chat_template([{"role": "user", "content": cap}], tokenize=False,
add_generation_prompt=True) + tail
ids = tok.encode(text, add_special_tokens=False)
pad = ids + [vs_id] + [img_id] * (tgt_len - 1)
pos = rope_index(1, img_id, vid_id, vs_id, pad, [[1, height // PATCH, width // PATCH]], [1])
vision = None
else:
content = [{"type": "image"} for _ in refs] + [{"type": "text", "text": cap}]
text = processor.apply_chat_template([{"role": "user", "content": content}], tokenize=False,
add_generation_prompt=True)
proc = processor(text=[text], images=vlm, padding="longest", return_tensors="np")
ids = list(proc["input_ids"][0]) + tok.encode(tail, add_special_tokens=False)
g = np.array(proc["image_grid_thw"]).copy()
gcond = g.copy(); gcond[:, 1:] //= cfg["vision_config"]["spatial_merge_size"]
pad = list(ids)
for L in [tgt_len] + ref_lens:
pad += [vs_id] + [img_id] * (L - 1)
pos = rope_index(1, img_id, vid_id, vs_id, pad, list(gcond) + tgt_grid + ref_grid,
[0] * len(refs) + [1] + [1] * len(refs))
vision = (np.array(proc["pixel_values"], np.float32), [tuple(int(v) for v in r) for r in g])
n = len(ids) - TIMESTEP_TOKEN_NUM
out.append((ids[:n], pos[:, :n], pos[:, n:], vision))
return out, ref_patches, tgt_len
def generate(model, processor, prompt: str, ref_images=(), width: int = 2048, height: int = 2048, steps: int = 50,
guidance: float = 5.0, shift: float = 3.0, seed: int = 32, noise_scale: float = NOISE_SCALE,
noise: np.ndarray | None = None, snap: bool = True, callback=None):
"""-> PIL image. `noise`: (height, width, 3) standard normal to fix the start (default: MLX's, from `seed`).
`snap` keeps the original's resolution snapping (to its 2048-class sizes) for text-to-image."""
from PIL import Image
if snap and not ref_images:
width, height = min(PREDEFINED_RESOLUTIONS, key=lambda r: abs(r[0] / r[1] - width / height))
width, height = width // PATCH * PATCH, height // PATCH * PATCH
samples, ref_patches, tgt_len = _samples(model, processor, prompt, list(ref_images), height, width, guidance)
caches, gen_pos = [], []
for ids, ppos, gpos, vision in samples:
emb = ds = None
if vision is not None:
emb, ds = model.visual(mx.array(vision[0]), vision[1])
caches.append(model.prefix(ids, ppos, emb, ds))
gen_pos.append(gpos)
if noise is None:
noise = np.array(mx.random.normal((height, width, 3), key=mx.random.key(seed + 1)))
z = _bf16(to_patches(noise_scale * noise.astype(np.float32)))
refp = None if ref_patches is None else mx.array(ref_patches).astype(mx.bfloat16)
sched = UniPC(steps, shift)
for k, step_t in enumerate(sched.timesteps):
t = 1.0 - float(step_t) / 1000.0
sigma = max(np.float32(step_t) / np.float32(1000.0), np.float32(T_EPS))
zin = mx.array(z)[None].astype(mx.bfloat16)
if refp is not None:
zin = mx.concatenate([zin, refp[None]], axis=1)
vs = []
for cache, gpos in zip(caches, gen_pos):
xp = model.step(cache, gpos, t, zin)[0, :tgt_len]
vs.append((np.array(xp) - z) / sigma)
v = vs[0] if len(vs) == 1 else vs[1] + guidance * (vs[0] - vs[1])
z = _bf16(sched.step(-v, z))
if callback is not None:
callback(k, sched.n)
img = from_patches((z + 1) / 2, height, width)
return Image.fromarray(np.round(np.clip(img * 255, 0, 255)).astype(np.uint8))
# ------------------------------------------------------------------------------------------------ conversion
def rename(k: str) -> str | None:
"""Hub name -> this file's name (None: not used)."""
if k == "lm_head.weight":
return None
k = k.removeprefix("model.")
k = k.replace("visual.blocks.", "visual.blocks.").replace(".attn.qkv.", ".qkv.").replace(".attn.proj.", ".proj.")
k = k.replace(".mlp.linear_fc1.", ".linear_fc1.").replace(".mlp.linear_fc2.", ".linear_fc2.")
k = k.replace("visual.patch_embed.proj.", "visual.patch_embed.")
k = k.replace("t_embedder1.mlp.0.", "t_embedder1.fc1.").replace("t_embedder1.mlp.2.", "t_embedder1.fc2.")
k = k.replace("x_embedder.proj1.", "x_embedder_proj1.").replace("x_embedder.proj2.", "x_embedder_proj2.")
k = k.replace("final_layer2.linear.", "final_layer2.")
return k