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: text to image, the first real images

Gabriele Lozupone9ee3221dcb92
diff --git a/engine-mac/README.md b/engine-mac/README.md
index 554536a..df6b4e9 100644
--- a/engine-mac/README.md
+++ b/engine-mac/README.md
@@ -12,6 +12,8 @@ swift test # no model needed
.build/release/kokon-engine-mac probe # this Mac's matrix throughput, ~1 min, no model
.build/release/kokon-engine-mac inspect <file.gguf>
.build/release/kokon-engine-mac check-dequant <file.gguf> [tensor...]
+.build/release/kokon-engine-mac generate <encoder.gguf> <dit.gguf> <vae.safetensors> "a red fox in the snow" \
+ [--size 1024x1024] [--seed 42] [--out out.png]
```
## What is here
@@ -30,6 +32,7 @@ swift test # no model needed
| `QwenVAE.swift`, `Safetensors.swift` | the VAE decoder as one MPSGraph, from Kokon's VAE file (Wan 2.2 names) |
| `QwenTokenizer.swift` | Qwen's byte-level BPE tokenizer, read from the encoder GGUF's metadata |
| `QwenTextEncoder.swift`, `Kernels/text.metal` | the text encoder: Qwen3-VL-8B's text decoder on the GPU, diffusers' prompt template |
+| `QwenPipeline.swift` | text to image: noise, Turbo's 8 flow-Euler steps (`planner::TURBO_SIGMAS`), VAE, PNG |
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.
@@ -62,6 +65,20 @@ head answers " Paris" to a factual prompt (it does), so the weights are read rig
2026-10-25: tokenizer identical on 42 cases (accents, CJK, emoji, decomposed Unicode, special tokens in the text);
conditioning within 5.1e-6 relative (37 tokens) and 5.6e-6 (144 tokens). One encode: 0.45 s (37 tokens), 0.8 s (144).
+**Text to image against diffusers.** `tools/reference_generate.py` runs QwenImage21Pipeline's loop with the
+references above (diffusers' scheduler on the checkpoint's sigmas, the DiT layer by layer, the VAE, the image
+processor) and saves its noise; `check-generate` starts the engine from that noise:
+
+```bash
+~/kokon-bench/venv-oracle/bin/python -I tools/reference_generate.py <dit.gguf> <vae.safetensors> ~/kokon-bench/ref/text/fox <repo dir> ~/kokon-bench/ref/generate-256 # ~5 min
+.build/release/kokon-engine-mac check-generate <encoder.gguf> <dit.gguf> <vae.safetensors> ~/kokon-bench/ref/generate-256
+```
+
+256², 2026-10-25: each step's latent within 6.7e-6 relative, the image within 1.0e-5, 97 of 262 144 8-bit values
+differ by 1. **First 1024² image (M2 Pro, `generate`): 100.7 s in all**, text encoder 1.7 s, 8 steps of 11.4–12.9 s,
+VAE 5.4 s with its graph build; peak memory 4.1 GB (Kokon's sd.cpp: ~4.5 min). The seed's noise is the engine's
+own (SplitMix64 + Box–Muller), not sd.cpp's: the same seed gives a different image than Kokon today.
+
## First measurements (M2 Pro 19-core GPU, 16 GB, macOS 27, 2026-10-25, `probe`)
m = 4 096 rows (a 1024² image), TFLOP/s:
diff --git a/engine-mac/Sources/KokonEngine/QwenPipeline.swift b/engine-mac/Sources/KokonEngine/QwenPipeline.swift
new file mode 100644
index 0000000..863c84d
--- /dev/null
+++ b/engine-mac/Sources/KokonEngine/QwenPipeline.swift
@@ -0,0 +1,171 @@
+import CoreGraphics
+import Foundation
+import ImageIO
+import UniformTypeIdentifiers
+
+/// **Qwen-Image 2.1 Turbo, text to image**: `QwenImage21Pipeline.__call__` (diffusers 0.42) with the engine's parts.
+///
+/// prompt ─ QwenTextEncoder ─ conditioning [T, 4096] (the encoder's file is unmapped before the DiT loads)
+/// noise [64, h, w] ─ packed [h·w, 64] ─ 8 × { v = DiT(x, σᵢ); x += (σᵢ₊₁ − σᵢ) · v } flow Euler
+/// x ─ unpacked [64, h, w] ─ QwenVAE ─ RGBA [4, 16h, 16w] in [−1, 1] ─ 8-bit RGBA
+///
+/// The sigmas are Turbo's (`sample_sigmas` of the checkpoint, the ones Kokon already sends to sd.cpp); the
+/// scheduler (shift 1, no dynamic shifting) uses them as they are and ends on 0. The DiT reads the timestep as σ.
+public final class QwenPipeline {
+ /// `planner::TURBO_SIGMAS` (crates/qls-core/src/planner.rs): the checkpoint's sample_sigmas, then 0.
+ public static let turboSigmas: [Float] = [1.0, 0.978453, 0.95418, 0.926626, 0.89508, 0.845148, 0.704534, 0.414568, 0.0]
+
+ public let encoderPath, ditPath, vaePath: String
+ let context: MetalContext
+ /// Progress lines; stdout by default.
+ public var log: (String) -> Void = { print($0) }
+ /// Seconds per phase of the last run: encode, steps (each), dit load, vae, total.
+ public private(set) var timings: [String: Double] = [:]
+
+ public init(encoder: String, dit: String, vae: String) throws {
+ encoderPath = encoder
+ ditPath = dit
+ vaePath = vae
+ context = try MetalContext()
+ }
+
+ /// The output size diffusers works at: each side floored to a multiple of 32 (two latent cells).
+ public static func workingSize(width: Int, height: Int) -> (width: Int, height: Int) {
+ (width / 32 * 32, height / 32 * 32)
+ }
+
+ /// Text to image at `width` × `height` (multiples of 32). `noise`: a latent `[64, h, w]` to start from instead of
+ /// the seed's; `step`: called after each step with its index and the packed latent `[h·w, 64]`.
+ /// Returns the decoded image, RGBA `[4, height, width]` in [−1, 1].
+ public func textToImage(prompt: String, width: Int, height: Int, seed: UInt64, noise: [Float]? = nil,
+ sigmas: [Float] = QwenPipeline.turboSigmas,
+ step: ((Int, [Float]) -> Void)? = nil) throws -> [Float] {
+ guard width % 32 == 0, height % 32 == 0, width >= 64, height >= 64 else {
+ throw QwenSequence.Failure.layout("\(width)×\(height): each side must be a multiple of 32, at least 64")
+ }
+ let started = DispatchTime.now().uptimeNanoseconds
+ timings = [:]
+ func since(_ t: UInt64) -> Double { Double(DispatchTime.now().uptimeNanoseconds - t) * 1e-9 }
+ let (h, w) = (height / 16, width / 16)
+ let channels = QwenDiT.channels
+
+ // 1. The prompt. The encoder and its 5 GB mapping are gone when this scope ends.
+ var t = DispatchTime.now().uptimeNanoseconds
+ let (conditioning, rows): ([Float], Int) = try {
+ let file = try GGUFFile(path: encoderPath)
+ let encoder = try QwenTextEncoder(file: file, context: context)
+ defer { encoder.release() }
+ return try encoder.conditioning(prompt: prompt)
+ }()
+ timings["encode"] = since(t)
+ log(String(format: "text encoder: %d tokens in %.2f s", rows, timings["encode"]!))
+
+ // 2. Noise, packed: token y·w + x holds the 64 channels of cell (y, x).
+ let start = noise ?? QwenPipeline.gaussian(seed: seed, count: channels * h * w)
+ guard start.count == channels * h * w else {
+ throw QwenSequence.Failure.layout("noise of \(start.count) values for a \(channels)×\(h)×\(w) latent")
+ }
+ var x = QwenPipeline.pack(start, height: h, width: w)
+
+ // 3. The steps.
+ t = DispatchTime.now().uptimeNanoseconds
+ let sequence = try QwenSequence.textToImage(text: rows, target: .init(height: h, width: w))
+ try {
+ let file = try GGUFFile(path: ditPath)
+ defer { context.release(file) }
+ let dit = try QwenDiT(file: file, context: context, sequence: sequence)
+ timings["dit load"] = since(t)
+ for i in 0..<(sigmas.count - 1) {
+ let stepStart = DispatchTime.now().uptimeNanoseconds
+ let velocity = try dit.forward(encoder: conditioning, target: x, sigma: sigmas[i])
+ let dt = sigmas[i + 1] - sigmas[i]
+ for j in x.indices { x[j] += dt * velocity[j] }
+ timings["step \(i + 1)"] = since(stepStart)
+ log(String(format: "step %d/%d (σ %.4f): %.2f s", i + 1, sigmas.count - 1, sigmas[i], timings["step \(i + 1)"]!))
+ step?(i, x)
+ }
+ }()
+
+ // 4. The image.
+ t = DispatchTime.now().uptimeNanoseconds
+ let vae = try QwenVAE(path: vaePath, context: context)
+ let image = try vae.decode(QwenPipeline.unpack(x, height: h, width: w), height: h, width: w)
+ timings["vae"] = since(t)
+ timings["total"] = since(started)
+ log(String(format: "VAE: %.2f s; total %.1f s", timings["vae"]!, timings["total"]!))
+ return image
+ }
+
+ // MARK: - latents
+
+ /// `[64, h, w]` → tokens `[h·w, 64]` (`_pack_latents`: a spatial flatten, then channels last).
+ public static func pack(_ latent: [Float], height h: Int, width w: Int) -> [Float] {
+ let c = latent.count / (h * w)
+ var out = [Float](repeating: 0, count: latent.count)
+ for ch in 0..<c { for p in 0..<(h * w) { out[p * c + ch] = latent[ch * h * w + p] } }
+ return out
+ }
+
+ /// Tokens `[h·w, 64]` → `[64, h, w]` (`_unpack_latents`).
+ public static func unpack(_ tokens: [Float], height h: Int, width w: Int) -> [Float] {
+ let c = tokens.count / (h * w)
+ var out = [Float](repeating: 0, count: tokens.count)
+ for p in 0..<(h * w) { for ch in 0..<c { out[ch * h * w + p] = tokens[p * c + ch] } }
+ return out
+ }
+
+ /// Standard normal values for `seed`: SplitMix64 bits, Box–Muller in double precision.
+ /// Not sd.cpp's generator nor torch's: the same seed does not give the same noise as they do.
+ public static func gaussian(seed: UInt64, count: Int) -> [Float] {
+ var state = seed
+ func next() -> UInt64 {
+ state &+= 0x9E37_79B9_7F4A_7C15
+ var z = state
+ z = (z ^ (z >> 30)) &* 0xBF58_476D_1CE4_E5B9
+ z = (z ^ (z >> 27)) &* 0x94D0_49BB_1331_11EB
+ return z ^ (z >> 31)
+ }
+ func uniform() -> Double { (Double(next() >> 11) + 0.5) / Double(1 << 53) } // (0, 1)
+ var out = [Float](repeating: 0, count: count)
+ var i = 0
+ while i < count {
+ let r = (-2 * Foundation.log(uniform())).squareRoot(), angle = 2 * Double.pi * uniform()
+ out[i] = Float(r * cos(angle))
+ if i + 1 < count { out[i + 1] = Float(r * sin(angle)) }
+ i += 2
+ }
+ return out
+ }
+
+ // MARK: - output
+
+ /// RGBA `[4, H, W]` in [−1, 1] → interleaved 8-bit RGBA, as VaeImageProcessor.postprocess (`(x / 2 + 0.5)`
+ /// clamped, `· 255`, rounded half to even).
+ public static func pixels(_ image: [Float], width: Int, height: Int) -> [UInt8] {
+ let plane = width * height, channels = image.count / plane
+ var out = [UInt8](repeating: 255, count: plane * 4)
+ for c in 0..<min(channels, 4) {
+ for p in 0..<plane {
+ let v = min(max(image[c * plane + p] / 2 + 0.5, 0), 1)
+ out[p * 4 + c] = UInt8((v * 255).rounded(.toNearestOrEven))
+ }
+ }
+ return out
+ }
+
+ /// Writes interleaved 8-bit RGBA (straight alpha) as a PNG.
+ public static func writePNG(_ rgba: [UInt8], width: Int, height: Int, to path: String) throws {
+ let data = Data(rgba) as CFData
+ guard let provider = CGDataProvider(data: data),
+ let image = CGImage(width: width, height: height, bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: width * 4,
+ space: CGColorSpace(name: CGColorSpace.sRGB)!,
+ bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.last.rawValue),
+ provider: provider, decode: nil, shouldInterpolate: false, intent: .defaultIntent),
+ let destination = CGImageDestinationCreateWithURL(URL(fileURLWithPath: path) as CFURL,
+ UTType.png.identifier as CFString, 1, nil) else {
+ throw MetalContext.Failure.buffer("cannot write \(path)")
+ }
+ CGImageDestinationAddImage(destination, image, nil)
+ guard CGImageDestinationFinalize(destination) else { throw MetalContext.Failure.buffer("cannot write \(path)") }
+ }
+}
diff --git a/engine-mac/Sources/KokonEngine/TextChecks.swift b/engine-mac/Sources/KokonEngine/TextChecks.swift
index 0c292d1..886fd32 100644
--- a/engine-mac/Sources/KokonEngine/TextChecks.swift
+++ b/engine-mac/Sources/KokonEngine/TextChecks.swift
@@ -56,3 +56,38 @@ extension Checks {
}
}
}
+
+extension Checks {
+ /// Text to image against `tools/reference_generate.py`, from its noise: each step's latent, the decoded image,
+ /// the 8-bit pixels.
+ public static func generate(encoder: String, dit: String, vae: String, reference directory: String) throws {
+ let meta = try JSONSerialization.jsonObject(with: Data(contentsOf: URL(fileURLWithPath: directory)
+ .appendingPathComponent("meta.json"))) as! [String: Any]
+ let prompt = meta["prompt"] as! String, grid = meta["grid"] as! [Int]
+ let (h, w) = (grid[0], grid[1])
+ let pipeline = try QwenPipeline(encoder: encoder, dit: dit, vae: vae)
+ func report(_ name: String, _ got: UnsafePointer<Float>, _ want: [Float]) {
+ let r = compare(got, want)
+ print(String(format: " %-12@ rel %.2e max |Δ| %.3g%@", name as NSString, r.relative, r.maxAbs, r.finite ? "" : " NON-FINITE"))
+ }
+ let image = try pipeline.textToImage(prompt: prompt, width: w * 16, height: h * 16, seed: 0,
+ noise: try reference(directory, "noise")) { i, latent in
+ latent.withUnsafeBufferPointer { report("latent\(i)", $0.baseAddress!, try! reference(directory, "latent\(i)")) }
+ }
+ image.withUnsafeBufferPointer { report("image", $0.baseAddress!, try! reference(directory, "image")) }
+ let got = QwenPipeline.pixels(image, width: w * 16, height: h * 16)
+ let want = [UInt8](try Data(contentsOf: URL(fileURLWithPath: directory).appendingPathComponent("pixels.u8")))
+ let channels = want.count / (h * 16 * w * 16)
+ var differ = 0, worst = 0
+ for p in 0..<(h * 16 * w * 16) {
+ for c in 0..<channels {
+ let d = abs(Int(got[p * 4 + c]) - Int(want[p * channels + c]))
+ if d > 0 { differ += 1; worst = max(worst, d) }
+ }
+ }
+ print("pixels: \(differ) of \(want.count) 8-bit values differ, by at most \(worst)")
+ let png = URL(fileURLWithPath: directory).appendingPathComponent("engine.png").path
+ try QwenPipeline.writePNG(got, width: w * 16, height: h * 16, to: png)
+ print("wrote \(png)")
+ }
+}
diff --git a/engine-mac/Sources/kokon-engine-mac/main.swift b/engine-mac/Sources/kokon-engine-mac/main.swift
index 7167e32..70a7b2c 100644
--- a/engine-mac/Sources/kokon-engine-mac/main.swift
+++ b/engine-mac/Sources/kokon-engine-mac/main.swift
@@ -11,6 +11,10 @@ kokon-engine-mac: Kokon's Apple Silicon engine (in development)
check-vae <vae.safetensors> <reference dir> [grid] the VAE decoder against tools/reference_vae.py
check-tokenizer <encoder.gguf> <fixture.json> the tokenizer against tools/reference_tokenizer.py
check-text <encoder.gguf> <reference dir> the text encoder against tools/reference_text_encoder.py
+ check-generate <encoder.gguf> <dit.gguf> <vae.safetensors> <reference dir>
+ text to image against tools/reference_generate.py, from its noise
+ generate <encoder.gguf> <dit.gguf> <vae.safetensors> "<prompt>" [--size WxH] [--seed N] [--out file.png]
+ text to image, Turbo's 8 steps (default 1024x1024, seed 42, out.png)
probe this Mac's matrix throughput: GPU, AMX, Neural Engine, together
"""
@@ -60,6 +64,32 @@ do {
case "check-text":
guard arguments.count == 3 else { fail(usage) }
try Checks.textEncoder(path: arguments[1], reference: arguments[2])
+ case "check-generate":
+ guard arguments.count == 5 else { fail(usage) }
+ try Checks.generate(encoder: arguments[1], dit: arguments[2], vae: arguments[3], reference: arguments[4])
+ case "generate":
+ guard arguments.count >= 5 else { fail(usage) }
+ var (width, height, seed, out) = (1024, 1024, UInt64(42), "out.png")
+ var options = arguments.dropFirst(5).makeIterator()
+ while let option = options.next() {
+ guard let value = options.next() else { fail(usage) }
+ switch option {
+ case "--size":
+ let parts = value.split(separator: "x").compactMap { Int($0) }
+ guard parts.count == 2 else { fail("--size takes WxH, e.g. 1024x768") }
+ (width, height) = (parts[0], parts[1])
+ case "--seed": seed = UInt64(value) ?? seed
+ case "--out": out = value
+ default: fail(usage)
+ }
+ }
+ let size = QwenPipeline.workingSize(width: width, height: height)
+ if size != (width, height) { print("size \(width)×\(height) → \(size.width)×\(size.height) (multiples of 32)") }
+ let pipeline = try QwenPipeline(encoder: arguments[1], dit: arguments[2], vae: arguments[3])
+ let image = try pipeline.textToImage(prompt: arguments[4], width: size.width, height: size.height, seed: seed)
+ try QwenPipeline.writePNG(QwenPipeline.pixels(image, width: size.width, height: size.height),
+ width: size.width, height: size.height, to: out)
+ print("wrote \(out) (\(size.width)×\(size.height), seed \(seed))")
case "probe":
try Probe.run()
default:
diff --git a/engine-mac/Tests/KokonEngineTests/QwenPipelineTests.swift b/engine-mac/Tests/KokonEngineTests/QwenPipelineTests.swift
new file mode 100644
index 0000000..f5a1b44
--- /dev/null
+++ b/engine-mac/Tests/KokonEngineTests/QwenPipelineTests.swift
@@ -0,0 +1,46 @@
+import XCTest
+@testable import KokonEngine
+
+/// The pipeline's glue, without a model: latent packing, the noise, the 8-bit conversion, the sizes.
+final class QwenPipelineTests: XCTestCase {
+ func testPackIsChannelsLastAndUnpackInvertsIt() {
+ // [2 channels, 2 × 3]: value = 100 · channel + position.
+ let (c, h, w) = (2, 2, 3)
+ let latent = (0..<(c * h * w)).map { Float(($0 / (h * w)) * 100 + $0 % (h * w)) }
+ let tokens = QwenPipeline.pack(latent, height: h, width: w)
+ XCTAssertEqual(Array(tokens[0..<4]), [0, 100, 1, 101]) // token 0: both channels, then token 1
+ XCTAssertEqual(Array(tokens[10..<12]), [5, 105]) // token 5 = cell (1, 2)
+ XCTAssertEqual(QwenPipeline.unpack(tokens, height: h, width: w), latent)
+ }
+
+ func testNoiseIsStandardNormalAndSeeded() {
+ let a = QwenPipeline.gaussian(seed: 7, count: 200_001)
+ XCTAssertEqual(a, QwenPipeline.gaussian(seed: 7, count: 200_001))
+ XCTAssertNotEqual(Array(a.prefix(8)), Array(QwenPipeline.gaussian(seed: 8, count: 8)))
+ let mean = a.reduce(0, +) / Float(a.count)
+ let variance = a.reduce(0) { $0 + ($1 - mean) * ($1 - mean) } / Float(a.count)
+ XCTAssertEqual(mean, 0, accuracy: 0.01)
+ XCTAssertEqual(variance, 1, accuracy: 0.01)
+ XCTAssert(a.allSatisfy(\.isFinite))
+ }
+
+ func testPixelsFollowVaeImageProcessor() {
+ // One pixel, RGBA planes: −1 → 0, 1 → 255, beyond the range clamped, 0 → 127.5 rounded to even (128).
+ let image: [Float] = [-1, 1, 3, 0]
+ XCTAssertEqual(QwenPipeline.pixels(image, width: 1, height: 1), [0, 255, 255, 128])
+ // Three channels: alpha stays opaque.
+ XCTAssertEqual(QwenPipeline.pixels([-1, -1, -1], width: 1, height: 1), [0, 0, 0, 255])
+ }
+
+ func testWorkingSizeFloorsToTwoLatentCells() {
+ XCTAssert(QwenPipeline.workingSize(width: 1024, height: 768) == (1024, 768))
+ XCTAssert(QwenPipeline.workingSize(width: 1000, height: 1376) == (992, 1376))
+ }
+
+ func testTurboSigmasAreThePlannersAndDecrease() {
+ XCTAssertEqual(QwenPipeline.turboSigmas.count, 9)
+ XCTAssertEqual(QwenPipeline.turboSigmas.first, 1)
+ XCTAssertEqual(QwenPipeline.turboSigmas.last, 0)
+ XCTAssert(zip(QwenPipeline.turboSigmas, QwenPipeline.turboSigmas.dropFirst()).allSatisfy { $0 > $1 })
+ }
+}
diff --git a/engine-mac/tools/reference_dit.py b/engine-mac/tools/reference_dit.py
index e1a58e4..94b96b4 100644
--- a/engine-mac/tools/reference_dit.py
+++ b/engine-mac/tools/reference_dit.py
@@ -72,6 +72,74 @@ def layer0_stages(block, x, modulation, rotary_emb, target_token_mask, save):
save("l0_mlp", block.img_mlp(normed2)[0])
+class ReferenceDiT:
+ """QwenImage21Transformer2DModel.forward, batch 1, no cache, text-to-image, one block module swapped per layer."""
+
+ def __init__(self, path, layers=32):
+ self.w = w = Weights(path)
+ d, self.layers = 4096, layers
+ self.img_in = torch.nn.Linear(64, d, bias=False)
+ w.load(self.img_in, "img_in.")
+ self.txt_in = QwenImage21TextProjection(d, d, eps=1e-6)
+ w.load(self.txt_in, "txt_in.")
+ self.time_text_embed = QwenImage21TimestepProjEmbeddings(embedding_dim=d)
+ w.load(self.time_text_embed, "time_text_embed.")
+ self.modulation_linear = torch.nn.Linear(d, 4 * d, bias=False)
+ self.modulation_linear.weight.copy_(w.get("modulation.1.weight"))
+ self.norm_out = QwenImage21AdaLayerNormContinuous(d, d, eps=1e-6)
+ w.load(self.norm_out, "norm_out.")
+ self.proj_out = torch.nn.Linear(d, 64, bias=False)
+ w.load(self.proj_out, "proj_out.")
+ self.rope = QwenImage21Rope(theta=10000, axes_dim=[16, 56, 56])
+ self.block = QwenImage21TransformerBlock(d, 32, 128, mlp_ratio=3, eps=1e-6)
+
+ def forward(self, encoder, latent, h, w_, timestep, save=None, progress=True):
+ """`encoder` [1, T, d], `latent` [1, h * w, 64], `timestep` a [1] tensor (σ); returns the target's velocity
+ [1, h * w, 64]. `save(name, tensor)` receives every stage when given."""
+ d, text, tokens = 4096, encoder.shape[1], h * w_
+ img_shapes = [(1, h, w_)]
+ img_mask = torch.tensor([[False] * text + [True] * (tokens // 4)])
+ hidden_states = self.img_in(latent)
+ encoder_hidden_states = self.txt_in(encoder)
+ repeats = torch.where(img_mask, 4, 1)[0]
+ image_pad_mask = torch.repeat_interleave(img_mask[0], repeats)
+ joint = torch.cat([encoder_hidden_states, encoder_hidden_states.new_zeros(1, tokens // 4, d)], dim=1)
+ joint = joint.repeat_interleave(repeats, dim=1)
+ joint[:, image_pad_mask] = hidden_states
+ if save:
+ save("joint_in", joint[0])
+
+ rotary_emb = self.rope(img_shapes, image_pad_mask, device=torch.device("cpu"))
+ image_ids, target_token_mask = QwenImage21Transformer2DModel.build_token_metadata(image_pad_mask, img_shapes)
+ t = torch.cat([timestep, timestep.new_zeros(1)], dim=0)
+ temb = self.time_text_embed(t, hidden_states)
+ modulation = self.modulation_linear(torch.nn.functional.silu(temb))
+ if save:
+ save("rope", torch.view_as_real(rotary_emb).reshape(rotary_emb.shape[0], -1))
+ save("temb", temb)
+ save("modulation", modulation)
+ prefix_len = int((~target_token_mask).sum())
+ segments = _qwenimage21_prefix_segments(image_ids, prefix_len)
+
+ for layer in range(self.layers):
+ self.w.load(self.block, f"transformer_blocks.{layer}.")
+ if layer == 0 and save:
+ layer0_stages(self.block, joint, modulation, rotary_emb, target_token_mask, save)
+ joint = self.block(hidden_states=joint, modulation=modulation, rotary_emb=rotary_emb, attention_mask=None,
+ target_token_mask=target_token_mask, segments=segments)
+ if save and (layer in (0, 1) or layer == self.layers - 1):
+ save(f"layer{layer}_out", joint[0])
+ if progress:
+ print(f"layer {layer} done", flush=True)
+
+ normed = self.norm_out(joint, temb, target_token_mask)
+ output = self.proj_out(normed)
+ if save:
+ save("norm_out", normed[0])
+ save("model_out", output[0, prefix_len:])
+ return output[:, prefix_len:]
+
+
def main():
parser = argparse.ArgumentParser()
parser.add_argument("gguf")
@@ -85,8 +153,6 @@ def main():
torch.manual_seed(args.seed)
torch.set_grad_enabled(False)
os.makedirs(args.out, exist_ok=True)
- w = Weights(args.gguf)
- d, heads, head_dim, layers = 4096, 32, 128, args.layers
saved = {}
@@ -97,67 +163,14 @@ def main():
# Inputs: the encoder's last layer for T positions (no image slots: text-to-image), the packed latent.
h = w_ = args.grid
- tokens = h * w_
- encoder = torch.randn(1, args.text, d) * 4
- latent = torch.randn(1, tokens, 64)
- timestep = torch.tensor([args.sigma], dtype=torch.float32)
+ encoder = torch.randn(1, args.text, 4096) * 4
+ latent = torch.randn(1, h * w_, 64)
save("in_encoder", encoder[0])
save("in_latent", latent[0])
- img_shapes = [(1, h, w_)]
- img_mask = torch.tensor([[False] * args.text + [True] * (tokens // 4)])
-
- img_in = torch.nn.Linear(64, d, bias=False)
- w.load(img_in, "img_in.")
- txt_in = QwenImage21TextProjection(d, d, eps=1e-6)
- w.load(txt_in, "txt_in.")
- time_text_embed = QwenImage21TimestepProjEmbeddings(embedding_dim=d)
- w.load(time_text_embed, "time_text_embed.")
- modulation_linear = torch.nn.Linear(d, 4 * d, bias=False)
- modulation_linear.weight.copy_(w.get("modulation.1.weight"))
- norm_out = QwenImage21AdaLayerNormContinuous(d, d, eps=1e-6)
- w.load(norm_out, "norm_out.")
- proj_out = torch.nn.Linear(d, 64, bias=False)
- w.load(proj_out, "proj_out.")
- rope = QwenImage21Rope(theta=10000, axes_dim=[16, 56, 56])
- block = QwenImage21TransformerBlock(d, heads, head_dim, mlp_ratio=3, eps=1e-6)
-
- # ── QwenImage21Transformer2DModel.forward, batch 1, no cache ──
- hidden_states = img_in(latent)
- encoder_hidden_states = txt_in(encoder)
- repeats = torch.where(img_mask, 4, 1)[0]
- image_pad_mask = torch.repeat_interleave(img_mask[0], repeats)
- joint = torch.cat([encoder_hidden_states, encoder_hidden_states.new_zeros(1, tokens // 4, d)], dim=1)
- joint = joint.repeat_interleave(repeats, dim=1)
- joint[:, image_pad_mask] = hidden_states
- save("joint_in", joint[0])
-
- rotary_emb = rope(img_shapes, image_pad_mask, device=torch.device("cpu"))
- save("rope", torch.view_as_real(rotary_emb).reshape(rotary_emb.shape[0], -1))
- image_ids, target_token_mask = QwenImage21Transformer2DModel.build_token_metadata(image_pad_mask, img_shapes)
- t = torch.cat([timestep, timestep.new_zeros(1)], dim=0)
- temb = time_text_embed(t, hidden_states)
- modulation = modulation_linear(torch.nn.functional.silu(temb))
- save("temb", temb)
- save("modulation", modulation)
- prefix_len = int((~target_token_mask).sum())
- segments = _qwenimage21_prefix_segments(image_ids, prefix_len)
-
- for layer in range(layers):
- w.load(block, f"transformer_blocks.{layer}.")
- if layer == 0:
- layer0_stages(block, joint, modulation, rotary_emb, target_token_mask, save)
- joint = block(hidden_states=joint, modulation=modulation, rotary_emb=rotary_emb, attention_mask=None,
- target_token_mask=target_token_mask, segments=segments)
- if layer in (0, 1) or layer == layers - 1:
- save(f"layer{layer}_out", joint[0])
- print(f"layer {layer} done", flush=True)
-
- normed = norm_out(joint, temb, target_token_mask)
- save("norm_out", normed[0])
- output = proj_out(normed)
- save("model_out", output[0, prefix_len:])
-
- meta = {"grid": [h, w_], "text": args.text, "sigma": args.sigma, "layers": layers, "prefix": prefix_len,
+ dit = ReferenceDiT(args.gguf, layers=args.layers)
+ dit.forward(encoder, latent, h, w_, torch.tensor([args.sigma], dtype=torch.float32), save=save)
+
+ meta = {"grid": [h, w_], "text": args.text, "sigma": args.sigma, "layers": args.layers, "prefix": args.text,
"seed": args.seed, "tensors": saved, "gguf": os.path.basename(args.gguf),
"diffusers": __import__("diffusers").__version__, "torch": torch.__version__}
with open(os.path.join(args.out, "meta.json"), "w") as f:
diff --git a/engine-mac/tools/reference_generate.py b/engine-mac/tools/reference_generate.py
new file mode 100644
index 0000000..df4fd04
--- /dev/null
+++ b/engine-mac/tools/reference_generate.py
@@ -0,0 +1,97 @@
+"""End-to-end text-to-image reference for the Mac engine: QwenImage21Pipeline.__call__'s loop (diffusers 0.42) with
+the pieces the other references check, in fp32 on the CPU:
+
+ conditioning of `reference_text_encoder.py` ─┐
+ torch.randn noise [1, 1, 64, h, w], packed ──┴ FlowMatchEulerDiscreteScheduler over the checkpoint's sample_sigmas,
+ each step `reference_dit.ReferenceDiT` (timestep = t / 1000)
+ unpacked, · std + mean ─ `reference_vae.load_vae` decode ─ VaeImageProcessor.postprocess ─ PNG
+
+Saves the noise, every step's velocity and latent, the decoded image and the final pixels for
+`kokon-engine-mac check-generate`. 256² takes ~5 min (8 DiT evaluations, each layer's weights unpacked by gguf-py).
+
+ python -I engine-mac/tools/reference_generate.py <dit.gguf> <vae.safetensors> <text reference dir> <repo dir> <out>
+ [--grid 16] [--seed 1]
+
+`<repo dir>`: the official Qwen/Qwen-Image-2.1-Turbo files (model_index.json: sample_sigmas; scheduler/).
+"""
+import argparse
+import json
+import os
+import sys
+
+import numpy as np
+import torch
+from diffusers import FlowMatchEulerDiscreteScheduler
+from diffusers.image_processor import VaeImageProcessor
+from diffusers.pipelines.qwenimage21.pipeline_qwenimage21 import calculate_shift
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) # the sibling references
+from reference_dit import ReferenceDiT # noqa: E402
+from reference_vae import load_vae # noqa: E402
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument("dit")
+ parser.add_argument("vae")
+ parser.add_argument("text", help="output of reference_text_encoder.py")
+ parser.add_argument("repo")
+ parser.add_argument("out")
+ parser.add_argument("--grid", type=int, default=16, help="latent grid side (16 = a 256² image)")
+ parser.add_argument("--seed", type=int, default=1)
+ args = parser.parse_args()
+ torch.set_grad_enabled(False)
+ os.makedirs(args.out, exist_ok=True)
+
+ def save(name, tensor):
+ tensor.detach().to(torch.float32).contiguous().numpy().tofile(os.path.join(args.out, name + ".f32"))
+
+ text_meta = json.load(open(os.path.join(args.text, "meta.json")))
+ conditioning = torch.from_numpy(np.fromfile(os.path.join(args.text, "conditioning.f32"), dtype=np.float32))
+ conditioning = conditioning.view(1, -1, 4096)
+ h = w = args.grid
+
+ # prepare_latents + _pack_latents
+ noise = torch.randn((1, 1, 64, h, w), generator=torch.Generator().manual_seed(args.seed), dtype=torch.float32)
+ save("noise", noise[0, 0])
+ latents = noise.view(1, 64, h * w).transpose(1, 2)
+
+ # retrieve_timesteps with the checkpoint's sigmas
+ index = json.load(open(os.path.join(args.repo, "model_index.json")))
+ scheduler = FlowMatchEulerDiscreteScheduler.from_config(
+ json.load(open(os.path.join(args.repo, "scheduler", "scheduler_config.json"))))
+ mu = calculate_shift(latents.shape[1], scheduler.config.get("base_image_seq_len", 256),
+ scheduler.config.get("max_image_seq_len", 4096), scheduler.config.get("base_shift", 0.5),
+ scheduler.config.get("max_shift", 1.15))
+ scheduler.set_timesteps(sigmas=index["sample_sigmas"], mu=mu)
+ scheduler.set_begin_index(0)
+
+ dit = ReferenceDiT(args.dit)
+ for i, t in enumerate(scheduler.timesteps):
+ velocity = dit.forward(conditioning, latents, h, w, t.expand(1).to(torch.float32) / 1000, progress=False)
+ save(f"velocity{i}", velocity[0])
+ latents = scheduler.step(velocity, t, latents, return_dict=False)[0]
+ save(f"latent{i}", latents[0])
+ print(f"step {i + 1}: t {float(t) / 1000:.6f}", flush=True)
+
+ # _unpack_latents, denormalize, decode, postprocess
+ vae = load_vae(args.vae)
+ unpacked = latents.transpose(1, 2).reshape(1, 64, 1, h, w)
+ 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(unpacked * std + mean, return_dict=False)[0][:, :, 0]
+ save("image", image[0])
+ pil = VaeImageProcessor(vae_scale_factor=16, vae_latent_channels=64).postprocess(image, output_type="pil")[0]
+ pil.save(os.path.join(args.out, "image.png"))
+ np.asarray(pil).tofile(os.path.join(args.out, "pixels.u8"))
+
+ meta = {"prompt": text_meta["prompt"], "grid": [h, w], "seed": args.seed, "mode": pil.mode,
+ "sigmas": scheduler.sigmas.tolist(), "timesteps": (scheduler.timesteps / 1000).tolist(),
+ "dit": os.path.basename(args.dit), "vae": os.path.basename(args.vae)}
+ with open(os.path.join(args.out, "meta.json"), "w") as f:
+ json.dump(meta, f, indent=1)
+ print(f"image {pil.size} {pil.mode}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/engine-mac/tools/reference_vae.py b/engine-mac/tools/reference_vae.py
index 7e641db..8498618 100644
--- a/engine-mac/tools/reference_vae.py
+++ b/engine-mac/tools/reference_vae.py
@@ -44,21 +44,12 @@ def decoder_name(key):
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)
-
+def load_vae(path):
+ """diffusers' decoder with the weights of Kokon's file (Wan 2.2 names), fp32, eval mode."""
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():
+ for key, value in load_file(path).items():
name = decoder_name(key)
if name is not None:
converted[name] = value.float().reshape(model[name].shape)
@@ -68,6 +59,21 @@ def main():
assert not missing, f"decoder weights missing: {missing[:10]}"
assert not unexpected, f"unexpected: {unexpected[:10]}"
vae.eval()
+ return vae
+
+
+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 = load_vae(args.vae)
g = args.grid
latent = torch.randn(1, 64, 1, g, g) # normalized, as the DiT produces