"""Qwen-Image VAE decoder in MLX (single-frame / text-to-image path only). Upstream decodes one latent frame at a time through causal 3D convs whose temporal padding is ``2 * pad`` zeros on the past side. For the first (and only) frame every causal conv therefore sees zeros for all but its last temporal tap, so it is exactly a 2D conv with ``weight[:, :, -1]``. The ``upsample3d`` resample stores "Rep" in its cache on the first frame and skips ``time_conv``, so it is identical to ``upsample2d``. convert.py performs the weight slicing; this module only ever sees 2D kernels (NHWC layout). """ from __future__ import annotations import mlx.core as mx import mlx.nn as nn class RMSNormC(nn.Module): """QwenImageRMS_norm: F.normalize over channels * sqrt(C) * gamma (fp32).""" def __init__(self, dim: int): super().__init__() self.gamma = mx.ones((dim,)) self.scale = dim**0.5 def __call__(self, x): dt = x.dtype xf = x.astype(mx.float32) n = mx.sqrt(mx.sum(xf * xf, axis=-1, keepdims=True)) xf = xf / mx.maximum(n, 1e-12) return xf.astype(dt) * self.scale * self.gamma.astype(dt) class Conv(nn.Module): def __init__(self, cin, cout, k, stride=1, padding=0, bias=True): super().__init__() self.weight = mx.zeros((cout, k, k, cin)) if bias: self.bias = mx.zeros((cout,)) self.stride = stride self.padding = padding def __call__(self, x): y = mx.conv2d(x, self.weight, stride=self.stride, padding=self.padding) if "bias" in self: y = y + self.bias return y class ResBlock(nn.Module): def __init__(self, cin, cout): super().__init__() self.norm1 = RMSNormC(cin) self.conv1 = Conv(cin, cout, 3, padding=1) self.norm2 = RMSNormC(cout) self.conv2 = Conv(cout, cout, 3, padding=1) self.has_shortcut = cin != cout if self.has_shortcut: self.conv_shortcut = Conv(cin, cout, 1) def __call__(self, x): h = self.conv_shortcut(x) if self.has_shortcut else x x = self.conv1(nn.silu(self.norm1(x))) x = self.conv2(nn.silu(self.norm2(x))) return x + h class AttnBlock(nn.Module): def __init__(self, dim): super().__init__() self.norm = RMSNormC(dim) self.to_qkv = Conv(dim, dim * 3, 1) self.proj = Conv(dim, dim, 1) def __call__(self, x): b, h, w, c = x.shape qkv = self.to_qkv(self.norm(x)).reshape(b, 1, h * w, 3 * c) q, k, v = mx.split(qkv, 3, axis=-1) o = mx.fast.scaled_dot_product_attention(q, k, v, scale=c**-0.5) o = o.reshape(b, h, w, c) return self.proj(o) + x class Upsample(nn.Module): """nearest-exact x2 (== pixel repeat for integer factor 2) + 3x3 conv.""" def __init__(self, dim): super().__init__() self.conv = Conv(dim, dim // 2, 3, padding=1) def __call__(self, x): b, h, w, c = x.shape x = mx.broadcast_to(x[:, :, None, :, None, :], (b, h, 2, w, 2, c)).reshape(b, 2 * h, 2 * w, c) return self.conv(x) class UpBlock(nn.Module): def __init__(self, cin, cout, num_res_blocks, upsample): super().__init__() self.resnets = [] cur = cin for _ in range(num_res_blocks + 1): self.resnets.append(ResBlock(cur, cout)) cur = cout self.upsampler = Upsample(cout) if upsample else None def __call__(self, x): for r in self.resnets: x = r(x) if self.upsampler is not None: x = self.upsampler(x) return x class Decoder(nn.Module): def __init__(self, base_dim=96, z_dim=16, dim_mult=(1, 2, 4, 4), num_res_blocks=2, out_ch=3): super().__init__() dims = [base_dim * u for u in [dim_mult[-1]] + list(dim_mult[::-1])] self.conv_in = Conv(z_dim, dims[0], 3, padding=1) self.mid_res0 = ResBlock(dims[0], dims[0]) self.mid_attn = AttnBlock(dims[0]) self.mid_res1 = ResBlock(dims[0], dims[0]) self.up_blocks = [] for i, (cin, cout) in enumerate(zip(dims[:-1], dims[1:])): if i > 0: cin = cin // 2 self.up_blocks.append(UpBlock(cin, cout, num_res_blocks, i != len(dim_mult) - 1)) self.norm_out = RMSNormC(cout) self.conv_out = Conv(cout, out_ch, 3, padding=1) def __call__(self, x): x = self.conv_in(x) x = self.mid_res1(self.mid_attn(self.mid_res0(x))) for ub in self.up_blocks: x = ub(x) mx.eval(x) # bound peak memory at 2048^2 (activations are large) return self.conv_out(nn.silu(self.norm_out(x))) class VAEDecoder(nn.Module): def __init__(self, config: dict): super().__init__() self.z_dim = config["z_dim"] self.post_quant_conv = Conv(self.z_dim, self.z_dim, 1) self.decoder = Decoder( base_dim=config["base_dim"], z_dim=self.z_dim, dim_mult=tuple(config["dim_mult"]), num_res_blocks=config["num_res_blocks"], out_ch=config.get("input_channels", 3), ) def decode(self, z_nhwc): """z: [B, H, W, C] VAE-space latents (already un-scaled). Returns [-1,1] NHWC.""" x = self.post_quant_conv(z_nhwc) return mx.clip(self.decoder(x), -1.0, 1.0)