Skip to content

armgit / kokon

Public Imported from GitHub
0

Edit photos by describing the change, on your own GPU. A free, open-source alternative to Nano Banana and ChatGPT image editing: photos stay on your computer, no daily limit. One installer for Windows, Mac and Linux sets up the best open model (Qwen-Image 2.1). MCP server for AI agents.

Mac engine: the Qwen-Image 2.1 VAE decoder

Gabriele Lozupone1ad504c8b4ac
diff --git a/engine-mac/README.md b/engine-mac/README.md
index a01585c..04b26a0 100644
--- a/engine-mac/README.md
+++ b/engine-mac/README.md
@@ -25,6 +25,9 @@ swift test # no model needed
| `Probe.swift` | GPU (MPS), AMX (Accelerate) and Neural Engine (Core ML) on Qwen's product shapes, alone and together |
| `QwenSequence.swift` | the joint text/image sequence, block-causal segments and RoPE positions |
| `QwenDiT.swift`, `Kernels/dit.metal`, `Attention.swift`, `Arena.swift` | the DiT: modulation on the CPU, everything per token on the GPU |
+| `Coexecution.swift`, `Kernels/ane.metal` | the AMX and the Neural Engine beside the GPU on the DiT's products |
+| `Kernels/attention.metal` | fused block-causal attention |
+| `QwenVAE.swift`, `Safetensors.swift` | the VAE decoder as one MPSGraph, from Kokon's VAE file (Wan 2.2 names) |
Tests check the CPU and GPU unpacking against gguf-py's values (`tools/make_quant_fixtures.py` writes the
fixture), and the sequence layout against diffusers' rules worked out by hand.
@@ -72,5 +75,8 @@ most tools do, deviates by roughly 1e-2.
mask): 4.5 s per 1024² evaluation against MPSGraph's 4.1 s, but without MPSGraph's score matrix (2.2 GB at 1 MP,
~34 GB at 4 MP). `KOKON_ATTENTION=graph` keeps MPSGraph for comparison. The other units are idle during it: next.
+**VAE decoder** (`check-vae`, against `tools/reference_vae.py`, diffusers fp32): within 1.1e-5; 1024² in 3.1 s
+(plus ~6 s to build its graph the first time).
+
Credits: the Neural Engine program technique and the GPU + AMX + Neural Engine split come from
[Siliconed](https://github.com/gwenn-ha-dev/Siliconed) (Apache-2.0), written again here.
diff --git a/engine-mac/Sources/KokonEngine/Checks.swift b/engine-mac/Sources/KokonEngine/Checks.swift
index 62fca2c..2677bbd 100644
--- a/engine-mac/Sources/KokonEngine/Checks.swift
+++ b/engine-mac/Sources/KokonEngine/Checks.swift
@@ -179,3 +179,30 @@ extension Checks {
print(String(format: "Neural Engine on GPU-written surfaces: max |Δ| %.4g of max |y| %.4g (fp16 output)", worst, scale))
}
}
+
+extension Checks {
+ /// The VAE decoder against `tools/reference_vae.py`, then its time at `grid` (64 = 1024²).
+ public static func vae(path: String, reference directory: String, timeGrid: Int?) throws {
+ let meta = try JSONSerialization.jsonObject(with: Data(contentsOf: URL(fileURLWithPath: directory)
+ .appendingPathComponent("meta.json"))) as! [String: Any]
+ let grid = meta["grid"] as! Int
+ let context = try MetalContext()
+ let vae = try QwenVAE(path: path, context: context)
+ let latent = try reference(directory, "latent"), want = try reference(directory, "image")
+ var started = DispatchTime.now().uptimeNanoseconds
+ let got = try vae.decode(latent, height: grid, width: grid)
+ let first = Double(DispatchTime.now().uptimeNanoseconds - started) * 1e-9
+ let r = got.withUnsafeBufferPointer { compare($0.baseAddress!, want) }
+ print(String(format: "VAE %d² → %d²: rel %.2e, max |Δ| %.3g%@ (%.2f s with the graph build)", grid, grid * 16,
+ r.relative, r.maxAbs, r.finite ? "" : " NON-FINITE", first))
+ if let t = timeGrid {
+ let random = (0..<(64 * t * t)).map { Float(($0 * 7919) % 1000) / 500 - 1 }
+ for run in 0..<2 {
+ started = DispatchTime.now().uptimeNanoseconds
+ _ = try vae.decode(random, height: t, width: t)
+ print(String(format: "decode %d² (run %d): %.2f s", t * 16, run + 1,
+ Double(DispatchTime.now().uptimeNanoseconds - started) * 1e-9))
+ }
+ }
+ }
+}
diff --git a/engine-mac/Sources/KokonEngine/QwenVAE.swift b/engine-mac/Sources/KokonEngine/QwenVAE.swift
new file mode 100644
index 0000000..22e97fd
--- /dev/null
+++ b/engine-mac/Sources/KokonEngine/QwenVAE.swift
@@ -0,0 +1,162 @@
+import Foundation
+import Metal
+import MetalPerformanceShaders
+import MetalPerformanceShadersGraph
+
+/// **The Qwen-Image 2.1 VAE decoder** (`AutoencoderKLQwenImage21.decode`, diffusers 0.42), as one MPSGraph per
+/// latent size, fp32. For a single image every causal 3D convolution of the Wan 2.2 design is a 2D one and the
+/// temporal convolutions never run (first chunk), so the graph is a plain 2D network:
+///
+/// latent · std + mean ─ post_quant_conv (1×1) ─ conv_in (3×3, 64 → 1152)
+/// mid: residual ─ single-head attention over all pixels ─ residual
+/// 5 up blocks (1152, 1152, 1152 → 576, 576 → 288, 288 → 144): 3 residual blocks, then (the first four)
+/// nearest 2× + conv 3×3, plus the block input duplicated into the new pixels (DupUp3D)
+/// RMS norm ─ SiLU ─ conv_out (3×3, 144 → 4: RGBA) ─ clamp [−1, 1]
+///
+/// residual block: x + conv2(SiLU(norm2(conv1(SiLU(norm1(x)))))), the skip through a 1×1 conv when widths differ.
+/// norm: F.normalize over channels × √C × γ. Weights are read by their Wan 2.2 names (Kokon's file); diffusers'
+/// names in the comments (`tools/reference_vae.py` maps between them).
+public final class QwenVAE {
+ public static let latentChannels = 64
+ static let latentsMean: [Float] = [0.5126, 0.7721, -0.0631, 1.3506, -0.7855, -2.1025, -0.3458, 1.3722, 1.8873, -1.7177,
+ -0.651, 0.2732, 0.7562, -0.6163, -1.0277, 3.8363, 2.021, 0.0472, 0.932, 2.0087, 2.4954, -0.1391, -1.4249, 1.8464,
+ -0.5236, 1.2826, 3.7046, -1.3035, 2.7286, -1.4518, -1.9036, -1.9955, -0.0342, -1.0265, -0.7636, 3.0555, 0.0746,
+ -3.0751, -0.1076, 1.7376, -1.0914, -1.9435, -0.2784, -1.368, 0.4809, -0.4433, 0.3764, 0.5729, -2.0595, 1.096,
+ -1.326, -2.0211, -5.0179, 0.5275, 4.0162, 1.8505, 0.3026, 1.9373, 1.4937, 0.2632, 0.5547, -1.7121, -0.1562, 0.0304]
+ static let latentsStd: [Float] = [3.2001, 3.2936, 3.4321, 3.0091, 3.1061, 4.0379, 4.0705, 3.791, 3.0785, 3.65, 3.9308,
+ 3.0904, 2.8778, 3.7675, 3.732, 5.0756, 3.2864, 4.0397, 3.1317, 4.0443, 2.9249, 3.9454, 3.0988, 4.2489, 3.4896,
+ 3.8513, 3.9323, 3.4719, 3.7498, 4.283, 3.5694, 4.2467, 3.9037, 3.2947, 5.077, 3.5075, 3.27, 3.4767, 2.8063, 5.1125,
+ 3.5327, 4.7833, 3.1286, 4.1819, 3.8527, 3.8312, 3.5605, 4.3875, 3.9624, 4.0168, 3.5643, 4.055, 5.5614, 4.2963,
+ 4.408, 3.4959, 3.8747, 3.7608, 3.5735, 3.149, 3.7662, 3.6746, 3.4563, 3.8161]
+ /// Channels per up block (diffusers' `dims`: base 144 × dim_mult [1, 2, 4, 8, 8] reversed, the first repeated).
+ static let dims = [1152, 1152, 1152, 576, 288, 144]
+ /// Temporal factor of each up block's DupUp3D shortcut (`temperal_upsample`); the last block does not upsample.
+ static let temporal = [2, 2, 2, 1]
+
+ let context: MetalContext
+ let file: SafetensorsFile
+ private var graphs: [String: (graph: MPSGraph, input: MPSGraphTensor, output: MPSGraphTensor)] = [:]
+
+ public init(path: String, context: MetalContext) throws {
+ file = try SafetensorsFile(path: path)
+ self.context = context
+ guard file.tensors["decoder.conv1.weight"] != nil, file.tensors["conv2.weight"] != nil else {
+ throw GGUFFile.Failure.unsupported("\(path): not a Qwen-Image 2.1 VAE (Wan 2.2 names expected)")
+ }
+ }
+
+ /// Decodes a normalized latent `[64, h, w]` (the DiT's packed tokens transposed) into RGBA `[4, 16h, 16w]` in
+ /// [−1, 1].
+ public func decode(_ latent: [Float], height h: Int, width w: Int) throws -> [Float] {
+ let key = "\(h)×\(w)"
+ let built = try graphs[key] ?? build(height: h, width: w)
+ graphs[key] = built
+ let input = MPSGraphTensorData(device: MPSGraphDevice(mtlDevice: context.device),
+ data: latent.withUnsafeBytes { Data($0) },
+ shape: [1, 64, NSNumber(value: h), NSNumber(value: w)], dataType: .float32)
+ let result = built.graph.run(with: context.queue, feeds: [built.input: input], targetTensors: [built.output],
+ targetOperations: nil)
+ guard let data = result[built.output] else { throw MetalContext.Failure.kernel("VAE decode") }
+ var out = [Float](repeating: 0, count: 4 * 16 * h * 16 * w)
+ out.withUnsafeMutableBytes { data.mpsndarray().readBytes($0.baseAddress!, strideBytes: nil) }
+ return out
+ }
+
+ // MARK: - the graph
+
+ private func build(height h: Int, width w: Int) throws -> (graph: MPSGraph, input: MPSGraphTensor, output: MPSGraphTensor) {
+ let g = MPSGraph()
+ func n(_ values: [Int]) -> [NSNumber] { values.map { NSNumber(value: $0) } }
+ func constant(_ values: [Float], _ shape: [Int]) -> MPSGraphTensor {
+ g.constant(values.withUnsafeBytes { Data($0) }, shape: n(shape), dataType: .float32)
+ }
+ func weight(_ name: String, _ shape: [Int]) throws -> MPSGraphTensor {
+ let values = try file.floats(name)
+ guard values.count == shape.reduce(1, *) else {
+ throw GGUFFile.Failure.unsupported("\(name): \(values.count) values, \(shape) expected")
+ }
+ return constant(values, shape)
+ }
+ /// Conv (OIHW weights, the file's 5D `[O, I, 1, k, k]` squeezed) + bias, padding k / 2.
+ func conv(_ x: MPSGraphTensor, _ name: String, _ inC: Int, _ outC: Int, _ k: Int) throws -> MPSGraphTensor {
+ let pad = k / 2
+ let d = MPSGraphConvolution2DOpDescriptor(strideInX: 1, strideInY: 1, dilationRateInX: 1, dilationRateInY: 1,
+ groups: 1, paddingLeft: pad, paddingRight: pad, paddingTop: pad,
+ paddingBottom: pad, paddingStyle: .explicit, dataLayout: .NCHW,
+ weightsLayout: .OIHW)!
+ let y = g.convolution2D(x, weights: try weight(name + ".weight", [outC, inC, k, k]), descriptor: d, name: nil)
+ return g.addition(y, try weight(name + ".bias", [1, outC, 1, 1]), name: nil)
+ }
+ /// QwenImage21RMS_norm: F.normalize over channels (x / max(‖x‖, 1e-12)) · √C · γ.
+ func norm(_ x: MPSGraphTensor, _ name: String, _ c: Int) throws -> MPSGraphTensor {
+ let length = g.squareRoot(with: g.reductionSum(with: g.square(with: x, name: nil), axes: [1], name: nil), name: nil)
+ let normalized = g.division(x, g.maximum(length, g.constant(1e-12, dataType: .float32), name: nil), name: nil)
+ let scaled = g.multiplication(normalized, g.constant(Double(Float(c).squareRoot()), dataType: .float32), name: nil)
+ return g.multiplication(scaled, try weight(name, [1, c, 1, 1]), name: nil)
+ }
+ func silu(_ x: MPSGraphTensor) -> MPSGraphTensor { g.multiplication(x, g.sigmoid(with: x, name: nil), name: nil) }
+ /// QwenImage21ResidualBlock (Wan `residual.{0,2,3,6}`, `shortcut`).
+ func residual(_ x: MPSGraphTensor, _ name: String, _ inC: Int, _ outC: Int) throws -> MPSGraphTensor {
+ let skip = inC == outC ? x : try conv(x, name + ".shortcut", inC, outC, 1)
+ var y = silu(try norm(x, name + ".residual.0.gamma", inC))
+ y = try conv(y, name + ".residual.2", inC, outC, 3)
+ y = silu(try norm(y, name + ".residual.3.gamma", outC))
+ y = try conv(y, name + ".residual.6", outC, outC, 3)
+ return g.addition(y, skip, name: nil)
+ }
+ /// QwenImage21AttentionBlock: one head over all `hw` pixels.
+ func attention(_ x: MPSGraphTensor, _ name: String, _ c: Int, _ hw: Int, _ hh: Int, _ ww: Int) throws -> MPSGraphTensor {
+ let qkv = try conv(try norm(x, name + ".norm.gamma", c), name + ".to_qkv", c, 3 * c, 1) // [1, 3C, H, W]
+ let rows = g.transpose(g.reshape(qkv, shape: n([3 * c, hw]), name: nil), permutation: n([1, 0]), name: nil)
+ func part(_ i: Int) -> MPSGraphTensor {
+ g.reshape(g.sliceTensor(rows, dimension: 1, start: i * c, length: c, name: nil), shape: n([1, 1, hw, c]), name: nil)
+ }
+ let o = g.scaledDotProductAttention(query: part(0), key: part(1), value: part(2), mask: nil,
+ scale: 1 / Float(c).squareRoot(), name: nil)
+ let back = g.reshape(g.transpose(g.reshape(o, shape: n([hw, c]), name: nil), permutation: n([1, 0]), name: nil),
+ shape: n([1, c, hh, ww]), name: nil)
+ return g.addition(try conv(back, name + ".proj", c, c, 1), x, name: nil)
+ }
+ /// QwenImage21DupUp3D on a first chunk: each output channel's 2×2 pixels from the input channels it repeats.
+ func dupUp(_ x: MPSGraphTensor, _ inC: Int, _ outC: Int, _ ft: Int, _ hh: Int, _ ww: Int) -> MPSGraphTensor {
+ let repeats = outC * ft * 4 / inC
+ var y = g.broadcast(g.reshape(x, shape: n([inC, 1, hh, ww]), name: nil), shape: n([inC, repeats, hh, ww]), name: nil)
+ y = g.reshape(y, shape: n([outC, ft, 2, 2, hh, ww]), name: nil)
+ y = g.sliceTensor(y, dimension: 1, start: ft - 1, length: 1, name: nil)
+ y = g.reshape(y, shape: n([outC, 2, 2, hh, ww]), name: nil)
+ y = g.transpose(y, permutation: n([0, 3, 1, 4, 2]), name: nil) // [C, H, 2, W, 2]
+ return g.reshape(y, shape: n([1, outC, 2 * hh, 2 * ww]), name: nil)
+ }
+
+ let input = g.placeholder(shape: n([1, 64, h, w]), dataType: .float32, name: "latent")
+ var x = g.addition(g.multiplication(input, constant(QwenVAE.latentsStd, [1, 64, 1, 1]), name: nil),
+ constant(QwenVAE.latentsMean, [1, 64, 1, 1]), name: nil)
+ x = try conv(x, "conv2", 64, 64, 1) // post_quant_conv
+ let dims = QwenVAE.dims
+ x = try conv(x, "decoder.conv1", 64, dims[0], 3) // conv_in
+ x = try residual(x, "decoder.middle.0", dims[0], dims[0]) // mid_block.resnets.0
+ x = try attention(x, "decoder.middle.1", dims[0], h * w, h, w) // mid_block.attentions.0
+ x = try residual(x, "decoder.middle.2", dims[0], dims[0]) // mid_block.resnets.1
+ var (hh, ww) = (h, w)
+ for i in 0..<5 { // up_blocks.i
+ let (inC, outC) = (dims[i], dims[i + 1])
+ let blockInput = x
+ var c = inC
+ for j in 0..<3 {
+ x = try residual(x, "decoder.upsamples.\(i).upsamples.\(j)", c, outC)
+ c = outC
+ }
+ if i < 4 {
+ x = g.resize(x, size: n([2 * hh, 2 * ww]), mode: .nearest, centerResult: true, alignCorners: false,
+ layout: .NCHW, name: nil)
+ x = try conv(x, "decoder.upsamples.\(i).upsamples.3.resample.1", outC, outC, 3) // upsampler
+ x = g.addition(x, dupUp(blockInput, inC, outC, QwenVAE.temporal[i], hh, ww), name: nil) // avg_shortcut
+ (hh, ww) = (2 * hh, 2 * ww)
+ }
+ }
+ x = silu(try norm(x, "decoder.head.0.gamma", dims[5])) // norm_out
+ x = try conv(x, "decoder.head.2", dims[5], 4, 3) // conv_out
+ x = g.clamp(x, min: g.constant(-1, dataType: .float32), max: g.constant(1, dataType: .float32), name: nil)
+ return (g, input, x)
+ }
+}
diff --git a/engine-mac/Sources/KokonEngine/Safetensors.swift b/engine-mac/Sources/KokonEngine/Safetensors.swift
new file mode 100644
index 0000000..9b62bdc
--- /dev/null
+++ b/engine-mac/Sources/KokonEngine/Safetensors.swift
@@ -0,0 +1,69 @@
+import Darwin
+import Foundation
+
+/// A safetensors file mapped read-only: an 8-byte header length, a JSON header (name → dtype, shape, byte range),
+/// then the data.
+public final class SafetensorsFile: @unchecked Sendable {
+ public struct Tensor: Sendable {
+ public let name: String, dtype: String, shape: [Int], start: Int, end: Int
+ public var count: Int { shape.reduce(1, *) }
+ }
+
+ public let path: String
+ public let tensors: [String: Tensor]
+ public let metadata: [String: String]
+ private let base: UnsafeRawPointer
+ private let length: Int
+ private let dataStart: Int
+
+ public init(path: String) throws {
+ self.path = path
+ let fd = open(path, O_RDONLY)
+ guard fd >= 0 else { throw GGUFFile.Failure.open(path) }
+ defer { close(fd) }
+ var info = stat()
+ guard fstat(fd, &info) == 0, info.st_size > 8 else { throw GGUFFile.Failure.open(path) }
+ length = Int(info.st_size)
+ guard let p = mmap(nil, length, PROT_READ, MAP_PRIVATE, fd, 0), p != MAP_FAILED else { throw GGUFFile.Failure.open(path) }
+ base = UnsafeRawPointer(p)
+ let headerLength = Int(UInt64(littleEndian: base.loadUnaligned(as: UInt64.self)))
+ guard headerLength > 0, 8 + headerLength <= length,
+ let json = try? JSONSerialization.jsonObject(with: Data(bytes: base + 8, count: headerLength)) as? [String: Any] else {
+ munmap(p, length)
+ throw GGUFFile.Failure.notGGUF("\(path): not a safetensors file")
+ }
+ dataStart = 8 + headerLength
+ var tensors: [String: Tensor] = [:]
+ for (name, value) in json where name != "__metadata__" {
+ guard let entry = value as? [String: Any], let dtype = entry["dtype"] as? String,
+ let shape = entry["shape"] as? [Int], let range = entry["data_offsets"] as? [Int], range.count == 2,
+ dataStart + range[1] <= length else {
+ munmap(p, length)
+ throw GGUFFile.Failure.truncated("\(path): \(name)")
+ }
+ tensors[name] = Tensor(name: name, dtype: dtype, shape: shape, start: range[0], end: range[1])
+ }
+ self.tensors = tensors
+ metadata = (json["__metadata__"] as? [String: String]) ?? [:]
+ }
+
+ deinit { munmap(UnsafeMutableRawPointer(mutating: base), length) }
+
+ /// A tensor as fp32 (BF16, F16 or F32 in the file).
+ public func floats(_ name: String) throws -> [Float] {
+ guard let t = tensors[name] else { throw GGUFFile.Failure.unsupported("no tensor \(name) in \(path)") }
+ let p = base + dataStart + t.start
+ var out = [Float](repeating: 0, count: t.count)
+ switch t.dtype {
+ case "BF16":
+ for i in 0..<t.count { out[i] = Float(bitPattern: UInt32(p.loadUnaligned(fromByteOffset: 2 * i, as: UInt16.self)) << 16) }
+ case "F16":
+ for i in 0..<t.count { out[i] = Float(Float16(bitPattern: p.loadUnaligned(fromByteOffset: 2 * i, as: UInt16.self))) }
+ case "F32":
+ for i in 0..<t.count { out[i] = p.loadUnaligned(fromByteOffset: 4 * i, as: Float.self) }
+ default:
+ throw GGUFFile.Failure.unsupported("\(name): dtype \(t.dtype)")
+ }
+ return out
+ }
+}
diff --git a/engine-mac/Sources/kokon-engine-mac/main.swift b/engine-mac/Sources/kokon-engine-mac/main.swift
index 68a5651..026e739 100644
--- a/engine-mac/Sources/kokon-engine-mac/main.swift
+++ b/engine-mac/Sources/kokon-engine-mac/main.swift
@@ -8,6 +8,7 @@ kokon-engine-mac: Kokon's Apple Silicon engine (in development)
check-dequant <file.gguf> [name...] GPU unpacking against the CPU reference
check-dit <dit.gguf> <reference dir> one DiT evaluation against tools/reference_dit.py
time-dit <dit.gguf> [grid] [text] [runs] DiT evaluations on random inputs (grid 64 = 1024²)
+ check-vae <vae.safetensors> <reference dir> [grid] the VAE decoder against tools/reference_vae.py
probe this Mac's matrix throughput: GPU, AMX, Neural Engine, together
"""
@@ -48,6 +49,9 @@ do {
runs: numbers.dropFirst(2).first ?? 3)
case "check-ane":
try Checks.aneSurfaces()
+ case "check-vae":
+ guard arguments.count >= 3 else { fail(usage) }
+ try Checks.vae(path: arguments[1], reference: arguments[2], timeGrid: arguments.count > 3 ? Int(arguments[3]) : nil)
case "probe":
try Probe.run()
default:
diff --git a/engine-mac/tools/reference_vae.py b/engine-mac/tools/reference_vae.py
new file mode 100644
index 0000000..7e641db
--- /dev/null
+++ b/engine-mac/tools/reference_vae.py
@@ -0,0 +1,86 @@
+"""The Qwen-Image 2.1 VAE decoder reference for the Mac engine: diffusers' `AutoencoderKLQwenImage21` in fp32 on
+the CPU, on Kokon's VAE file. Decodes a random
+normalized latent as the pipeline does (`latents * std + mean`, decode, clamp) and saves the input and the
+RGBA output for `kokon-engine-mac check-vae`. Kokon's file uses Wan 2.2's names; `decoder_name` maps them to
+diffusers' (the same mapping the engine reads them by).
+
+ python -I engine-mac/tools/reference_vae.py <vae.safetensors> <out dir> [--grid 16]
+"""
+import argparse
+import json
+import os
+
+import numpy as np
+import torch
+from diffusers import AutoencoderKLQwenImage21
+from safetensors.torch import load_file
+
+
+def decoder_name(key):
+ """Wan 2.2 VAE name -> diffusers AutoencoderKLQwenImage21 name, decoder side; None for the encoder."""
+ if key.startswith("conv2."):
+ return "post_quant_conv." + key[6:]
+ if not key.startswith("decoder."):
+ return None
+ k = key[len("decoder."):]
+ residual = {"residual.0.gamma": "norm1.gamma", "residual.2.weight": "conv1.weight", "residual.2.bias": "conv1.bias",
+ "residual.3.gamma": "norm2.gamma", "residual.6.weight": "conv2.weight", "residual.6.bias": "conv2.bias",
+ "shortcut.weight": "conv_shortcut.weight", "shortcut.bias": "conv_shortcut.bias"}
+ parts = k.split(".")
+ if parts[0] == "conv1":
+ return "decoder.conv_in." + parts[1]
+ if parts[0] == "head":
+ return "decoder.norm_out.gamma" if parts[1] == "0" else "decoder.conv_out." + parts[2]
+ if parts[0] == "middle":
+ rest = ".".join(parts[2:])
+ if parts[1] == "1":
+ return "decoder.mid_block.attentions.0." + rest
+ return f"decoder.mid_block.resnets.{int(parts[1]) // 2}." + residual[rest]
+ if parts[0] == "upsamples":
+ i, j, rest = parts[1], int(parts[3]), ".".join(parts[4:])
+ if j == 3:
+ return f"decoder.up_blocks.{i}.upsampler." + rest
+ return f"decoder.up_blocks.{i}.resnets.{j}." + residual[rest]
+ raise KeyError(key)
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument("vae")
+ parser.add_argument("out")
+ parser.add_argument("--grid", type=int, default=16)
+ parser.add_argument("--seed", type=int, default=7)
+ args = parser.parse_args()
+ torch.manual_seed(args.seed)
+ torch.set_grad_enabled(False)
+ os.makedirs(args.out, exist_ok=True)
+
+ vae = AutoencoderKLQwenImage21() # the defaults are Qwen-Image 2.1's config
+ model = vae.state_dict()
+ converted = {}
+ for key, value in load_file(args.vae).items():
+ name = decoder_name(key)
+ if name is not None:
+ converted[name] = value.float().reshape(model[name].shape)
+ missing, unexpected = vae.load_state_dict(converted, strict=False)
+ missing = [k for k in missing if not k.startswith("encoder.") and "time_conv" not in k and k != "quant_conv.weight"
+ and k != "quant_conv.bias"]
+ assert not missing, f"decoder weights missing: {missing[:10]}"
+ assert not unexpected, f"unexpected: {unexpected[:10]}"
+ vae.eval()
+
+ g = args.grid
+ latent = torch.randn(1, 64, 1, g, g) # normalized, as the DiT produces
+ mean = torch.tensor(vae.config.latents_mean).view(1, 64, 1, 1, 1)
+ std = torch.tensor(vae.config.latents_std).view(1, 64, 1, 1, 1)
+ image = vae.decode(latent * std + mean, return_dict=False)[0][:, :, 0] # [1, 4, H, W] in [-1, 1]
+
+ latent[0, :, 0].contiguous().numpy().astype(np.float32).tofile(os.path.join(args.out, "latent.f32"))
+ image[0].contiguous().numpy().astype(np.float32).tofile(os.path.join(args.out, "image.f32"))
+ with open(os.path.join(args.out, "meta.json"), "w") as f:
+ json.dump({"grid": g, "image": list(image.shape[1:]), "seed": args.seed}, f)
+ print("image", tuple(image.shape), float(image.min()), float(image.max()))
+
+
+if __name__ == "__main__":
+ main()