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: fused attention kernel
Gabriele Lozuponed1473cea923c
diff --git a/engine-mac/README.md b/engine-mac/README.mdindex 991c55b..a01585c 100644--- a/engine-mac/README.md+++ b/engine-mac/README.md@@ -67,7 +67,10 @@ of 32 rows (the text projection) slowed all later ones to 18.5 s.Engine 2048 at 1024²): **11.3 s per evaluation at 1024²**, 8.8 s at 896². The GPU packs the Neural Engine's fp16operands straight into its IOSurfaces and unpacks its output, so the CPU only runs the AMX. Accuracy at 896²against diffusers fp32: the velocity within 3.6e-4 relative (GPU alone 4.4e-6); running the model in bf16, as-most tools do, deviates by roughly 1e-2. The attention (4.1 s, GPU only, the other units idle) is next.+most tools do, deviates by roughly 1e-2.+**Attention** is a fused (flash) kernel of our own (`Kernels/attention.metal`, fp32, online softmax, block-causal+mask): 4.5 s per 1024² evaluation against MPSGraph's 4.1 s, but without MPSGraph's score matrix (2.2 GB at 1 MP,+~34 GB at 4 MP). `KOKON_ATTENTION=graph` keeps MPSGraph for comparison. The other units are idle during it: next.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/Kernels/attention.metal b/engine-mac/Sources/KokonEngine/Kernels/attention.metalnew file mode 100644index 0000000..1b7e784--- /dev/null+++ b/engine-mac/Sources/KokonEngine/Kernels/attention.metal@@ -0,0 +1,159 @@+#include <metal_stdlib>+#include <metal_simdgroup_matrix>+using namespace metal;++// Fused scaled dot-product attention, fp32, head_dim 128, on the layout the products write: q, k, v and out are+// rows of `stride` floats (all heads side by side), head h at columns [128 h, 128 h + 128).+//+// A threadgroup takes 64 query rows of one head (8 SIMD groups of 8 rows) and walks the keys 32 at a time with an+// online softmax (running max and sum per row), so the [queries, keys] score matrix never exists in memory. Each+// key tile, then value tile, is loaded once into threadgroup memory by all 256 threads (coalesced rows) and shared+// by the 8 SIMD groups; products on 8×8 SIMD-group matrices.+//+// causal: the queries are the last `queries` of the keys; query i sees keys j <= keys - queries + i (a text+// segment of Qwen-Image 2.1's block-causal mask). Rows past `queries` are computed but never stored and keys past+// `keys` are masked: the caller guarantees those rows exist (up to 63 past the end) and are finite.+//+// Barriers are threadgroup barriers: with simdgroup barriers alone the lanes' writes to threadgroup memory were+// sometimes not seen by the SIMD-group loads that followed (1 run in 4 wrong, M2 Pro, macOS 27, AttentionTests).++constant uint BQ = 64, BK = 32, D = 128, GROUPS = 8;++struct FlashParams {+ uint queries;+ uint keys;+ uint causal;+ uint stride;+ float scale; // 1/sqrt(head_dim) * log2(e): scores go straight to exp2+ uint headBase;+};++kernel void flash_attention(device const float *q [[buffer(0)]], device const float *k [[buffer(1)]],+ device const float *v [[buffer(2)]], device float *out [[buffer(3)]],+ constant FlashParams &p [[buffer(4)]],+ uint2 tg [[threadgroup_position_in_grid]],+ uint tid [[thread_index_in_threadgroup]],+ uint sg [[simdgroup_index_in_threadgroup]],+ uint lane [[thread_index_in_simdgroup]]) {+ threadgroup float tile[BK * D]; // 16 KB: the key tile, then the value tile+ threadgroup float stageAll[GROUPS][8 * BK]; // 8 KB: each SIMD group's scores / probabilities+ threadgroup float diagAll[GROUPS][64]; // 2 KB: each SIMD group's per-row scale, as a diagonal+ threadgroup float *stage = stageAll[sg];+ threadgroup float *diag = diagAll[sg];++ const uint head = p.headBase + tg.y;+ const uint q0 = tg.x * BQ + sg * 8;+ const uint stride = p.stride;+ device const float *kh = k + head * D;+ device const float *vh = v + head * D;++ simdgroup_float8x8 Q[16], O[16];+ for (uint d = 0; d < 16; d++) {+ simdgroup_load(Q[d], q + (ulong)q0 * stride + head * D + 8 * d, stride);+ O[d] = make_filled_simdgroup_matrix<float, 8, 8>(0.0f);+ }+ diag[lane * 2] = 0.0f;+ diag[lane * 2 + 1] = 0.0f;++ // Each lane owns 8 scores of one row: row lane / 4, columns (lane % 4) * 8 ... + 8.+ const uint row = lane / 4, cbase = (lane % 4) * 8;+ const uint qi = q0 + row;+ const uint offset = p.keys - p.queries;+ const int limit = p.causal ? int(offset + qi) : int(p.keys) - 1;+ float m = -INFINITY, l = 0.0f;++ uint kEnd = p.keys;+ if (p.causal) kEnd = min(p.keys, offset + min(tg.x * BQ + BQ - 1, p.queries - 1) + 1);++ for (uint j0 = 0; j0 < kEnd; j0 += BK) {+ // Key tile: 32 rows × 128, 256 threads × 4 float4.+ for (uint i = tid; i < BK * D / 4; i += 256) {+ uint r = i / (D / 4), c = i % (D / 4);+ ((threadgroup float4 *)tile)[i] = *((device const float4 *)(kh + (ulong)(j0 + r) * stride) + c);+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ simdgroup_float8x8 S[4];+ for (uint c = 0; c < 4; c++) S[c] = make_filled_simdgroup_matrix<float, 8, 8>(0.0f);+ for (uint d = 0; d < 16; d++) {+ for (uint c = 0; c < 4; c++) {+ simdgroup_float8x8 Kt;+ simdgroup_load(Kt, tile + 8 * c * D + 8 * d, D, ulong2(0, 0), true);+ simdgroup_multiply_accumulate(S[c], Q[d], Kt, S[c]);+ }+ }+ for (uint c = 0; c < 4; c++) simdgroup_store(S[c], stage + 8 * c, BK);+ threadgroup_barrier(mem_flags::mem_threadgroup);++ // Value tile into the same memory (everyone is done with the keys), softmax meanwhile.+ for (uint i = tid; i < BK * D / 4; i += 256) {+ uint r = i / (D / 4), c = i % (D / 4);+ ((threadgroup float4 *)tile)[i] = *((device const float4 *)(vh + (ulong)(j0 + r) * stride) + c);+ }+ float s[8];+ float blockMax = -INFINITY;+ for (uint t = 0; t < 8; t++) {+ int j = int(j0 + cbase + t);+ float x = stage[row * BK + cbase + t] * p.scale;+ if (j > limit) x = -INFINITY;+ s[t] = x;+ blockMax = max(blockMax, x);+ }+ blockMax = max(blockMax, simd_shuffle_xor(blockMax, 1));+ blockMax = max(blockMax, simd_shuffle_xor(blockMax, 2));+ float mNew = max(m, blockMax);+ float alpha = (mNew == -INFINITY) ? 1.0f : exp2(m - mNew);+ float sum = 0.0f;+ for (uint t = 0; t < 8; t++) {+ float e = (mNew == -INFINITY) ? 0.0f : exp2(s[t] - mNew);+ stage[row * BK + cbase + t] = e;+ sum += e;+ }+ sum += simd_shuffle_xor(sum, 1);+ sum += simd_shuffle_xor(sum, 2);+ l = l * alpha + sum;+ m = mNew;+ if (lane % 4 == 0) diag[row * 8 + row] = alpha;+ const bool rescale = !simd_all(alpha == 1.0f);+ threadgroup_barrier(mem_flags::mem_threadgroup);++ simdgroup_float8x8 P[4];+ for (uint c = 0; c < 4; c++) simdgroup_load(P[c], stage + 8 * c, BK);+ if (rescale) {+ simdgroup_float8x8 Dg;+ simdgroup_load(Dg, diag, 8);+ for (uint d = 0; d < 16; d++) {+ simdgroup_float8x8 scaled;+ simdgroup_multiply(scaled, Dg, O[d]);+ O[d] = scaled;+ }+ }+ for (uint d = 0; d < 16; d++) {+ for (uint c = 0; c < 4; c++) {+ simdgroup_float8x8 V;+ simdgroup_load(V, tile + 8 * c * D + 8 * d, D);+ simdgroup_multiply_accumulate(O[d], P[c], V, O[d]);+ }+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);+ }++ // O / l per row, then the valid rows to memory.+ if (lane % 4 == 0) diag[row * 8 + row] = 1.0f / l;+ threadgroup_barrier(mem_flags::mem_threadgroup);+ simdgroup_float8x8 Dg;+ simdgroup_load(Dg, diag, 8);+ for (uint part = 0; part < 4; part++) {+ for (uint c = 0; c < 4; c++) {+ simdgroup_float8x8 r;+ simdgroup_multiply(r, Dg, O[part * 4 + c]);+ simdgroup_store(r, stage + 8 * c, BK);+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);+ if (qi < p.queries) {+ device float *o = out + (ulong)qi * stride + head * D + part * 32 + cbase;+ for (uint t = 0; t < 8; t++) o[t] = stage[row * BK + cbase + t];+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);+ }+}diff --git a/engine-mac/Sources/KokonEngine/QwenDiT.swift b/engine-mac/Sources/KokonEngine/QwenDiT.swiftindex aee47f5..5a475cf 100644--- a/engine-mac/Sources/KokonEngine/QwenDiT.swift+++ b/engine-mac/Sources/KokonEngine/QwenDiT.swift@@ -397,8 +397,28 @@ public final class QwenDiT {}}+ /// Attention through `Kernels/attention.metal` (default) or MPSGraph (`KOKON_ATTENTION=graph`, the check).+ let graphAttention = ProcessInfo.processInfo.environment["KOKON_ATTENTION"] == "graph"+ struct FlashParams { var queries, keys, causal, stride: UInt32; var scale: Float; var headBase: UInt32 }+/// 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 row = QwenDiT.dim * 4+ if !graphAttention {+ try compute("flash_attention", commands: commands) { e in+ e.setBuffer(arena.buffer, offset: q.offset + queries * row, index: 0)+ e.setBuffer(arena.buffer, offset: k.offset, index: 1)+ e.setBuffer(arena.buffer, offset: v.offset, index: 2)+ e.setBuffer(arena.buffer, offset: attended.offset + queries * row, index: 3)+ var params = FlashParams(queries: UInt32(count), keys: UInt32(keys), causal: causal ? 1 : 0,+ stride: UInt32(QwenDiT.dim), scale: 1 / Float(QwenDiT.headDim).squareRoot() * Float(M_LOG2E),+ headBase: 0)+ e.setBytes(¶ms, length: MemoryLayout<FlashParams>.stride, index: 4)+ e.dispatchThreadgroups(MTLSize(width: (count + 63) / 64, height: QwenDiT.heads, depth: 1),+ threadsPerThreadgroup: MTLSize(width: 256, height: 1, depth: 1))+ }+ return+ }let key = "\(count)×\(keys)\(causal ? "c" : "")"let attention: GraphAttentionif let a = attentions[key] { attention = a } else {@@ -406,7 +426,6 @@ public final class QwenDiT {headDim: QwenDiT.headDim, causal: causal)attentions[key] = attention}- let row = QwenDiT.dim * 4let b = arena.buffertry gpu("attention", commands) {attention.encode(commands: $0, q: (b, q.offset + queries * row), k: (b, k.offset), v: (b, v.offset),diff --git a/engine-mac/Tests/KokonEngineTests/AttentionTests.swift b/engine-mac/Tests/KokonEngineTests/AttentionTests.swiftnew file mode 100644index 0000000..56c1fef--- /dev/null+++ b/engine-mac/Tests/KokonEngineTests/AttentionTests.swift@@ -0,0 +1,91 @@+import Metal+import XCTest+@testable import KokonEngine++/// `flash_attention` against attention computed in double on the CPU: plain and causal (the block-causal mask's+/// text segments), sizes that are not multiples of the kernel's tiles, rows past the queries left untouched.+final class AttentionTests: XCTestCase {+ struct FlashParams { var queries, keys, causal, stride: UInt32; var scale: Float; var headBase: UInt32 }++ func run(queries: Int, keys: Int, causal: Bool, heads: Int = 2, magnitude: Float = 4) throws -> (worst: Double, untouched: Bool) {+ let context = try MetalContext()+ let stride = heads * 128, padding = 64+ let rows = max(queries, keys) + padding+ var seed: UInt64 = UInt64(queries * 1000 + keys)+ func random() -> Float {+ seed = seed &* 6364136223846793005 &+ 1442695040888963407+ return (Float(seed >> 40) / Float(1 << 24) - 0.5) * magnitude+ }+ let q = (0..<(rows * stride)).map { _ in random() }+ let k = (0..<(rows * stride)).map { _ in random() }+ let v = (0..<(rows * stride)).map { _ in random() }+ func buffer(_ a: [Float]) throws -> MTLBuffer {+ let b = try context.scratch(a.count * 4, label: "t")+ b.contents().copyMemory(from: a, byteCount: a.count * 4)+ return b+ }+ let (qb, kb, vb) = (try buffer(q), try buffer(k), try buffer(v))+ let ob = try buffer([Float](repeating: 7, count: rows * stride))+ let commands = context.queue.makeCommandBuffer()!+ let e = commands.makeComputeCommandEncoder()!+ e.setComputePipelineState(try context.pipeline("flash_attention"))+ for (i, b) in [qb, kb, vb, ob].enumerated() { e.setBuffer(b, offset: 0, index: i) }+ var p = FlashParams(queries: UInt32(queries), keys: UInt32(keys), causal: causal ? 1 : 0, stride: UInt32(stride),+ scale: 1 / Float(128).squareRoot() * Float(M_LOG2E), headBase: 0)+ e.setBytes(&p, length: MemoryLayout<FlashParams>.stride, index: 4)+ e.dispatchThreadgroups(MTLSize(width: (queries + 63) / 64, height: heads, depth: 1),+ threadsPerThreadgroup: MTLSize(width: 256, height: 1, depth: 1))+ e.endEncoding()+ try MetalContext.finish(commands, "flash")+ let o = ob.contents().assumingMemoryBound(to: Float.self)+ var worst = 0.0+ for h in 0..<heads {+ for i in 0..<queries {+ let visible = causal ? keys - queries + i + 1 : keys+ var scores = [Double](repeating: 0, count: visible)+ for j in 0..<visible {+ var s = 0.0+ for d in 0..<128 { s += Double(q[i * stride + h * 128 + d]) * Double(k[j * stride + h * 128 + d]) }+ scores[j] = s / 128.0.squareRoot()+ }+ let peak = scores.max()!+ let weights = scores.map { exp($0 - peak) }+ let total = weights.reduce(0, +)+ for d in 0..<128 {+ var acc = 0.0+ for j in 0..<visible { acc += weights[j] * Double(v[j * stride + h * 128 + d]) }+ worst = max(worst, abs(acc / total - Double(o[i * stride + h * 128 + d])))+ }+ }+ }+ let untouched = (queries * stride..<(rows * stride)).allSatisfy { o[$0] == 7 }+ return (worst, untouched)+ }++ func testPlain() throws {+ for (q, k) in [(32, 32), (40, 70), (100, 130), (7, 300)] {+ let r = try run(queries: q, keys: k, causal: false)+ XCTAssertLessThan(r.worst, 1e-5, "\(q)×\(k)")+ XCTAssertTrue(r.untouched, "\(q)×\(k) wrote past its queries")+ }+ }++ /// Broad softmax (small scores) catches a missed barrier: it once failed 1 run in 4 at 0.017. Large scores+ /// (hundreds) leave fp32's relative error in the exponent, the limit of any fp32 attention: bounded loosely.+ func testMagnitudes() throws {+ for (magnitude, bound): (Float, Double) in [(4, 1e-5), (16, 1e-3), (40, 1e-2)] {+ for _ in 0..<3 {+ let r = try run(queries: 64, keys: 96, causal: false, magnitude: magnitude)+ XCTAssertLessThan(r.worst, bound, "magnitude \(magnitude)")+ }+ }+ }++ func testCausal() throws {+ for (q, k) in [(24, 24), (24, 60), (45, 45), (70, 100)] {+ let r = try run(queries: q, keys: k, causal: true)+ XCTAssertLessThan(r.worst, 1e-5, "\(q)×\(k) causal")+ XCTAssertTrue(r.untouched, "\(q)×\(k) causal wrote past its queries")+ }+ }+}