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 DiT on the GPU, checked against diffusers

Gabriele Lozupone485998ee9bef
diff --git a/engine-mac/README.md b/engine-mac/README.md
index 005d04b..685d8d8 100644
--- a/engine-mac/README.md
+++ b/engine-mac/README.md
@@ -23,9 +23,23 @@ swift test # no model needed
| `Kernels/dequant.metal`, `GPUDequant.swift` | the same on the GPU, to `[n, k]` or `[k, n]`, fp32 or fp16 |
| `NeuralEngine.swift` | a matrix product on the Neural Engine: a small Core ML program written at run time, weight as an input |
| `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 |
Tests check the CPU and GPU unpacking against gguf-py's values (`tools/make_quant_fixtures.py` writes the
-fixture).
+fixture), and the sequence layout against diffusers' rules worked out by hand.
+
+**The DiT against diffusers.** `tools/reference_dit.py` runs diffusers' own Qwen-Image 2.1 modules in fp32 on the
+CPU, on Kokon's GGUF weights unpacked by gguf-py, and saves every stage; `check-dit` compares the engine with it:
+
+```bash
+python3 -m venv ~/kokon-bench/venv-oracle && ~/kokon-bench/venv-oracle/bin/pip install torch diffusers transformers gguf numpy
+~/kokon-bench/venv-oracle/bin/python -I tools/reference_dit.py <dit.gguf> ~/kokon-bench/ref/dit-t2i-256 # ~30 s
+.build/release/kokon-engine-mac check-dit <dit.gguf> ~/kokon-bench/ref/dit-t2i-256
+.build/release/kokon-engine-mac time-dit <dit.gguf> 64 32 # 1024², 32 text rows, plus a profile
+```
+
+256² text-to-image, σ 0.7, 2026-10-25: every stage within 2e-5 relative of diffusers fp32 (velocity 6e-6).
## First measurements (M2 Pro 19-core GPU, 16 GB, macOS 27, 2026-10-25, `probe`)
@@ -45,5 +59,9 @@ m = 4 096 rows (a 1024² image), TFLOP/s:
- Neural Engine numbers leave out the fp32 ↔ fp16 conversions and scaling it needs; the plan is to have the
GPU write its inputs straight into the Neural Engine's buffers.
+**One DiT evaluation at 1024² (32 text rows), GPU only: 16.2 s** (sd.cpp: 27.4 s): products 11.6 s, attention
+(MPSGraph) 4.1 s, unpacking 0.2 s, the rest 0.3 s. Every product goes to MPS on a multiple of 64 rows: one product
+of 32 rows (the text projection) slowed all later ones to 18.5 s.
+
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/Arena.swift b/engine-mac/Sources/KokonEngine/Arena.swift
new file mode 100644
index 0000000..25cf348
--- /dev/null
+++ b/engine-mac/Sources/KokonEngine/Arena.swift
@@ -0,0 +1,67 @@
+import Darwin
+import Metal
+
+/// The engine's working memory: one page-aligned anonymous mapping, seen by the CPU as pointers and by the GPU
+/// as one shared buffer (no copies, unified memory). Slices start on a page, and a DiT row (4 096 floats) is
+/// exactly one 16 KB page, so any row range of a slice is page-aligned too: `view` wraps it as a buffer of its
+/// own for APIs that take no offset (MPSGraph).
+public final class Arena: @unchecked Sendable {
+ public let base: UnsafeMutableRawPointer
+ public let capacity: Int
+ public let buffer: MTLBuffer
+ private let device: MTLDevice
+ private var used = 0
+ private var views: [Int: MTLBuffer] = [:]
+ public static let page = Int(getpagesize())
+
+ public struct Slice: Sendable {
+ public let offset: Int, bytes: Int
+ public var floats: Int { bytes / 4 }
+ }
+
+ public init(device: MTLDevice, bytes: Int) throws {
+ capacity = max(Arena.page, (bytes + Arena.page - 1) / Arena.page * Arena.page)
+ guard let p = mmap(nil, capacity, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0), p != MAP_FAILED else {
+ throw MetalContext.Failure.buffer("arena of \(capacity) bytes")
+ }
+ base = p
+ guard let b = device.makeBuffer(bytesNoCopy: p, length: capacity, options: .storageModeShared, deallocator: nil) else {
+ munmap(p, capacity)
+ throw MetalContext.Failure.buffer("arena of \(capacity) bytes (over the GPU's buffer limit?)")
+ }
+ b.label = "arena"
+ buffer = b
+ self.device = device
+ }
+
+ deinit { munmap(base, capacity) }
+
+ /// Bytes a set of slices needs, each rounded to the page.
+ public static func bytes(_ sizes: [Int]) -> Int { sizes.reduce(0) { $0 + ($1 + page - 1) / page * page } }
+
+ public func slice(floats: Int) throws -> Slice {
+ let bytes = max(4, floats * 4)
+ let rounded = (bytes + Arena.page - 1) / Arena.page * Arena.page
+ guard used + rounded <= capacity else { throw MetalContext.Failure.buffer("arena full (\(capacity) bytes)") }
+ defer { used += rounded }
+ return Slice(offset: used, bytes: bytes)
+ }
+
+ public func pointer(_ s: Slice, floatOffset: Int = 0) -> UnsafeMutablePointer<Float> {
+ (base + s.offset).assumingMemoryBound(to: Float.self) + floatOffset
+ }
+
+ /// A buffer starting at `s.offset + byteOffset` (page-aligned), to the end of the slice.
+ public func view(_ s: Slice, byteOffset: Int = 0) throws -> MTLBuffer {
+ let start = s.offset + byteOffset
+ guard start % Arena.page == 0 else { throw MetalContext.Failure.buffer("view at \(start) is not page-aligned") }
+ let length = (s.offset + s.bytes - start + Arena.page - 1) / Arena.page * Arena.page
+ if let v = views[start], v.length >= length { return v }
+ guard let v = device.makeBuffer(bytesNoCopy: base + start, length: length, options: .storageModeShared,
+ deallocator: nil) else {
+ throw MetalContext.Failure.buffer("view at \(start)")
+ }
+ views[start] = v
+ return v
+ }
+}
diff --git a/engine-mac/Sources/KokonEngine/Attention.swift b/engine-mac/Sources/KokonEngine/Attention.swift
new file mode 100644
index 0000000..4a4209b
--- /dev/null
+++ b/engine-mac/Sources/KokonEngine/Attention.swift
@@ -0,0 +1,67 @@
+import Metal
+import MetalPerformanceShaders
+import MetalPerformanceShadersGraph
+
+/// Scaled dot-product attention through MPSGraph, fp32, on the layout the products write: `q` `[queries, H·D]`,
+/// `k`, `v` `[keys, H·D]`, out `[queries, H·D]`. The head transposes happen inside the graph.
+///
+/// `causal`: the queries are the last `queries` of the keys and query `i` sees keys `0 …< keys − queries + i + 1`
+/// (a text segment of Qwen-Image 2.1's block-causal mask: everything before it, plus its own triangle).
+///
+/// MPSGraph builds the whole `[H, queries, keys]` score matrix: 2.2 GB at 1024². A flash-attention kernel
+/// replaces this later (memory, and the split by heads with the CPU).
+final class GraphAttention {
+ let queries: Int, keys: Int, heads: Int, headDim: Int, causal: Bool
+ private let graph: MPSGraph
+ private let q: MPSGraphTensor, k: MPSGraphTensor, v: MPSGraphTensor, out: MPSGraphTensor
+ private let mask: (tensor: MPSGraphTensor, data: MPSGraphTensorData)?
+
+ init(device: MTLDevice, queries: Int, keys: Int, heads: Int, headDim: Int, causal: Bool) throws {
+ self.queries = queries; self.keys = keys; self.heads = heads; self.headDim = headDim; self.causal = causal
+ func n(_ x: Int) -> NSNumber { NSNumber(value: x) }
+ let graph = MPSGraph()
+ self.graph = graph
+ let q = graph.placeholder(shape: [1, n(queries), n(heads), n(headDim)], dataType: .float32, name: "q")
+ let k = graph.placeholder(shape: [1, n(keys), n(heads), n(headDim)], dataType: .float32, name: "k")
+ let v = graph.placeholder(shape: [1, n(keys), n(heads), n(headDim)], dataType: .float32, name: "v")
+ self.q = q; self.k = k; self.v = v
+ func headsFirst(_ t: MPSGraphTensor) -> MPSGraphTensor { graph.transposeTensor(t, dimension: 1, withDimension: 2, name: nil) }
+ var maskTensor: MPSGraphTensor?
+ if causal {
+ let shape: [NSNumber] = [1, 1, n(queries), n(keys)]
+ guard let buffer = device.makeBuffer(length: queries * keys * 4, options: .storageModeShared) else {
+ throw MetalContext.Failure.buffer("causal mask \(queries)×\(keys)")
+ }
+ let m = buffer.contents().assumingMemoryBound(to: Float.self)
+ let offset = keys - queries
+ for i in 0..<queries {
+ for j in 0..<keys { m[i * keys + j] = j <= offset + i ? 0 : -.infinity }
+ }
+ let t = graph.placeholder(shape: shape, dataType: .float32, name: "mask")
+ mask = (t, MPSGraphTensorData(buffer, shape: shape, dataType: .float32))
+ maskTensor = t
+ } else {
+ mask = nil
+ }
+ let attended = graph.scaledDotProductAttention(query: headsFirst(q), key: headsFirst(k), value: headsFirst(v),
+ mask: maskTensor, scale: 1 / Float(headDim).squareRoot(), name: nil)
+ out = graph.transposeTensor(attended, dimension: 1, withDimension: 2, name: nil)
+ }
+
+ /// Encodes into `commands`. Each operand is `(buffer, byte offset of its first row)`: MPSNDArrays over the
+ /// caller's own buffer, so Metal orders this work with the kernels around it. (Separate buffers aliasing
+ /// the same memory are not ordered: attention then raced the RoPE before it and the product after it.)
+ func encode(commands: MTLCommandBuffer, q qb: (MTLBuffer, Int), k kb: (MTLBuffer, Int), v vb: (MTLBuffer, Int),
+ out ob: (MTLBuffer, Int)) {
+ func data(_ b: (MTLBuffer, Int), _ rows: Int) -> MPSGraphTensorData {
+ let shape = [1, rows, heads, headDim].map { NSNumber(value: $0) }
+ let array = MPSNDArray(buffer: b.0, offset: b.1,
+ descriptor: MPSNDArrayDescriptor(dataType: .float32, shape: shape))
+ return MPSGraphTensorData(array)
+ }
+ var feeds = [q: data(qb, queries), k: data(kb, keys), v: data(vb, keys)]
+ if let mask { feeds[mask.tensor] = mask.data }
+ graph.encode(to: commands as! MPSCommandBuffer, feeds: feeds, targetOperations: nil,
+ resultsDictionary: [out: data(ob, queries)], executionDescriptor: nil)
+ }
+}
diff --git a/engine-mac/Sources/KokonEngine/Checks.swift b/engine-mac/Sources/KokonEngine/Checks.swift
index b7de312..c8352d0 100644
--- a/engine-mac/Sources/KokonEngine/Checks.swift
+++ b/engine-mac/Sources/KokonEngine/Checks.swift
@@ -48,3 +48,87 @@ public enum Checks {
}
}
}
+
+extension Checks {
+ /// Reads a reference tensor written by `tools/reference_dit.py`.
+ static func reference(_ directory: String, _ name: String) throws -> [Float] {
+ let data = try Data(contentsOf: URL(fileURLWithPath: directory).appendingPathComponent(name + ".f32"))
+ return data.withUnsafeBytes { Array($0.bindMemory(to: Float.self)) }
+ }
+
+ /// ‖a − b‖ / ‖b‖ and the largest |a − b|.
+ static func compare(_ a: UnsafePointer<Float>, _ b: [Float]) -> (relative: Double, maxAbs: Float, finite: Bool) {
+ var diff = 0.0, norm = 0.0, worst: Float = 0, finite = true
+ for i in b.indices {
+ let e = a[i] - b[i]
+ if !a[i].isFinite { finite = false }
+ diff += Double(e) * Double(e); norm += Double(b[i]) * Double(b[i]); worst = max(worst, abs(e))
+ }
+ return ((diff / max(norm, 1e-30)).squareRoot(), worst, finite)
+ }
+
+ /// One DiT evaluation against the diffusers reference in `directory` (`tools/reference_dit.py`).
+ public static func dit(path: String, reference directory: String) throws {
+ let meta = try JSONSerialization.jsonObject(with: Data(contentsOf: URL(fileURLWithPath: directory)
+ .appendingPathComponent("meta.json"))) as! [String: Any]
+ let grid = meta["grid"] as! [Int], text = meta["text"] as! Int, sigma = Float(meta["sigma"] as! Double)
+ let file = try GGUFFile(path: path)
+ let context = try MetalContext()
+ let sequence = try QwenSequence.textToImage(text: text, target: .init(height: grid[0], width: grid[1]))
+ let dit = try QwenDiT(file: file, context: context, sequence: sequence)
+ print("sequence: \(sequence.count) rows (\(sequence.prefix) prefix, \(sequence.target) target), σ = \(sigma)")
+
+ 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 rope = sequence.ropeTable()
+ rope.withUnsafeBufferPointer { report("rope", $0.baseAddress!, try! reference(directory, "rope")) }
+ let m = try dit.modulationRows(timesteps: [sigma, 0])
+ (m.temb[0] + m.temb[1]).withUnsafeBufferPointer { report("temb", $0.baseAddress!, try! reference(directory, "temb")) }
+ (m.raw[0] + m.raw[1]).withUnsafeBufferPointer { report("modulation", $0.baseAddress!, try! reference(directory, "modulation")) }
+
+ let encoder = try reference(directory, "in_encoder"), latent = try reference(directory, "in_latent")
+ _ = try dit.forward(encoder: encoder, target: latent, sigma: sigma) { name, pointer, count in
+ guard let want = try? reference(directory, name) else { return }
+ precondition(want.count == count, "\(name): \(count) floats, reference \(want.count)")
+ report(name, pointer, want)
+ }
+ // Timing without the stage waits.
+ let started = DispatchTime.now().uptimeNanoseconds
+ _ = try dit.forward(encoder: encoder, target: latent, sigma: sigma)
+ print(String(format: "evaluation: %.3f s (modulation on the CPU %.3f s)",
+ Double(DispatchTime.now().uptimeNanoseconds - started) * 1e-9, dit.timings["modulation"] ?? 0))
+ }
+}
+
+extension Checks {
+ /// Times DiT evaluations on random inputs at a `grid` × `grid` target (64 = 1024²) after `text` text rows.
+ public static func timeDiT(path: String, grid: Int, text: Int, runs: Int) throws {
+ let file = try GGUFFile(path: path)
+ let context = try MetalContext()
+ let sequence = try QwenSequence.textToImage(text: text, target: .init(height: grid, width: grid))
+ let dit = try QwenDiT(file: file, context: context, sequence: sequence)
+ var seed: UInt64 = 1
+ func random(_ n: Int, _ scale: Float) -> [Float] {
+ (0..<n).map { _ in
+ seed = seed &* 6364136223846793005 &+ 1442695040888963407
+ return (Float(seed >> 40) / Float(1 << 24) - 0.5) * scale
+ }
+ }
+ let encoder = random(text * QwenDiT.dim, 8), latent = random(sequence.target * QwenDiT.channels, 2)
+ print("sequence: \(sequence.count) rows (\(sequence.prefix) text, \(sequence.target) target)")
+ for run in 0..<runs {
+ let started = DispatchTime.now().uptimeNanoseconds
+ let out = try dit.forward(encoder: encoder, target: latent, sigma: 0.5)
+ let seconds = Double(DispatchTime.now().uptimeNanoseconds - started) * 1e-9
+ print(String(format: "evaluation %d: %.2f s%@", run + 1, seconds, out.allSatisfy(\.isFinite) ? "" : " NON-FINITE OUTPUT"))
+ }
+ dit.profiling = true
+ _ = try dit.forward(encoder: encoder, target: latent, sigma: 0.5)
+ print("profile (each operation alone, GPU seconds):")
+ for (kind, seconds) in dit.timings.sorted(by: { $0.value > $1.value }) {
+ print(String(format: " %-24@ %6.2f s", kind as NSString, seconds))
+ }
+ }
+}
diff --git a/engine-mac/Sources/KokonEngine/Kernels/dit.metal b/engine-mac/Sources/KokonEngine/Kernels/dit.metal
new file mode 100644
index 0000000..f68db79
--- /dev/null
+++ b/engine-mac/Sources/KokonEngine/Kernels/dit.metal
@@ -0,0 +1,121 @@
+#include <metal_stdlib>
+using namespace metal;
+
+// The Qwen-Image 2.1 DiT's elementwise and per-row kernels, fp32, following diffusers'
+// transformer_qwenimage21.py operation by operation (QwenDiT.swift says which module each one replaces).
+//
+// Rows are joint-sequence rows of `columns` floats. A modulated kernel reads its per-channel vector from
+// `prefixMod` for rows < `targetStart` (text and reference images read t = 0) and from `targetMod` after.
+
+constant uint ROW_THREADS = 256;
+
+struct RowParams {
+ uint columns;
+ uint targetStart;
+ float eps;
+};
+
+// Sum over the 256 threads of a threadgroup.
+static inline float row_sum(float v, threadgroup float *shared, uint tid) {
+ v = simd_sum(v);
+ if (tid % 32 == 0) shared[tid / 32] = v;
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ float total = 0;
+ for (uint i = 0; i < ROW_THREADS / 32; i++) total += shared[i];
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ return total;
+}
+
+// out = LayerNorm(x) (no affine) * onePlusScale[band]: img_norm1/2 + _modulate, norm_out.
+// One threadgroup per row.
+kernel void layernorm_modulate(device const float *x [[buffer(0)]], device float *out [[buffer(1)]],
+ device const float *prefixMod [[buffer(2)]], device const float *targetMod [[buffer(3)]],
+ constant RowParams &p [[buffer(4)]],
+ uint row [[threadgroup_position_in_grid]], uint tid [[thread_index_in_threadgroup]]) {
+ threadgroup float shared[ROW_THREADS / 32];
+ device const float *r = x + (ulong)row * p.columns;
+ float s = 0;
+ for (uint j = tid; j < p.columns; j += ROW_THREADS) s += r[j];
+ float mean = row_sum(s, shared, tid) / float(p.columns);
+ float q = 0;
+ for (uint j = tid; j < p.columns; j += ROW_THREADS) { float c = r[j] - mean; q += c * c; }
+ float inv = rsqrt(row_sum(q, shared, tid) / float(p.columns) + p.eps);
+ device const float *m = row < p.targetStart ? prefixMod : targetMod;
+ device float *o = out + (ulong)row * p.columns;
+ for (uint j = tid; j < p.columns; j += ROW_THREADS) o[j] = ((r[j] - mean) * inv) * m[j];
+}
+
+// QwenImage21ZeroCenterRMSNorm: x * rsqrt(mean(x²) + eps) * (w + 1), `onePlusWeight` precomputed.
+kernel void rmsnorm_rows(device const float *x [[buffer(0)]], device float *out [[buffer(1)]],
+ device const float *onePlusWeight [[buffer(2)]], constant RowParams &p [[buffer(3)]],
+ uint row [[threadgroup_position_in_grid]], uint tid [[thread_index_in_threadgroup]]) {
+ threadgroup float shared[ROW_THREADS / 32];
+ device const float *r = x + (ulong)row * p.columns;
+ float q = 0;
+ for (uint j = tid; j < p.columns; j += ROW_THREADS) q += r[j] * r[j];
+ float inv = rsqrt(row_sum(q, shared, tid) / float(p.columns) + p.eps);
+ device float *o = out + (ulong)row * p.columns;
+ for (uint j = tid; j < p.columns; j += ROW_THREADS) o[j] = (r[j] * inv) * onePlusWeight[j];
+}
+
+struct HeadParams {
+ uint heads;
+ uint rows;
+ float eps;
+};
+
+// attn.norm_q / norm_k (RMSNorm over head_dim 128, weight) then apply_rotary_emb_qwen(use_real=False): adjacent
+// pairs times (cos, sin) as a complex product. `rope` is [rows, 64 pairs, (cos, sin)]. One SIMD group per
+// (row, head), each thread two pairs.
+kernel void head_rmsnorm_rope(device float *x [[buffer(0)]], device const float *weight [[buffer(1)]],
+ device const float *rope [[buffer(2)]], constant HeadParams &p [[buffer(3)]],
+ uint group [[threadgroup_position_in_grid]], uint lane [[thread_index_in_simdgroup]],
+ uint simd [[simdgroup_index_in_threadgroup]], uint groups [[simdgroups_per_threadgroup]]) {
+ uint unit = group * groups + simd; // (row, head)
+ if (unit >= p.rows * p.heads) return;
+ uint row = unit / p.heads;
+ device float *h = x + (ulong)unit * 128;
+ float4 v = float4(h[lane * 2], h[lane * 2 + 1], h[64 + lane * 2], h[64 + lane * 2 + 1]);
+ float inv = rsqrt(simd_sum(dot(v, v)) / 128.0f + p.eps);
+ float4 w = float4(weight[lane * 2], weight[lane * 2 + 1], weight[64 + lane * 2], weight[64 + lane * 2 + 1]);
+ v = (v * inv) * w;
+ device const float *t = rope + (ulong)row * 128;
+ uint p0 = lane, p1 = 32 + lane; // pair indices
+ float c0 = t[p0 * 2], s0 = t[p0 * 2 + 1], c1 = t[p1 * 2], s1 = t[p1 * 2 + 1];
+ h[lane * 2] = v.x * c0 - v.y * s0;
+ h[lane * 2 + 1] = v.x * s0 + v.y * c0;
+ h[64 + lane * 2] = v.z * c1 - v.w * s1;
+ h[64 + lane * 2 + 1] = v.z * s1 + v.w * c1;
+}
+
+struct ResidualParams {
+ uint columns;
+ uint targetStart;
+ uint count;
+};
+
+// x += tanh(gate)[band] * o: the block's two residuals, `tanhGate` precomputed per band.
+kernel void gated_residual(device float *x [[buffer(0)]], device const float *o [[buffer(1)]],
+ device const float *prefixGate [[buffer(2)]], device const float *targetGate [[buffer(3)]],
+ constant ResidualParams &p [[buffer(4)]], uint i [[thread_position_in_grid]]) {
+ if (i >= p.count) return;
+ uint row = i / p.columns, j = i % p.columns;
+ float g = (row < p.targetStart ? prefixGate : targetGate)[j];
+ x[i] = x[i] + g * o[i];
+}
+
+// QwenImage21SwiGLUFeedForward: gate = SiLU(gate) * proj, in place in `gate`.
+kernel void swiglu(device float *gate [[buffer(0)]], device const float *proj [[buffer(1)]],
+ constant uint &count [[buffer(2)]], uint i [[thread_position_in_grid]]) {
+ if (i >= count) return;
+ float g = gate[i];
+ gate[i] = (g / (1.0f + exp(-g))) * proj[i];
+}
+
+// nn.GELU(approximate="tanh"), in place.
+kernel void gelu_tanh(device float *x [[buffer(0)]], constant uint &count [[buffer(1)]],
+ uint i [[thread_position_in_grid]]) {
+ if (i >= count) return;
+ float v = x[i];
+ x[i] = 0.5f * v * (1.0f + precise::tanh(0.7978845608028654f * (v + 0.044715f * v * v * v)));
+}
diff --git a/engine-mac/Sources/KokonEngine/QwenDiT.swift b/engine-mac/Sources/KokonEngine/QwenDiT.swift
new file mode 100644
index 0000000..34832f0
--- /dev/null
+++ b/engine-mac/Sources/KokonEngine/QwenDiT.swift
@@ -0,0 +1,393 @@
+import Accelerate
+import Foundation
+import Metal
+import MetalPerformanceShaders
+
+/// **The Qwen-Image 2.1 DiT** (`QwenImage21Transformer2DModel`, diffusers 0.42) on the GPU, fp32 activations, the
+/// GGUF weights unpacked on the GPU just before each product.
+///
+/// encoder rows ─ txt_in (zero-centred RMSNorm, Linear, GELU tanh, Linear) ─┐
+/// latent tokens ─ img_in ─────────────────────────────────────────────────┴ joint sequence x
+/// σ ─ sinusoid [cos | sin] ─ timestep MLP ─ temb ─ SiLU ─ modulation.1 → [scale₁, gate₁, scale₂, gate₂]
+/// └ SiLU ─ norm_out.linear → final scale
+/// 32 × { x += tanh g₁ · to_out(SDPA(RoPE(RMS(q)), RoPE(RMS(k)), v)) on LN(x)·(1 + s₁)
+/// x += tanh g₂ · out(SiLU(gate) ⊙ proj) on LN(x)·(1 + s₂) }
+/// LN(x)·(1 + s_final) ─ proj_out → velocity of the target rows
+///
+/// Text and condition images read the modulation of t = 0, the target the one of σ (`causal_condition`).
+/// Attention is block-causal: each prefix segment sees the keys before its end (a text segment with a causal
+/// triangle), the target sees every key.
+///
+/// This first version runs the full pass every evaluation (no K/V cache of the prefix yet) on the GPU alone;
+/// the AMX and the Neural Engine join in the products later.
+public final class QwenDiT {
+ public static let dim = 4096, heads = 32, headDim = 128, hidden = 12288, layers = 32, channels = 64
+ static let eps: Float = 1e-6
+ static let prefix = "model.diffusion_model."
+
+ /// **Every product is submitted on a multiple of 64 rows, at least 64.** One MPS fp32 product of 8 to 32
+ /// rows slows every later MPS product of the process: a 1024² evaluation with 32 text rows took 18.5 s of
+ /// products against 11.4–11.6 s with 0 or 64 (M2 Pro, macOS 27, `time-dit`, 2026-10-25; Siliconed found the
+ /// same on an M1 Pro). The padding rows stay zero: row kernels cover the real rows only, and the product of a
+ /// zero row is zero. Slices therefore hold `padded(rows) + 64` rows.
+ static func padded(_ rows: Int) -> Int { max(64, (rows + 63) / 64 * 64) }
+
+ public let file: GGUFFile
+ let context: MetalContext
+ let dequant: GPUDequant
+ public let sequence: QwenSequence
+ let arena: Arena
+
+ // Arena slices, rows of the joint sequence (N = prefix + target).
+ let x, normed, q, k, v, attended, o, h1, h2: Arena.Slice
+ let reserves: [Arena.Slice]
+ let rope, modulation, qkNorms, textNorm, textIn, textOut, latent, output: Arena.Slice
+ private var nextReserve = 0
+ private var products: [String: MPSMatrixMultiplication] = [:]
+ private var attentions: [String: GraphAttention] = [:]
+ /// Seconds per phase of the last evaluation.
+ public private(set) var timings: [String: Double] = [:]
+
+ public init(file: GGUFFile, context: MetalContext, sequence: QwenSequence) throws {
+ self.file = file
+ self.context = context
+ self.dequant = GPUDequant(context: context)
+ self.sequence = sequence
+ let d = QwenDiT.dim
+ let n = QwenDiT.padded(sequence.count) + 64, s = QwenDiT.padded(sequence.target) + 64
+ let t = QwenDiT.padded(sequence.textRows.count)
+ let sizes = [n * d, n * d, n * d, n * d, n * d, n * d, n * d, n * QwenDiT.hidden, n * QwenDiT.hidden,
+ d * QwenDiT.hidden, d * QwenDiT.hidden,
+ n * 128, 2 * 5 * d, QwenDiT.layers * 2 * QwenDiT.headDim, d, t * d, t * d,
+ s * QwenDiT.channels, s * QwenDiT.channels]
+ let arena = try Arena(device: context.device, bytes: Arena.bytes(sizes.map { $0 * 4 }))
+ self.arena = arena
+ var slices = try sizes.map { try arena.slice(floats: $0) }.makeIterator()
+ x = slices.next()!; normed = slices.next()!; q = slices.next()!; k = slices.next()!; v = slices.next()!
+ attended = slices.next()!; o = slices.next()!; h1 = slices.next()!; h2 = slices.next()!
+ reserves = [slices.next()!, slices.next()!]
+ rope = slices.next()!; modulation = slices.next()!; qkNorms = slices.next()!; textNorm = slices.next()!
+ textIn = slices.next()!; textOut = slices.next()!; latent = slices.next()!; output = slices.next()!
+
+ let table = sequence.ropeTable()
+ arena.pointer(rope).update(from: table, count: table.count)
+ // Small weights unpacked once on the CPU: the QK norms of every layer, txt_in's norm as (w + 1).
+ for layer in 0..<QwenDiT.layers {
+ for (i, which) in ["norm_q", "norm_k"].enumerated() {
+ let w = try Dequant.array(file, QwenDiT.prefix + "transformer_blocks.\(layer).attn.\(which).weight")
+ arena.pointer(qkNorms, floatOffset: (layer * 2 + i) * QwenDiT.headDim).update(from: w, count: QwenDiT.headDim)
+ }
+ }
+ let tn = try Dequant.array(file, QwenDiT.prefix + "txt_in.text_norm.weight")
+ for j in 0..<d { arena.pointer(textNorm)[j] = tn[j] + 1 }
+ }
+
+ // MARK: - modulation (CPU, fp32)
+
+ /// `[cos | sin]` of `1000 · t · ω_j`, `ω_j = exp(−ln(10⁴) · j / 128)`: QwenImage21TemporalTimesteps in fp32.
+ static func sinusoid(_ t: Float) -> [Float] {
+ let half = 128
+ var out = [Float](repeating: 0, count: 2 * half)
+ let scaled = 1000 * t
+ for j in 0..<half {
+ let omega = expf(-Float(log(10000.0)) * Float(j) / Float(half))
+ let angle = scaled * omega
+ out[j] = cosf(angle)
+ out[half + j] = sinf(angle)
+ }
+ return out
+ }
+
+ static func silu(_ x: [Float]) -> [Float] { x.map { $0 / (1 + expf(-$0)) } }
+
+ /// `y = W x` for a Linear weight `[out, in]` of the file, unpacked on the CPU.
+ func linearCPU(_ name: String, _ x: [Float]) throws -> [Float] {
+ let t = try file.tensor(QwenDiT.prefix + name)
+ let w = try Dequant.array(file, t.name)
+ var y = [Float](repeating: 0, count: t.rows)
+ cblas_sgemv(CblasRowMajor, CblasNoTrans, Int32(t.rows), Int32(t.columns), 1, w, Int32(t.columns), x, 1, 0, &y, 1)
+ return y
+ }
+
+ /// The temb, block modulation and final scale of each timestep, as stored for the kernels:
+ /// `[1 + s₁, tanh g₁, 1 + s₂, tanh g₂, 1 + s_final]`, `dim` floats each.
+ public func modulationRows(timesteps: [Float]) throws -> (temb: [[Float]], raw: [[Float]], stored: [[Float]]) {
+ let d = QwenDiT.dim
+ var tembs: [[Float]] = [], raws: [[Float]] = [], stored: [[Float]] = []
+ for t in timesteps {
+ let h = QwenDiT.silu(try linearCPU("time_text_embed.timestep_embedder.linear_1.weight", QwenDiT.sinusoid(t)))
+ let temb = try linearCPU("time_text_embed.timestep_embedder.linear_2.weight", h)
+ let active = QwenDiT.silu(temb)
+ let m = try linearCPU("modulation.1.weight", active)
+ let f = try linearCPU("norm_out.linear.weight", active)
+ var row = [Float](repeating: 0, count: 5 * d)
+ for j in 0..<d {
+ row[j] = 1 + m[j]
+ row[d + j] = tanhf(m[d + j])
+ row[2 * d + j] = 1 + m[2 * d + j]
+ row[3 * d + j] = tanhf(m[3 * d + j])
+ row[4 * d + j] = 1 + f[j]
+ }
+ tembs.append(temb); raws.append(m); stored.append(row)
+ }
+ return (tembs, raws, stored)
+ }
+
+ // MARK: - one evaluation
+
+ /// Called with a stage's name and its rows (CPU pointer, floats) when `probe` is set; the pass then waits on
+ /// the GPU at each stage. Stages: joint_in, layer0_out, layer1_out, layer31_out, norm_out, model_out.
+ public typealias Probe = (String, UnsafePointer<Float>, Int) -> Void
+
+ /// One evaluation: `encoder` the encoder's last layer `[T, 4096]` (all positions, image slots included),
+ /// `target` the target latent `[S, 64]` as packed tokens, `sigma` in [0, 1]. Returns the velocity `[S, 64]`.
+ public func forward(encoder: [Float], target: [Float], sigma: Float, probe: Probe? = nil) throws -> [Float] {
+ let d = QwenDiT.dim, n = sequence.count, p = sequence.prefix, s = sequence.target
+ let started = DispatchTime.now().uptimeNanoseconds
+ timings = [:]
+ let rows = try modulationRows(timesteps: [0, sigma]).stored
+ arena.pointer(modulation).update(from: rows[0] + rows[1], count: 10 * d)
+ timings["modulation"] = elapsed(since: started)
+
+ // Inputs: the text rows gathered in encoder order, the target tokens.
+ for (i, row) in sequence.textRows.enumerated() {
+ arena.pointer(textIn, floatOffset: i * d).update(from: Array(encoder[row.encoder * d..<(row.encoder + 1) * d]), count: d)
+ }
+ arena.pointer(latent).update(from: target, count: s * QwenDiT.channels)
+
+ var commands = try begin()
+ let textCount = sequence.textRows.count
+ if textCount > 0 {
+ try rmsNorm(textIn, into: textOut, rows: textCount, weight: textNorm, commands: commands)
+ try linear("txt_in.in_layer.weight", a: textOut, c: textIn, m: textCount, commands: commands)
+ try elementwise("gelu_tanh", [(textIn, 0)], count: textCount * d, commands: commands)
+ try linear("txt_in.out_layer.weight", a: textIn, c: textOut, m: textCount, commands: commands)
+ // Scatter to the joint rows, by runs.
+ let blit = commands.makeBlitCommandEncoder()!
+ var i = 0
+ while i < textCount {
+ var j = i + 1
+ while j < textCount, sequence.textRows[j].joint == sequence.textRows[j - 1].joint + 1 { j += 1 }
+ blit.copy(from: arena.buffer, sourceOffset: textOut.offset + i * d * 4, to: arena.buffer,
+ destinationOffset: x.offset + sequence.textRows[i].joint * d * 4, size: (j - i) * d * 4)
+ i = j
+ }
+ blit.endEncoding()
+ }
+ try linear("img_in.weight", a: latent, c: x, m: s, cRow: p, commands: commands)
+ if let probe { try finish(commands); probe("joint_in", arena.pointer(x), n * d); commands = try begin() }
+
+ for layer in 0..<QwenDiT.layers {
+ var stage: Stage?
+ if let probe, layer == 0 {
+ stage = { name, slice, current in
+ try self.finish(current)
+ probe("l0_" + name, self.arena.pointer(slice), n * d)
+ return try self.begin()
+ }
+ }
+ try encodeLayer(layer, commands: &commands, stage: stage)
+ if let probe, layer == 0 || layer == 1 || layer == QwenDiT.layers - 1 {
+ try finish(commands); probe("layer\(layer)_out", arena.pointer(x), n * d); commands = try begin()
+ } else {
+ commands.commit()
+ commands = try begin()
+ }
+ }
+ try layerNorm(x, into: normed, rows: n, prefixMod: 4 * d, targetMod: 5 * d + 4 * d, commands: commands)
+ if let probe { try finish(commands); probe("norm_out", arena.pointer(normed), n * d); commands = try begin() }
+ try linear("proj_out.weight", a: normed, aRow: p, c: output, m: s, commands: commands)
+ try finish(commands)
+ let out = Array(UnsafeBufferPointer(start: arena.pointer(output), count: s * QwenDiT.channels))
+ probe?("model_out", arena.pointer(output), s * QwenDiT.channels)
+ timings["total"] = elapsed(since: started)
+ return out
+ }
+
+ /// One block on all rows of `x`.
+ /// A probe point inside a layer: finishes the command buffer, reads, returns the next one.
+ typealias Stage = (String, Arena.Slice, MTLCommandBuffer) throws -> MTLCommandBuffer
+
+ func encodeLayer(_ layer: Int, commands: inout MTLCommandBuffer, stage: Stage? = nil) throws {
+ func mark(_ name: String, _ slice: Arena.Slice) throws {
+ if let stage { commands = try stage(name, slice, commands) }
+ }
+ let d = QwenDiT.dim, n = sequence.count, p = sequence.prefix
+ let block = "transformer_blocks.\(layer)."
+ let band = 5 * d // the target's modulation row follows the prefix's
+ try layerNorm(x, into: normed, rows: n, prefixMod: 0, targetMod: band, commands: commands)
+ try linear(block + "attn.to_q.weight", a: normed, c: q, m: n, commands: commands)
+ try linear(block + "attn.to_k.weight", a: normed, c: k, m: n, commands: commands)
+ try mark("norm1", normed)
+ try linear(block + "attn.to_v.weight", a: normed, c: v, m: n, commands: commands)
+ try headNormRope(q, weightOffset: (layer * 2) * QwenDiT.headDim, rows: n, commands: commands)
+ try headNormRope(k, weightOffset: (layer * 2 + 1) * QwenDiT.headDim, rows: n, commands: commands)
+ try mark("q", q); try mark("k", k); try mark("v", v)
+ for segment in sequence.segments {
+ try attend(queries: segment.start, count: segment.end - segment.start, keys: segment.end,
+ causal: segment.isText, commands: commands)
+ }
+ try attend(queries: p, count: n - p, keys: n, causal: false, commands: commands)
+ try linear(block + "attn.to_out.0.weight", a: attended, c: o, m: n, commands: commands)
+ try mark("attn_out", o)
+ try residual(gate: d, rows: n, commands: commands)
+ try mark("res1", x)
+ try layerNorm(x, into: normed, rows: n, prefixMod: 2 * d, targetMod: band + 2 * d, commands: commands)
+ try mark("norm2", normed)
+ try linear(block + "img_mlp.gate_layer.weight", a: normed, c: h1, m: n, commands: commands)
+ try linear(block + "img_mlp.proj.weight", a: normed, c: h2, m: n, commands: commands)
+ try elementwise("swiglu", [(h1, 0), (h2, 0)], count: n * QwenDiT.hidden, commands: commands)
+ try linear(block + "img_mlp.out.weight", a: h1, c: o, m: n, commands: commands)
+ try mark("mlp", o)
+ try residual(gate: 3 * d, rows: n, commands: commands)
+ }
+
+ // MARK: - encoders
+
+ /// When set, every operation runs in a command buffer of its own and its GPU time is added to `timings`
+ /// under its kind (slower overall: the GPU idles between operations).
+ public var profiling = false
+
+ /// Encodes `body` into `commands`, or, when profiling, into its own command buffer, timed.
+ func gpu(_ kind: String, _ commands: MTLCommandBuffer, _ body: (MTLCommandBuffer) throws -> Void) throws {
+ guard profiling else { return try body(commands) }
+ let own = try begin()
+ try body(own)
+ timings["gpu " + kind, default: 0] += try MetalContext.finish(own, kind)
+ }
+
+ func begin() throws -> MTLCommandBuffer {
+ MPSCommandBuffer(from: context.queue)
+ }
+
+ func finish(_ commands: MTLCommandBuffer) throws {
+ try MetalContext.finish(commands, "DiT")
+ }
+
+ func elapsed(since start: UInt64) -> Double { Double(DispatchTime.now().uptimeNanoseconds - start) * 1e-9 }
+
+ /// `C[m, n] = A[m, k] · W` with W the file's Linear `[n, k]`, unpacked to `[k, n]` fp32 in a reserve first.
+ /// `aRow`, `cRow`: first row of A and C in their slices.
+ func linear(_ name: String, a: Arena.Slice, aRow: Int = 0, c: Arena.Slice, m: Int, cRow: Int = 0,
+ commands: MTLCommandBuffer) throws {
+ let tensor = try file.tensor(QwenDiT.prefix + name)
+ let (kk, nn) = (tensor.columns, tensor.rows)
+ let m = QwenDiT.padded(m)
+ guard (aRow + m) * kk * 4 <= a.bytes, (cRow + m) * nn * 4 <= c.bytes else {
+ throw MetalContext.Failure.buffer("\(name): no room for \(m) padded rows")
+ }
+ let reserve = reserves[nextReserve]
+ nextReserve = (nextReserve + 1) % reserves.count
+ try gpu("dequant", commands) {
+ try dequant.encode(tensor, of: file, into: arena.buffer, outOffset: reserve.offset, transposed: true, commands: $0)
+ }
+ let key = "\(m)×\(kk)×\(nn)"
+ let product: MPSMatrixMultiplication
+ if let existing = products[key] { product = existing } else {
+ product = MPSMatrixMultiplication(device: context.device, transposeLeft: false, transposeRight: false,
+ resultRows: m, resultColumns: nn, interiorColumns: kk, alpha: 1, beta: 0)
+ products[key] = product
+ }
+ let left = MPSMatrix(buffer: arena.buffer, offset: a.offset + aRow * kk * 4,
+ descriptor: MPSMatrixDescriptor(rows: m, columns: kk, rowBytes: kk * 4, dataType: .float32))
+ let right = MPSMatrix(buffer: arena.buffer, offset: reserve.offset,
+ descriptor: MPSMatrixDescriptor(rows: kk, columns: nn, rowBytes: nn * 4, dataType: .float32))
+ let result = MPSMatrix(buffer: arena.buffer, offset: c.offset + cRow * nn * 4,
+ descriptor: MPSMatrixDescriptor(rows: m, columns: nn, rowBytes: nn * 4, dataType: .float32))
+ try gpu(m < 512 ? "products (few rows)" : "products", commands) {
+ product.encode(commandBuffer: $0, leftMatrix: left, rightMatrix: right, resultMatrix: result)
+ }
+ }
+
+ func compute(_ name: String, commands: MTLCommandBuffer, _ body: (MTLComputeCommandEncoder) throws -> Void) throws {
+ try gpu(name, commands) { commands in
+ let encoder = commands.makeComputeCommandEncoder()!
+ encoder.label = name
+ encoder.setComputePipelineState(try context.pipeline(name))
+ try body(encoder)
+ encoder.endEncoding()
+ }
+ }
+
+ struct RowParams { var columns: UInt32; var targetStart: UInt32; var eps: Float }
+ struct HeadParams { var heads: UInt32; var rows: UInt32; var eps: Float }
+ struct ResidualParams { var columns: UInt32; var targetStart: UInt32; var count: UInt32 }
+
+ /// `out = LN(x) · mod[band]`, `prefixMod` / `targetMod` floats into the modulation slice.
+ func layerNorm(_ input: Arena.Slice, into out: Arena.Slice, rows: Int, prefixMod: Int, targetMod: Int,
+ commands: MTLCommandBuffer) throws {
+ try compute("layernorm_modulate", commands: commands) { e in
+ e.setBuffer(arena.buffer, offset: input.offset, index: 0)
+ e.setBuffer(arena.buffer, offset: out.offset, index: 1)
+ e.setBuffer(arena.buffer, offset: modulation.offset + prefixMod * 4, index: 2)
+ e.setBuffer(arena.buffer, offset: modulation.offset + targetMod * 4, index: 3)
+ var params = RowParams(columns: UInt32(QwenDiT.dim), targetStart: UInt32(sequence.prefix), eps: QwenDiT.eps)
+ e.setBytes(&params, length: MemoryLayout<RowParams>.stride, index: 4)
+ e.dispatchThreadgroups(MTLSize(width: rows, height: 1, depth: 1), threadsPerThreadgroup: MTLSize(width: 256, height: 1, depth: 1))
+ }
+ }
+
+ func rmsNorm(_ input: Arena.Slice, into out: Arena.Slice, rows: Int, weight: Arena.Slice, commands: MTLCommandBuffer) throws {
+ try compute("rmsnorm_rows", commands: commands) { e in
+ e.setBuffer(arena.buffer, offset: input.offset, index: 0)
+ e.setBuffer(arena.buffer, offset: out.offset, index: 1)
+ e.setBuffer(arena.buffer, offset: weight.offset, index: 2)
+ var params = RowParams(columns: UInt32(QwenDiT.dim), targetStart: 0, eps: QwenDiT.eps)
+ e.setBytes(&params, length: MemoryLayout<RowParams>.stride, index: 3)
+ e.dispatchThreadgroups(MTLSize(width: rows, height: 1, depth: 1), threadsPerThreadgroup: MTLSize(width: 256, height: 1, depth: 1))
+ }
+ }
+
+ func headNormRope(_ tensor: Arena.Slice, weightOffset: Int, rows: Int, commands: MTLCommandBuffer) throws {
+ try compute("head_rmsnorm_rope", commands: commands) { e in
+ e.setBuffer(arena.buffer, offset: tensor.offset, index: 0)
+ e.setBuffer(arena.buffer, offset: qkNorms.offset + weightOffset * 4, index: 1)
+ e.setBuffer(arena.buffer, offset: rope.offset, index: 2)
+ var params = HeadParams(heads: UInt32(QwenDiT.heads), rows: UInt32(rows), eps: QwenDiT.eps)
+ e.setBytes(&params, length: MemoryLayout<HeadParams>.stride, index: 3)
+ let units = rows * QwenDiT.heads // one SIMD group each, 8 per threadgroup
+ e.dispatchThreadgroups(MTLSize(width: (units + 7) / 8, height: 1, depth: 1),
+ threadsPerThreadgroup: MTLSize(width: 256, height: 1, depth: 1))
+ }
+ }
+
+ /// `x += tanh(gate) · o`, the gate `gate` floats into each band's modulation row.
+ func residual(gate: Int, rows: Int, commands: MTLCommandBuffer) throws {
+ let d = QwenDiT.dim
+ try compute("gated_residual", commands: commands) { e in
+ e.setBuffer(arena.buffer, offset: x.offset, index: 0)
+ e.setBuffer(arena.buffer, offset: o.offset, index: 1)
+ e.setBuffer(arena.buffer, offset: modulation.offset + gate * 4, index: 2)
+ e.setBuffer(arena.buffer, offset: modulation.offset + (5 * d + gate) * 4, index: 3)
+ var params = ResidualParams(columns: UInt32(d), targetStart: UInt32(sequence.prefix), count: UInt32(rows * d))
+ e.setBytes(&params, length: MemoryLayout<ResidualParams>.stride, index: 4)
+ e.dispatchThreads(MTLSize(width: rows * d, height: 1, depth: 1), threadsPerThreadgroup: MTLSize(width: 256, height: 1, depth: 1))
+ }
+ }
+
+ func elementwise(_ name: String, _ buffers: [(Arena.Slice, Int)], count: Int, commands: MTLCommandBuffer) throws {
+ try compute(name, commands: commands) { e in
+ for (i, (slice, offset)) in buffers.enumerated() { e.setBuffer(arena.buffer, offset: slice.offset + offset * 4, index: i) }
+ var c = UInt32(count)
+ e.setBytes(&c, length: 4, index: buffers.count)
+ e.dispatchThreads(MTLSize(width: count, height: 1, depth: 1), threadsPerThreadgroup: MTLSize(width: 256, height: 1, depth: 1))
+ }
+ }
+
+ /// Queries `[queries, queries + count)` against keys `[0, keys)`, into the same rows of `attended`.
+ func attend(queries: Int, count: Int, keys: Int, causal: Bool, commands: MTLCommandBuffer) throws {
+ let key = "\(count)×\(keys)\(causal ? "c" : "")"
+ let attention: GraphAttention
+ if let a = attentions[key] { attention = a } else {
+ attention = try GraphAttention(device: context.device, queries: count, keys: keys, heads: QwenDiT.heads,
+ headDim: QwenDiT.headDim, causal: causal)
+ attentions[key] = attention
+ }
+ let row = QwenDiT.dim * 4
+ let b = arena.buffer
+ try gpu("attention", commands) {
+ attention.encode(commands: $0, q: (b, q.offset + queries * row), k: (b, k.offset), v: (b, v.offset),
+ out: (b, attended.offset + queries * row))
+ }
+ }
+}
diff --git a/engine-mac/Sources/KokonEngine/QwenSequence.swift b/engine-mac/Sources/KokonEngine/QwenSequence.swift
new file mode 100644
index 0000000..77664fc
--- /dev/null
+++ b/engine-mac/Sources/KokonEngine/QwenSequence.swift
@@ -0,0 +1,120 @@
+import Foundation
+
+/// **Qwen-Image 2.1's joint sequence**, as `QwenImage21Transformer2DModel.forward` builds it (diffusers 0.42): the
+/// encoder's positions in order, each image slot standing for 2×2 latent tokens (so 4 rows), the target's slots
+/// appended. Image tokens fill their rows row-major, conditions first, the target last.
+public struct QwenSequence: Sendable, Equatable {
+ public struct Grid: Sendable, Equatable { public let height, width: Int
+ public init(height: Int, width: Int) { self.height = height; self.width = width }
+ public var tokens: Int { height * width }
+ }
+ /// A run of prefix rows with the same image id: text (causal) or one condition image (bidirectional).
+ public struct Segment: Sendable, Equatable { public let start, end: Int; public let isText: Bool }
+
+ public let images: [Grid]
+ /// Per joint row: -1 for text, else the image's index (`image_ids`).
+ public let imageIds: [Int]
+ /// The joint row of each text row, in encoder order, with its encoder row.
+ public let textRows: [(joint: Int, encoder: Int)]
+ /// First joint row of each image.
+ public let blockStarts: [Int]
+ public let segments: [Segment]
+ /// (frame, height, width) RoPE positions per joint row.
+ public let positions: [(Int, Int, Int)]
+
+ public var count: Int { imageIds.count }
+ public var target: Int { images.last!.tokens }
+ public var prefix: Int { count - target }
+
+ public static func == (a: QwenSequence, b: QwenSequence) -> Bool {
+ a.images == b.images && a.imageIds == b.imageIds && a.blockStarts == b.blockStarts && a.segments == b.segments
+ }
+
+ public enum Failure: Error, CustomStringConvertible {
+ case layout(String)
+ public var description: String { if case .layout(let s) = self { return "sequence: \(s)" }; return "" }
+ }
+
+ /// Text to image: `text` encoder rows, then the target.
+ public static func textToImage(text: Int, target: Grid) throws -> QwenSequence {
+ try QwenSequence(slots: [Bool](repeating: false, count: text) + [Bool](repeating: true, count: target.tokens / 4),
+ images: [target])
+ }
+
+ /// `slots`: the encoder's image-slot mask with the target's slots appended; `images`: conditions, then target.
+ public init(slots: [Bool], images: [Grid]) throws {
+ guard let last = images.last else { throw Failure.layout("no target image") }
+ guard images.allSatisfy({ $0.tokens % 4 == 0 }) else { throw Failure.layout("an image grid is not a multiple of 4 tokens") }
+ guard 4 * slots.filter({ $0 }).count == images.reduce(0, { $0 + $1.tokens }) else {
+ throw Failure.layout("\(slots.filter { $0 }.count) slots for \(images.reduce(0) { $0 + $1.tokens }) image tokens")
+ }
+ guard slots.suffix(last.tokens / 4).allSatisfy({ $0 }) else { throw Failure.layout("the target's slots are not last") }
+ self.images = images
+ var isImage: [Bool] = []
+ var text: [(Int, Int)] = []
+ for (position, slot) in slots.enumerated() {
+ if slot { isImage += [true, true, true, true] } else { text.append((isImage.count, position)); isImage.append(false) }
+ }
+ textRows = text
+ // Image ids from the token counts, not from runs of slots: two adjacent images stay two blocks.
+ var ids = [Int](repeating: -1, count: isImage.count), starts: [Int] = []
+ var block = 0, used = 0
+ for row in isImage.indices where isImage[row] {
+ if used == 0 { starts.append(row) }
+ ids[row] = block
+ used += 1
+ if used == images[block].tokens { block += 1; used = 0 }
+ }
+ imageIds = ids
+ blockStarts = starts
+ for (i, s) in starts.enumerated() where !(s..<(s + images[i].tokens)).allSatisfy({ ids[$0] == i }) {
+ throw Failure.layout("image \(i) is not contiguous")
+ }
+ let prefix = isImage.count - last.tokens
+ var segments: [Segment] = []
+ var start = 0
+ if prefix > 0 {
+ for index in 1...prefix where index == prefix || ids[index] != ids[start] {
+ segments.append(Segment(start: start, end: index, isText: ids[start] < 0))
+ start = index
+ }
+ }
+ self.segments = segments
+ // QwenImage21Rope.forward: text advances one position on all axes; an image freezes the frame at the
+ // current position, centres (y, x) on zero, then advances it by max(h, w).
+ var positions = [(Int, Int, Int)](repeating: (0, 0, 0), count: isImage.count)
+ var cursor = 0, p = 0
+ for (i, grid) in images.enumerated() {
+ for row in cursor..<starts[i] { positions[row] = (p, p, p); p += 1 }
+ let (h, w) = (grid.height, grid.width)
+ for y in 0..<h {
+ for x in 0..<w { positions[starts[i] + y * w + x] = (p, y - (h - h / 2), x - (w - w / 2)) }
+ }
+ cursor = starts[i] + h * w
+ p += max(h, w)
+ }
+ for row in cursor..<isImage.count { positions[row] = (p, p, p); p += 1 }
+ self.positions = positions
+ }
+
+ /// The RoPE table `[rows, 64 pairs, (cos, sin)]`: pairs `[frame 8 | height 28 | width 28]`,
+ /// `ω_i = 1 / θ^(2i / dim)` and `angle = position · ω_i`, in fp32 as `QwenImage21Rope.rope_params` computes them.
+ public func ropeTable(axes: [Int] = [16, 56, 56], theta: Float = 10000) -> [Float] {
+ let omegas = axes.map { dim in (0..<(dim / 2)).map { i in 1 / powf(theta, Float(2 * i) / Float(dim)) } }
+ let pairs = axes.reduce(0, +) / 2
+ var out = [Float](repeating: 0, count: count * pairs * 2)
+ for (row, position) in positions.enumerated() {
+ let axisPositions = [position.0, position.1, position.2]
+ var j = 0
+ for (axis, omega) in omegas.enumerated() {
+ for w in omega {
+ let angle = Float(axisPositions[axis]) * w
+ out[(row * pairs + j) * 2] = cosf(angle)
+ out[(row * pairs + j) * 2 + 1] = sinf(angle)
+ j += 1
+ }
+ }
+ }
+ return out
+ }
+}
diff --git a/engine-mac/Sources/kokon-engine-mac/main.swift b/engine-mac/Sources/kokon-engine-mac/main.swift
index 68caecb..b905c20 100644
--- a/engine-mac/Sources/kokon-engine-mac/main.swift
+++ b/engine-mac/Sources/kokon-engine-mac/main.swift
@@ -6,6 +6,8 @@ kokon-engine-mac: Kokon's Apple Silicon engine (in development)
inspect <file.gguf> tensor types and shapes
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²)
probe this Mac's matrix throughput: GPU, AMX, Neural Engine, together
"""
@@ -36,6 +38,14 @@ do {
case "check-dequant":
guard arguments.count >= 2 else { fail(usage) }
try Checks.dequant(path: arguments[1], names: Array(arguments.dropFirst(2)))
+ case "check-dit":
+ guard arguments.count == 3 else { fail(usage) }
+ try Checks.dit(path: arguments[1], reference: arguments[2])
+ case "time-dit":
+ guard arguments.count >= 2 else { fail(usage) }
+ let numbers = arguments.dropFirst(2).compactMap { Int($0) }
+ try Checks.timeDiT(path: arguments[1], grid: numbers.first ?? 64, text: numbers.dropFirst().first ?? 32,
+ runs: numbers.dropFirst(2).first ?? 3)
case "probe":
try Probe.run()
default:
diff --git a/engine-mac/Tests/KokonEngineTests/QwenSequenceTests.swift b/engine-mac/Tests/KokonEngineTests/QwenSequenceTests.swift
new file mode 100644
index 0000000..fffc0d0
--- /dev/null
+++ b/engine-mac/Tests/KokonEngineTests/QwenSequenceTests.swift
@@ -0,0 +1,61 @@
+import XCTest
+@testable import KokonEngine
+
+/// The joint sequence and its RoPE positions, worked out by hand from diffusers 0.42
+/// (`build_token_metadata`, `_qwenimage21_prefix_segments`, `QwenImage21Rope.forward`).
+final class QwenSequenceTests: XCTestCase {
+ func testTextToImage() throws {
+ let s = try QwenSequence.textToImage(text: 3, target: .init(height: 2, width: 4))
+ XCTAssertEqual(s.count, 11)
+ XCTAssertEqual(s.prefix, 3)
+ XCTAssertEqual(s.target, 8)
+ XCTAssertEqual(s.segments, [.init(start: 0, end: 3, isText: true)])
+ XCTAssertEqual(s.blockStarts, [3])
+ XCTAssertEqual(s.textRows.map(\.joint), [0, 1, 2])
+ let expected: [(Int, Int, Int)] = [(0, 0, 0), (1, 1, 1), (2, 2, 2),
+ (3, -1, -2), (3, -1, -1), (3, -1, 0), (3, -1, 1),
+ (3, 0, -2), (3, 0, -1), (3, 0, 0), (3, 0, 1)]
+ XCTAssertEqual(s.positions.map { [$0.0, $0.1, $0.2] }, expected.map { [$0.0, $0.1, $0.2] })
+ }
+
+ /// Two text positions, a 2×2 reference (one slot), one text position, the 2×2 target.
+ func testEditLayout() throws {
+ let s = try QwenSequence(slots: [false, false, true, false, true],
+ images: [.init(height: 2, width: 2), .init(height: 2, width: 2)])
+ XCTAssertEqual(s.count, 11)
+ XCTAssertEqual(s.imageIds, [-1, -1, 0, 0, 0, 0, -1, 1, 1, 1, 1])
+ XCTAssertEqual(s.blockStarts, [2, 7])
+ XCTAssertEqual(s.prefix, 7)
+ XCTAssertEqual(s.segments, [.init(start: 0, end: 2, isText: true), .init(start: 2, end: 6, isText: false),
+ .init(start: 6, end: 7, isText: true)])
+ XCTAssertEqual(s.textRows.map { [$0.joint, $0.encoder] }, [[0, 0], [1, 1], [6, 3]])
+ let expected = [[0, 0, 0], [1, 1, 1], [2, -1, -1], [2, -1, 0], [2, 0, -1], [2, 0, 0], [4, 4, 4],
+ [5, -1, -1], [5, -1, 0], [5, 0, -1], [5, 0, 0]]
+ XCTAssertEqual(s.positions.map { [$0.0, $0.1, $0.2] }, expected)
+ }
+
+ /// Two adjacent references stay two blocks (ids from token counts, not from runs of slots).
+ func testAdjacentReferencesStayTwoBlocks() throws {
+ let s = try QwenSequence(slots: [false, true, true, true],
+ images: [.init(height: 2, width: 2), .init(height: 2, width: 2), .init(height: 2, width: 2)])
+ XCTAssertEqual(s.segments.map { [$0.start, $0.end] }, [[0, 1], [1, 5], [5, 9]])
+ XCTAssertEqual(s.blockStarts, [1, 5, 9])
+ }
+
+ func testRefusesBadLayouts() {
+ XCTAssertThrowsError(try QwenSequence(slots: [false, true], images: [.init(height: 4, width: 4)]))
+ XCTAssertThrowsError(try QwenSequence(slots: [true, false], images: [.init(height: 2, width: 2)]))
+ }
+
+ /// Row 0 at position 0 is (cos 0, sin 0) = (1, 0) on every pair; a row's pairs follow ω = 1/θ^(2i/dim).
+ func testRopeTable() throws {
+ let s = try QwenSequence.textToImage(text: 2, target: .init(height: 2, width: 2))
+ let table = s.ropeTable()
+ XCTAssertEqual(table.count, s.count * 128)
+ for j in 0..<64 { XCTAssertEqual(table[2 * j], 1); XCTAssertEqual(table[2 * j + 1], 0) }
+ // Row 1 is position (1, 1, 1): pair 1 of the frame axis (dim 16) has ω = 1/10000^(2/16).
+ let omega = 1 / powf(10000, 2.0 / 16.0)
+ XCTAssertEqual(table[128 + 2], cosf(omega), accuracy: 1e-7)
+ XCTAssertEqual(table[128 + 3], sinf(omega), accuracy: 1e-7)
+ }
+}
diff --git a/engine-mac/tools/reference_dit.py b/engine-mac/tools/reference_dit.py
new file mode 100644
index 0000000..e1a58e4
--- /dev/null
+++ b/engine-mac/tools/reference_dit.py
@@ -0,0 +1,168 @@
+"""The Qwen-Image 2.1 DiT reference for the Mac engine: diffusers' own modules, in fp32 on the CPU, on the
+weights of Kokon's GGUF unpacked by gguf-py. One evaluation of a text-to-image case (text prefix, target image),
+every stage saved for `kokon-engine-mac check-dit` to compare against.
+
+The whole model in fp32 is 28 GB, more than a 16 GB Mac holds: the script follows
+`QwenImage21Transformer2DModel.forward` step by step (diffusers 0.42, default `QwenImage21AttnProcessor`, no KV
+cache) with one block module whose weights are swapped layer by layer.
+
+ python -I engine-mac/tools/reference_dit.py <dit.gguf> <out dir> [--grid 16] [--text 24] [--sigma 0.7]
+
+Writes `<out>/meta.json` and one raw little-endian fp32 file per tensor (`<name>.f32`).
+"""
+import argparse
+import json
+import math
+import os
+
+import gguf
+import numpy as np
+import torch
+from diffusers.models.transformers.transformer_qwenimage21 import (
+ QwenImage21AdaLayerNormContinuous,
+ QwenImage21Rope,
+ QwenImage21TextProjection,
+ QwenImage21TimestepProjEmbeddings,
+ QwenImage21Transformer2DModel,
+ QwenImage21TransformerBlock,
+ _qwenimage21_prefix_segments,
+)
+
+PREFIX = "model.diffusion_model."
+
+
+class Weights:
+ def __init__(self, path):
+ self.reader = gguf.GGUFReader(path)
+ self.tensors = {t.name.removeprefix(PREFIX): t for t in self.reader.tensors}
+
+ def get(self, name):
+ t = self.tensors[name]
+ values = gguf.quants.dequantize(t.data, t.tensor_type).astype(np.float32)
+ shape = [int(d) for d in reversed(t.shape)] # ggml ne order -> torch order
+ return torch.from_numpy(values.reshape(shape).copy())
+
+ def load(self, module, prefix):
+ state = {name: self.get(prefix + name) for name, _ in module.named_parameters()}
+ module.load_state_dict(state, strict=True)
+
+
+def layer0_stages(block, x, modulation, rotary_emb, target_token_mask, save):
+ """QwenImage21TransformerBlock.forward and its processor, unrolled, saving each stage (t2i: one text segment)."""
+ from diffusers.models.transformers.transformer_qwenimage21 import apply_rotary_emb_qwen
+ mod1, mod2 = modulation.chunk(2, dim=-1)
+ normed, gate1 = block._modulate(block.img_norm1(x), mod1, target_token_mask)
+ save("l0_norm1", normed[0])
+ attn = block.attn
+ q = attn.norm_q(attn.to_q(normed).unflatten(-1, (-1, 128)))
+ k = attn.norm_k(attn.to_k(normed).unflatten(-1, (-1, 128)))
+ v = attn.to_v(normed).unflatten(-1, (-1, 128))
+ q = apply_rotary_emb_qwen(q, rotary_emb, use_real=False)
+ k = apply_rotary_emb_qwen(k, rotary_emb, use_real=False)
+ save("l0_q", q[0].flatten(1))
+ save("l0_k", k[0].flatten(1))
+ save("l0_v", v[0].flatten(1))
+ out = attn(hidden_states=normed, rotary_emb=rotary_emb,
+ segments=[(0, int((~target_token_mask).sum()), True)])
+ save("l0_attn_out", out[0])
+ x = x + gate1.tanh() * out
+ save("l0_res1", x[0])
+ normed2, gate2 = block._modulate(block.img_norm2(x), mod2, target_token_mask)
+ save("l0_norm2", normed2[0])
+ save("l0_mlp", block.img_mlp(normed2)[0])
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument("gguf")
+ parser.add_argument("out")
+ parser.add_argument("--grid", type=int, default=16, help="target latent grid side (16 = a 256² image)")
+ parser.add_argument("--text", type=int, default=24, help="text tokens of the prefix")
+ parser.add_argument("--sigma", type=float, default=0.7)
+ parser.add_argument("--layers", type=int, default=32)
+ parser.add_argument("--seed", type=int, default=42)
+ args = parser.parse_args()
+ 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 = {}
+
+ def save(name, tensor):
+ array = tensor.detach().to(torch.float32).contiguous().numpy()
+ array.tofile(os.path.join(args.out, name + ".f32"))
+ saved[name] = list(array.shape)
+
+ # 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)
+ 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,
+ "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:
+ json.dump(meta, f, indent=1)
+
+
+if __name__ == "__main__":
+ main()