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.
TypeScript ai-photo-editorcomfyui-alternativegenerative-fillimage-editingimage-generationinpaintinglinuxlocal-aimacosmcpmcp-servernano-banana-alternativeofflinephoto-editorprivacyqwen-imageqwen-image-2-1stable-diffusion-cppvulkanwindows
Mac engine: VAE mid stage as operations, compiled operations shared by every instance
Gabriele Lozupone9460753636ce
diff --git a/engine-mac/README.md b/engine-mac/README.mdindex f0d8a2a..866e37b 100644--- a/engine-mac/README.md+++ b/engine-mac/README.md@@ -504,6 +504,15 @@ reach: the result is the whole graph's (1.2e-7; a 2-pixel halo is 17 levels off)| operations, tiles of 144 | 3.9 s | 1.47 GB | 3.85 GB || graphs per block, every block tiled | 3.45 s | 3.8–5 GB | 6.25 GB |+**The mid stage as operations too, the compiled operations shared by every instance** (2026-10-26; `KOKON_VAE_MID_OPS=0`+for the graph): below 32 GB the pipeline makes a new VAE for each image, which converted its ~260 M weights bf16 → fp32+one value at a time and compiled every graph again (the mid stage's with its ~54 M weights as constants). Now the weights+are widened 8 at a time on every core straight into their buffers, the convolution and attention graphs (weights as+inputs) are cached across instances, and the mid stage runs as the up blocks do (its one-head attention a graph of its+own). `time-vae` at 1024², M2 Pro: a new instance's decode 3.9–4.1 → 3.1 s, the first 4.2 → 3.2, the next ones 3.05+either way (the up blocks run at the GPU's fp32 rate, ~16 TFLOP in ~3 s), 1.67 → 1.52 GB kept after it, peak 4.6 → 4.5.+`check-vae` against diffusers: 1.11e-5 at 256² (graph mid stage 1.04e-5), 1.37e-5 at 768², 1 level off at most.+The untiled peak grows with the image; the tiles keep it bounded. Buffers the GPU used leave the footprint up to a secondafter their release (`time-vae` waits 1.5 s). `KOKON_VAE_OPS=0`, `KOKON_VAE_SPLIT`, `KOKON_VAE_TILES` to compare.fp16 up blocks (norms and the mid block kept fp32) are wrong (2.7e-1) and 3–11× slower only when MPSGraph may placediff --git a/engine-mac/Sources/KokonEngine/Checks.swift b/engine-mac/Sources/KokonEngine/Checks.swiftindex 74c885a..1ff4465 100644--- a/engine-mac/Sources/KokonEngine/Checks.swift+++ b/engine-mac/Sources/KokonEngine/Checks.swift@@ -246,17 +246,20 @@ extension Checks {/// first decode with its graph builds, then two more; the footprint 1.5 s after each, and the process's peak.public static func timeVAE(path: String, grid: Int) throws {let context = try MetalContext()- let vae = try QwenVAE(path: path, context: context)+ var vae = try QwenVAE(path: path, context: context)let random = (0..<(64 * grid * grid)).map { Float(($0 * 7919) % 1000) / 500 - 1 }print("VAE \(grid * 16)² in \(tiles(vae, grid, grid)), \(String(format: "footprint %.2f GB", MemoryUsage.now().footprint))")- for run in 0..<3 {+ for run in 0..<4 {+ // The last one on a new instance, as the pipeline decodes below 32 GB (weights read, graphs compiled again).+ if run == 3 { vae = try QwenVAE(path: path, context: context) }let started = DispatchTime.now().uptimeNanosecondstry autoreleasepool { _ = try vae.decode(random, height: grid, width: grid) }let seconds = Double(DispatchTime.now().uptimeNanoseconds - started) * 1e-9// Buffers the GPU used leave the footprint within a second of their release.Thread.sleep(forTimeInterval: 1.5)let m = MemoryUsage.now()- print(String(format: "decode %d: %.2f s, then footprint %.2f GB (peak %.2f GB)", run + 1, seconds, m.footprint, m.footprintPeak))+ print(String(format: "decode %d%@: %.2f s, then footprint %.2f GB (peak %.2f GB)", run + 1, run == 3 ? " (new instance)" : "",+ seconds, m.footprint, m.footprintPeak))}}}diff --git a/engine-mac/Sources/KokonEngine/Kernels/vae.metal b/engine-mac/Sources/KokonEngine/Kernels/vae.metalindex e483980..4a947bb 100644--- a/engine-mac/Sources/KokonEngine/Kernels/vae.metal+++ b/engine-mac/Sources/KokonEngine/Kernels/vae.metal@@ -70,3 +70,26 @@ kernel void vae_avg_down_add(device float *out [[buffer(0)]], device const float}out[(ulong(gid.z) * p.h + gid.y) * p.w + gid.x] += sum / float(group);}++/// QwenImage21RMS_norm alone (the attention block's), one pixel a thread: x / max(‖x‖, 1e-12) · √C · γ.+kernel void vae_norm(device const float *x [[buffer(0)]], device float *out [[buffer(1)]],+ device const float *gamma [[buffer(2)]], constant uint2 &p [[buffer(3)]],+ uint i [[thread_position_in_grid]]) {+ if (i >= p.y) return;+ float sum = 0;+ for (uint c = 0; c < p.x; c++) { float v = x[ulong(c) * p.y + i]; sum += v * v; }+ float scale = sqrt(float(p.x)) / max(sqrt(sum), 1e-12f);+ for (uint c = 0; c < p.x; c++) {+ ulong at = ulong(c) * p.y + i;+ out[at] = x[at] * scale * gamma[c];+ }+}++/// The normalized latent back to the VAE's: x · std + mean per channel (`p.x` channels of `p.y` pixels).+kernel void vae_latent_affine(device const float *x [[buffer(0)]], device float *out [[buffer(1)]],+ device const float *std [[buffer(2)]], device const float *mean [[buffer(3)]],+ constant uint2 &p [[buffer(4)]], uint2 gid [[thread_position_in_grid]]) {+ if (gid.x >= p.y || gid.y >= p.x) return;+ ulong at = ulong(gid.y) * p.y + gid.x;+ out[at] = x[at] * std[gid.y] + mean[gid.y];+}diff --git a/engine-mac/Sources/KokonEngine/QwenVAE.swift b/engine-mac/Sources/KokonEngine/QwenVAE.swiftindex 3215d3c..735e397 100644--- a/engine-mac/Sources/KokonEngine/QwenVAE.swift+++ b/engine-mac/Sources/KokonEngine/QwenVAE.swift@@ -47,9 +47,25 @@ public final class QwenVAE {/// 1024², the first two 2.65, for 2.2–2.7e-3 of diffusers instead of 1.1e-5 (M2 Pro, `check-vae`, 2026-10-25). The/// VAE stays fp32.var executables: [String: MPSGraphExecutable] = [:]- private var feedOrders: [String: [Int]] = [:]let lock = NSLock()+ /// **Compiled single-operation graphs** (a convolution with its bias and skip, the mid block's attention), shared by+ /// every instance: their weights are inputs, so they hold none. Below 32 GB the pipeline makes a new VAE for each+ /// image, which compiled them all again (a new instance's decode 3.9–4.1 s against 3.1, with its weights' reading).+ nonisolated(unsafe) private static var operationGraphs: [String: (MPSGraphExecutable, [Int])] = [:]+ private static let graphLock = NSLock()++ /// The graph cached under `key` (with the device), compiled by `build` the first time; its executable and the+ /// order of its inputs.+ static func operationGraph(_ key: String, _ build: () throws -> (MPSGraphExecutable, [Int])) throws -> (MPSGraphExecutable, [Int]) {+ try graphLock.withLock {+ if let cached = operationGraphs[key] { return cached }+ let made = try build()+ operationGraphs[key] = made+ return made+ }+ }+public init(path: String, context: MetalContext) throws {file = try SafetensorsFile(path: path)self.context = context@@ -117,6 +133,7 @@ public final class QwenVAE {var commands = MPSCommandBuffer(from: context.queue)let pool = BufferPool(context: context)let memory = ProcessInfo.processInfo.environment["KOKON_VAE_MEMORY"] != nil // waits after each stage to tell+ var stageStart = DispatchTime.now().uptimeNanosecondsvar current = try pool.take(latent.count)current.contents().copyMemory(from: latent, byteCount: 4 * latent.count)for (stage, tile) in stages {@@ -133,8 +150,10 @@ public final class QwenVAE {commands.commit()commands.waitUntilCompleted()commands = MPSCommandBuffer(from: context.queue)- print(String(format: " after %@: footprint %.2f GB, pool %.2f GB", stage.description, MemoryUsage.now().footprint,- Double(pool.bytes) / Double(1 << 30)))+ let now = DispatchTime.now().uptimeNanoseconds+ print(String(format: " after %@: %.2f s, footprint %.2f GB, pool %.2f GB", stage.description,+ Double(now - stageStart) * 1e-9, MemoryUsage.now().footprint, Double(pool.bytes) / Double(1 << 30)))+ stageStart = now}}commands.commit()@@ -170,7 +189,7 @@ public final class QwenVAE {/// `stage` on an `H` × `W` input, whole.private func encode(_ stage: Stage, from input: MTLBuffer, to output: MTLBuffer, height H: Int, width W: Int,pool: BufferPool, commands: MPSCommandBuffer) throws {- if ops && stage.first >= 0 {+ if ops && (stage.first >= 0 || midOperations) {return try encodeOperations(stage, from: input, to: output, height: H, width: W, pool: pool, commands: commands)}_ = try prepare(stage, height: H, width: W)@@ -206,21 +225,18 @@ public final class QwenVAE {var (x, c, hh, ww) = (input, Stage.channels(stage.first), H, W)/// Gives `b` back unless it is the stage's input (the caller's).func done(_ b: MTLBuffer) { if b !== input { pool.give(b) } }- for i in stage.first..<stage.end {+ if stage.first < 0 {+ let mid = stage.end == 0 ? output : try pool.take(QwenVAE.dims[0] * H * W)+ try encodeMid(from: input, to: mid, height: H, width: W, pool: pool, commands: commands)+ if stage.end == 0 { return }+ (x, c) = (mid, QwenVAE.dims[0])+ }+ for i in max(stage.first, 0)..<stage.end {let (inC, outC) = (QwenVAE.dims[i], QwenVAE.dims[i + 1])let blockInput = xfor j in 0..<3 {- let name = "decoder.upsamples.\(i).upsamples.\(j)"- let t = try pool.take(c * hh * ww)- try normSilu(x, to: t, gamma: name + ".residual.0.gamma", channels: c, pixels: hh * ww, commands: commands)- let u = try pool.take(outC * hh * ww)- try convolution(t, name + ".residual.2", inC: c, outC: outC, k: 3, height: hh, width: ww, to: u, commands: commands)- pool.give(t)- try normSilu(u, to: u, gamma: name + ".residual.3.gamma", channels: outC, pixels: hh * ww, commands: commands)- let y = try pool.take(outC * hh * ww)- try convolution(u, name + ".residual.6", inC: outC, outC: outC, k: 3, height: hh, width: ww, to: y,- skip: (x, c == outC ? nil : name + ".shortcut", c), commands: commands)- pool.give(u)+ let y = try residualBlock(x, "decoder.upsamples.\(i).upsamples.\(j)", inC: c, outC: outC, height: hh, width: ww,+ pool: pool, commands: commands)if x !== blockInput { done(x) }(x, c) = (y, outC)}@@ -253,14 +269,103 @@ public final class QwenVAE {}}+ /// QwenImage21ResidualBlock on `[inC, h, w]` in `x`: norm + SiLU, 3×3, norm + SiLU, 3×3 with the skip (through+ /// the 1×1 shortcut when the channels change), into `out` or a buffer of the pool.+ func residualBlock(_ x: MTLBuffer, _ name: String, inC: Int, outC: Int, height hh: Int, width ww: Int, out: MTLBuffer? = nil,+ pool: BufferPool, commands: MPSCommandBuffer) throws -> MTLBuffer {+ let t = try pool.take(inC * hh * ww)+ try normSilu(x, to: t, gamma: name + ".residual.0.gamma", channels: inC, pixels: hh * ww, commands: commands)+ let u = try pool.take(outC * hh * ww)+ try convolution(t, name + ".residual.2", inC: inC, outC: outC, k: 3, height: hh, width: ww, to: u, commands: commands)+ pool.give(t)+ try normSilu(u, to: u, gamma: name + ".residual.3.gamma", channels: outC, pixels: hh * ww, commands: commands)+ let y = try out ?? pool.take(outC * hh * ww)+ try convolution(u, name + ".residual.6", inC: outC, outC: outC, k: 3, height: hh, width: ww, to: y,+ skip: (x, inC == outC ? nil : name + ".shortcut", inC), commands: commands)+ pool.give(u)+ return y+ }++ /// **The mid stage as operations** (`KOKON_VAE_MID_OPS=0`: one graph): the latent's scale and shift, post_quant_conv,+ /// conv_in, the two residual blocks as the up blocks run them, and the attention block (norm, to_qkv, one head over+ /// every pixel in a graph of its own, proj with the skip). As one graph it was compiled for each new instance with+ /// its ~54 M weights as constants and kept 0.55 GB of intermediates at 1024².+ public var midOperations = ProcessInfo.processInfo.environment["KOKON_VAE_MID_OPS"] != "0"++ private lazy var latentAffine: (std: MTLBuffer, mean: MTLBuffer)? = {+ guard let s = try? context.scratch(4 * 64, label: "latent std"), let m = try? context.scratch(4 * 64, label: "latent mean") else { return nil }+ s.contents().copyMemory(from: QwenVAE.latentsStd, byteCount: 4 * 64)+ m.contents().copyMemory(from: QwenVAE.latentsMean, byteCount: 4 * 64)+ return (s, m)+ }()++ /// The normalized latent `[64, h, w]` in `input` to the mid block's output `[1152, h, w]` in `output`.+ private func encodeMid(from input: MTLBuffer, to output: MTLBuffer, height h: Int, width w: Int, pool: BufferPool,+ commands: MPSCommandBuffer) throws {+ let c = QwenVAE.dims[0], px = h * w+ guard let affine = latentAffine else { throw MetalContext.Failure.buffer("VAE latent statistics") }+ let a = try pool.take(64 * px)+ try dispatch("vae_latent_affine", [input, a, affine.std, affine.mean], [64, UInt32(px)],+ grid: MTLSize(width: px, height: 64, depth: 1), commands: commands)+ let b = try pool.take(64 * px)+ try convolution(a, "conv2", inC: 64, outC: 64, k: 1, height: h, width: w, to: b, commands: commands) // post_quant_conv+ pool.give(a)+ var x = try pool.take(c * px)+ try convolution(b, "decoder.conv1", inC: 64, outC: c, k: 3, height: h, width: w, to: x, commands: commands) // conv_in+ pool.give(b)+ var y = try residualBlock(x, "decoder.middle.0", inC: c, outC: c, height: h, width: w, pool: pool, commands: commands)+ pool.give(x)+ x = try attentionBlock(y, "decoder.middle.1", channels: c, height: h, width: w, pool: pool, commands: commands)+ pool.give(y)+ y = try residualBlock(x, "decoder.middle.2", inC: c, outC: c, height: h, width: w, out: output, pool: pool, commands: commands)+ pool.give(x)+ }++ /// QwenImage21AttentionBlock on `[c, h, w]` in `x`: one head over every pixel, its own graph between to_qkv and proj.+ func attentionBlock(_ x: MTLBuffer, _ name: String, channels c: Int, height h: Int, width w: Int, pool: BufferPool,+ commands: MPSCommandBuffer) throws -> MTLBuffer {+ let px = h * w+ let t = try pool.take(c * px)+ try dispatch("vae_norm", [x, t, try weight(name + ".norm.gamma")], [UInt32(c), UInt32(px)],+ grid: MTLSize(width: px, height: 1, depth: 1), commands: commands)+ let qkv = try pool.take(3 * c * px)+ try convolution(t, name + ".to_qkv", inC: c, outC: 3 * c, k: 1, height: h, width: w, to: qkv, commands: commands)+ pool.give(t)+ let o = try pool.take(c * px)+ let (executable, _) = try QwenVAE.operationGraph("\(context.device.registryID) attention \(c) \(h)×\(w)") {+ let g = MPSGraph()+ func n(_ v: [Int]) -> [NSNumber] { v.map { NSNumber(value: $0) } }+ let input = g.placeholder(shape: n([1, 3 * c, h, w]), dataType: .float32, name: nil)+ let rows = g.transpose(g.reshape(input, shape: n([3 * c, px]), 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, px, c]), name: nil)+ }+ let a = 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(a, shape: n([px, c]), name: nil), permutation: n([1, 0]), name: nil),+ shape: n([1, c, h, w]), name: nil)+ let descriptor = MPSGraphCompilationDescriptor()+ descriptor.waitForCompilationCompletion = true+ return (g.compile(with: MPSGraphDevice(mtlDevice: context.device),+ feeds: [input: MPSGraphShapedType(shape: n([1, 3 * c, h, w]), dataType: .float32)],+ targetTensors: [back], targetOperations: nil, compilationDescriptor: descriptor), [0])+ }+ _ = executable.encode(to: commands, inputs: [data(qkv, [1, 3 * c, h, w])], results: [data(o, [1, c, h, w])], executionDescriptor: nil)+ pool.give(qkv)+ let y = try pool.take(c * px)+ try convolution(o, name + ".proj", inC: c, outC: c, k: 1, height: h, width: w, to: y, skip: (x, nil, c), commands: commands)+ pool.give(o)+ return y+ }+/// Weights as fp32 buffers, each read from the file once.private var weightBuffers: [String: MTLBuffer] = [:]func weight(_ name: String) throws -> MTLBuffer {try lock.withLock {if let b = weightBuffers[name] { return b }- let values = try file.floats(name)- let b = try context.scratch(4 * values.count, label: name)- b.contents().copyMemory(from: values, byteCount: 4 * values.count)+ guard let t = file.tensors[name] else { throw GGUFFile.Failure.unsupported("no tensor \(name) in \(file.path)") }+ let b = try context.scratch(4 * t.count, label: name)+ try file.copyFloats(name, into: b.contents().assumingMemoryBound(to: Float.self))weightBuffers[name] = breturn b}@@ -302,8 +407,7 @@ public final class QwenVAE {let kind = skip == nil ? "" : skip!.shortcut == nil ? "+x" : "+1x1(\(skip!.channels))"let key = "conv \(inC)→\(outC) \(k)×\(k)\(kind)\(clamp ? " clamp" : "")\(downsample ? " /2" : "") \(h)×\(w)"let (oh, ow) = downsample ? (h / 2, w / 2) : (h, w)- let (executable, order) = try lock.withLock { () throws -> (MPSGraphExecutable, [Int]) in- if let e = executables[key], let order = feedOrders[key] { return (e, order) }+ let (executable, order) = try QwenVAE.operationGraph("\(context.device.registryID) " + key) { () throws -> (MPSGraphExecutable, [Int]) inlet g = MPSGraph()func n(_ v: [Int]) -> [NSNumber] { v.map { NSNumber(value: $0) } }var feeds: [MPSGraphTensor: MPSGraphShapedType] = [:], placeholders: [MPSGraphTensor] = []@@ -338,8 +442,6 @@ public final class QwenVAE {targetOperations: nil, compilationDescriptor: descriptor)// The executable takes its inputs in its own order (`feedTensors`), not the placeholders'.let order = (e.feedTensors ?? placeholders).map { t in placeholders.firstIndex { $0 === t }! }- executables[key] = e- feedOrders[key] = orderreturn (e, order)}var inputs = [data(x, [1, inC, h, w]), data(try weight(name + ".weight"), [outC, inC, k, k]),diff --git a/engine-mac/Sources/KokonEngine/Safetensors.swift b/engine-mac/Sources/KokonEngine/Safetensors.swiftindex 9b62bdc..2ef9cb9 100644--- a/engine-mac/Sources/KokonEngine/Safetensors.swift+++ b/engine-mac/Sources/KokonEngine/Safetensors.swift@@ -49,6 +49,33 @@ public final class SafetensorsFile: @unchecked Sendable {deinit { munmap(UnsafeMutableRawPointer(mutating: base), length) }+ /// A tensor as fp32 into `out` (its count of floats); BF16 widened 8 values at a time on every core (the VAE's+ /// ~260 M decoder weights, read again for each image below 32 GB of memory).+ public func copyFloats(_ name: String, into out: UnsafeMutablePointer<Float>) throws {+ guard let t = tensors[name] else { throw GGUFFile.Failure.unsupported("no tensor \(name) in \(path)") }+ guard t.dtype == "BF16" else {+ let values = try floats(name)+ out.update(from: values, count: values.count)+ return+ }+ let p = base + dataStart + t.start, count = t.count+ let chunk = 1 << 20, chunks = (count + chunk - 1) / chunk+ nonisolated(unsafe) let (source, target) = (p, UnsafeMutableRawPointer(out))+ DispatchQueue.concurrentPerform(iterations: chunks) { c in+ let start = c * chunk, end = min(count, start + chunk)+ var i = start+ while i + 8 <= end {+ let v = SIMD8<UInt32>(truncatingIfNeeded: source.loadUnaligned(fromByteOffset: 2 * i, as: SIMD8<UInt16>.self)) &<< 16+ target.storeBytes(of: v, toByteOffset: 4 * i, as: SIMD8<UInt32>.self)+ i += 8+ }+ while i < end {+ target.storeBytes(of: UInt32(source.loadUnaligned(fromByteOffset: 2 * i, as: UInt16.self)) << 16, toByteOffset: 4 * i, as: UInt32.self)+ i += 1+ }+ }+ }+/// 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)") }