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: attention on K and V packed to fp16; direct-load variant for Apple9+
Gabriele Lozupone44df002d5610
diff --git a/engine-mac/README.md b/engine-mac/README.mdindex 3f0e1d1..0220816 100644--- a/engine-mac/README.md+++ b/engine-mac/README.md@@ -183,6 +183,16 @@ against 5.1e-4 before (fp16 weights alone 5.7e-4; the Neural Engine's rows wereThe 1024² image against the previous precision: 0.05 levels on average, at most 6. **1024² image: 69.8 s** (textencoder 2.0 s, step 1 8.4 s, steps 2–8 7.4–8.0 s, VAE 6.0 s).+**Attention retune after MFA's tables** (`probe-attention`, 1024², 32 heads, M2 Pro, 2026-10-25): K and V are+packed once per layer to fp16, heads first (`attention_pack_kv`, 1.1 ms), and the kernel reads them unconverted:+91.0 ms with the packing against 95.2, the same accuracy; per layer in the DiT the attention's wall 66.5–67.3 →+64.7–65.6 ms, an evaluation ~1 % (A/B in alternating runs; `KOKON_ATTENTION=unpacked` for the comparison). MFA's+M1/M2 shape (4 SIMD groups × 8 rows, 128-key tiles, the head in chunks of 32) on the same packed operands: 105 ms;+8 × 8 rows with 128-key tiles in chunks of 32: 94; 64-key tiles in chunks of 64: 104; so the kernel keeps 8 × 8+rows, 64-key tiles, K and V loaded together. MFA's shapes rest on its async copies, which run-time compiled Metal+cannot use. On Apple9+ GPUs (M3 and later) the engine picks `flash_attention_direct`, each SIMD group reading the+packed K and V straight from memory as MFA's tables prefer there: 142 ms on the M2 Pro, not yet measured on an M3+.+MFA's GEMM (libnnc, 48 × 48 blocks, 2 × 2 SIMD groups) was tried against MPS: its async copies are an AIR intrinsicthat macOS 27's run-time compiler refuses (libnnc ships prebuilt metallibs for it), and without them it ran at3.6–4.0 TFLOP/s against MPS's 5.1–5.6 at 1472 × 4096 × 4096, so MPS stays.diff --git a/engine-mac/Sources/KokonEngine/AttentionProbe.swift b/engine-mac/Sources/KokonEngine/AttentionProbe.swiftindex 0db6637..611e8d1 100644--- a/engine-mac/Sources/KokonEngine/AttentionProbe.swift+++ b/engine-mac/Sources/KokonEngine/AttentionProbe.swift@@ -51,23 +51,49 @@ extension Probe {// The GPU's flash kernel, all heads.struct FlashParams { var queries, keys, causal, stride: UInt32; var scale: Float; var headBase: UInt32 }- for kernel in ["flash_attention", "flash_attention_half"] {+ // Packed fp16 K and V (`attention_pack_kv`) for the kernels that read them, keys padded to 128.+ struct PackParams { var keys, paddedKeys, stride, heads: UInt32 }+ let paddedKeys = (keys + 127) / 128 * 128+ let kp = try context.scratch(heads * paddedKeys * d * 2, label: "k fp16"), vp = try context.scratch(heads * paddedKeys * d * 2, label: "v fp16")+ func pack(_ commands: MTLCommandBuffer) throws {+ let e = commands.makeComputeCommandEncoder()!+ e.setComputePipelineState(try context.pipeline("attention_pack_kv"))+ e.setBuffer(kb, offset: 0, index: 0); e.setBuffer(vb, offset: 0, index: 1)+ e.setBuffer(kp, offset: 0, index: 2); e.setBuffer(vp, offset: 0, index: 3)+ var pp = PackParams(keys: UInt32(keys), paddedKeys: UInt32(paddedKeys), stride: UInt32(stride), heads: UInt32(heads))+ e.setBytes(&pp, length: MemoryLayout<PackParams>.stride, index: 4)+ e.dispatchThreads(MTLSize(width: d / 4, height: paddedKeys, depth: heads), threadsPerThreadgroup: MTLSize(width: 32, height: 8, depth: 1))+ e.endEncoding()+ }+ let packTime = try best(3) {+ let commands = context.queue.makeCommandBuffer()!+ try pack(commands)+ return try MetalContext.finish(commands, "pack")+ }+ print(String(format: "GPU attention_pack_kv, 32 heads: %.2f ms", packTime * 1e3))+ let kernels = [("flash_attention", false, 64, 256), ("flash_attention_half", false, 64, 256),+ ("flash_attention_packed", true, 64, 256), ("flash_attention_direct", true, 64, 256)]+ for (kernel, packed, rowsPerGroup, threads) in kernels {let gpu = try best(3) {let commands = context.queue.makeCommandBuffer()!+ if packed { try pack(commands) }let e = commands.makeComputeCommandEncoder()!e.setComputePipelineState(try context.pipeline(kernel))- e.setBuffer(qb, offset: offset * stride * 4, index: 0); e.setBuffer(kb, offset: 0, index: 1)- e.setBuffer(vb, offset: 0, index: 2); e.setBuffer(ob, offset: offset * stride * 4, index: 3)+ e.setBuffer(qb, offset: offset * stride * 4, index: 0)+ e.setBuffer(packed ? kp : kb, offset: 0, index: 1); e.setBuffer(packed ? vp : vb, offset: 0, index: 2)+ e.setBuffer(ob, offset: offset * stride * 4, index: 3)var p = FlashParams(queries: UInt32(queries), keys: UInt32(keys), causal: 0, stride: UInt32(stride),scale: scale * 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))+ var padded = UInt32(paddedKeys)+ if packed { e.setBytes(&padded, length: 4, index: 5) }+ e.dispatchThreadgroups(MTLSize(width: (queries + rowsPerGroup - 1) / rowsPerGroup, height: heads, depth: 1),+ threadsPerThreadgroup: MTLSize(width: threads, height: 1, depth: 1))e.endEncoding()return try MetalContext.finish(commands, "flash")}let gpuError = error { i, c in f(ob)[(offset + i) * stride + c] }- print(String(format: "GPU %@, 32 heads: %.1f ms, %.2f ms/head, %.2f TFLOP/s; head 0 rel %.1e", kernel,+ print(String(format: "GPU %@%@, 32 heads: %.1f ms, %.2f ms/head, %.2f TFLOP/s; head 0 rel %.1e", kernel, packed ? " (with packing)" : "",gpu * 1e3, gpu * 1e3 / Double(heads), 4 * Double(queries) * Double(keys) * Double(d) * Double(heads) / gpu / 1e12, gpuError))}if ProcessInfo.processInfo.environment["KOKON_PROBE_GPU_ONLY"] == "1" { return }diff --git a/engine-mac/Sources/KokonEngine/Kernels/attention.metal b/engine-mac/Sources/KokonEngine/Kernels/attention.metalindex 4158912..90070ef 100644--- a/engine-mac/Sources/KokonEngine/Kernels/attention.metal+++ b/engine-mac/Sources/KokonEngine/Kernels/attention.metal@@ -259,3 +259,228 @@ kernel void flash_attention_half(device const float *q [[buffer(0)]], device con}}}++// K and V of heads [0, heads) packed for the kernels below: fp16, heads first, `[head][key][128]`, keys padded with+// zeros to `paddedKeys`. One pass per layer; each threadgroup then reads half the bytes, contiguous, unconverted.+struct PackParams {+ uint keys;+ uint paddedKeys;+ uint stride;+ uint heads;+};++kernel void attention_pack_kv(device const float *k [[buffer(0)]], device const float *v [[buffer(1)]],+ device half *kp [[buffer(2)]], device half *vp [[buffer(3)]],+ constant PackParams &p [[buffer(4)]], uint3 g [[thread_position_in_grid]]) {+ uint c4 = g.x, r = g.y, h = g.z; // c4: 4 columns+ if (c4 >= D / 4 || r >= p.paddedKeys || h >= p.heads) return;+ ulong at = ((ulong)h * p.paddedKeys + r) * D / 4 + c4;+ if (r < p.keys) {+ ulong from = (ulong)r * p.stride / 4 + h * D / 4 + c4;+ ((device half4 *)kp)[at] = half4(((device const float4 *)k)[from]);+ ((device half4 *)vp)[at] = half4(((device const float4 *)v)[from]);+ } else {+ ((device half4 *)kp)[at] = half4(0.0h);+ ((device half4 *)vp)[at] = half4(0.0h);+ }+}++// `flash_attention_half` on the packed K and V: the same tiles and arithmetic, loads straight from fp16.+kernel void flash_attention_packed(device const float *q [[buffer(0)]], device const half *kp [[buffer(1)]],+ device const half *vp [[buffer(2)]], device float *out [[buffer(3)]],+ constant FlashParams &p [[buffer(4)]], constant uint &paddedKeys [[buffer(5)]],+ 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 half ktile[BK * D];+ threadgroup half vtile[BK * D];+ threadgroup half *qstage = ktile + sg * 8 * D;++ const uint head = p.headBase + tg.y;+ const uint q0 = tg.x * BQ + sg * 8;+ const uint stride = p.stride;+ device const half4 *kh = (device const half4 *)(kp + (ulong)head * paddedKeys * D);+ device const half4 *vh = (device const half4 *)(vp + (ulong)head * paddedKeys * D);++ for (uint i = lane; i < 8 * D; i += 32) qstage[i] = half(q[(ulong)(q0 + i / D) * stride + head * D + i % D]);+ threadgroup_barrier(mem_flags::mem_threadgroup);+ simdgroup_half8x8 Q[16];+ simdgroup_float8x8 O[16];+ for (uint d = 0; d < 16; d++) {+ simdgroup_load(Q[d], qstage + 8 * d, D);+ O[d] = make_filled_simdgroup_matrix<float, 8, 8>(0.0f);+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ const uint row = (lane / 16) * 4 + (lane / 2) % 4;+ const uint col = ((lane / 8) % 2) * 4 + (lane % 2) * 2;+ 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) {+ for (uint i = tid; i < BK * D / 4; i += 256) {+ ((threadgroup half4 *)ktile)[i] = kh[(ulong)j0 * D / 4 + i];+ ((threadgroup half4 *)vtile)[i] = vh[(ulong)j0 * D / 4 + i];+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ simdgroup_float8x8 S[8];+ for (uint c = 0; c < 8; c++) S[c] = make_filled_simdgroup_matrix<float, 8, 8>(0.0f);+ for (uint d = 0; d < 16; d++) {+ for (uint c = 0; c < 8; c++) {+ simdgroup_half8x8 Kt;+ simdgroup_load(Kt, ktile + 8 * c * D + 8 * d, D, ulong2(0, 0), true);+ simdgroup_multiply_accumulate(S[c], Q[d], Kt, S[c]);+ }+ }++ float2 s[8];+ float blockMax = -INFINITY;+ for (uint c = 0; c < 8; c++) {+ s[c] = elements(S[c]) * p.scale;+ int j = int(j0 + 8 * c + col);+ if (j > limit) s[c].x = -INFINITY;+ if (j + 1 > limit) s[c].y = -INFINITY;+ blockMax = max(blockMax, max(s[c].x, s[c].y));+ }+ blockMax = max(blockMax, simd_shuffle_xor(blockMax, 1));+ blockMax = max(blockMax, simd_shuffle_xor(blockMax, 8));+ float mNew = max(m, blockMax);+ float alpha = (mNew == -INFINITY) ? 1.0f : exp2(m - mNew);+ float sum = 0.0f;+ simdgroup_half8x8 P[8];+ for (uint c = 0; c < 8; c++) {+ float2 e = (mNew == -INFINITY) ? float2(0.0f) : exp2(s[c] - mNew);+ elementsHalf(P[c]) = half2(e);+ sum += e.x + e.y;+ }+ sum += simd_shuffle_xor(sum, 1);+ sum += simd_shuffle_xor(sum, 8);+ l = l * alpha + sum;+ m = mNew;+ if (!simd_all(alpha == 1.0f)) {+ for (uint d = 0; d < 16; d++) elements(O[d]) *= alpha;+ }+ for (uint d = 0; d < 16; d++) {+ for (uint c = 0; c < 8; c++) {+ simdgroup_half8x8 V;+ simdgroup_load(V, vtile + 8 * c * D + 8 * d, D);+ simdgroup_multiply_accumulate(O[d], P[c], V, O[d]);+ }+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);+ }++ if (qi < p.queries) {+ const float inv = 1.0f / l;+ device float *o = out + (ulong)qi * stride + head * D + col;+ for (uint d = 0; d < 16; d++) {+ float2 e = elements(O[d]) * inv;+ o[8 * d] = e.x;+ o[8 * d + 1] = e.y;+ }+ }+}++// The same on GPUs that prefer device loads to threadgroup tiles (Apple9+, M3 and later: MFA's and libnnc's tables):+// each SIMD group reads the packed K and V straight from memory, no threadgroup tiles, no barriers in the loop.+kernel void flash_attention_direct(device const float *q [[buffer(0)]], device const half *kp [[buffer(1)]],+ device const half *vp [[buffer(2)]], device float *out [[buffer(3)]],+ constant FlashParams &p [[buffer(4)]], constant uint &paddedKeys [[buffer(5)]],+ 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 half qtile[BQ * D];+ threadgroup half *qstage = qtile + sg * 8 * D;++ const uint head = p.headBase + tg.y;+ const uint q0 = tg.x * BQ + sg * 8;+ const uint stride = p.stride;+ device const half *kh = kp + (ulong)head * paddedKeys * D;+ device const half *vh = vp + (ulong)head * paddedKeys * D;++ for (uint i = lane; i < 8 * D; i += 32) qstage[i] = half(q[(ulong)(q0 + i / D) * stride + head * D + i % D]);+ threadgroup_barrier(mem_flags::mem_threadgroup);+ simdgroup_half8x8 Q[16];+ simdgroup_float8x8 O[16];+ for (uint d = 0; d < 16; d++) {+ simdgroup_load(Q[d], qstage + 8 * d, D);+ O[d] = make_filled_simdgroup_matrix<float, 8, 8>(0.0f);+ }+ threadgroup_barrier(mem_flags::mem_threadgroup);++ const uint row = (lane / 16) * 4 + (lane / 2) % 4;+ const uint col = ((lane / 8) % 2) * 4 + (lane % 2) * 2;+ 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) {++ simdgroup_float8x8 S[8];+ for (uint c = 0; c < 8; c++) S[c] = make_filled_simdgroup_matrix<float, 8, 8>(0.0f);+ for (uint d = 0; d < 16; d++) {+ for (uint c = 0; c < 8; c++) {+ simdgroup_half8x8 Kt;+ simdgroup_load(Kt, kh + (ulong)(j0 + 8 * c) * D + 8 * d, D, ulong2(0, 0), true);+ simdgroup_multiply_accumulate(S[c], Q[d], Kt, S[c]);+ }+ }++ float2 s[8];+ float blockMax = -INFINITY;+ for (uint c = 0; c < 8; c++) {+ s[c] = elements(S[c]) * p.scale;+ int j = int(j0 + 8 * c + col);+ if (j > limit) s[c].x = -INFINITY;+ if (j + 1 > limit) s[c].y = -INFINITY;+ blockMax = max(blockMax, max(s[c].x, s[c].y));+ }+ blockMax = max(blockMax, simd_shuffle_xor(blockMax, 1));+ blockMax = max(blockMax, simd_shuffle_xor(blockMax, 8));+ float mNew = max(m, blockMax);+ float alpha = (mNew == -INFINITY) ? 1.0f : exp2(m - mNew);+ float sum = 0.0f;+ simdgroup_half8x8 P[8];+ for (uint c = 0; c < 8; c++) {+ float2 e = (mNew == -INFINITY) ? float2(0.0f) : exp2(s[c] - mNew);+ elementsHalf(P[c]) = half2(e);+ sum += e.x + e.y;+ }+ sum += simd_shuffle_xor(sum, 1);+ sum += simd_shuffle_xor(sum, 8);+ l = l * alpha + sum;+ m = mNew;+ if (!simd_all(alpha == 1.0f)) {+ for (uint d = 0; d < 16; d++) elements(O[d]) *= alpha;+ }+ for (uint d = 0; d < 16; d++) {+ for (uint c = 0; c < 8; c++) {+ simdgroup_half8x8 V;+ simdgroup_load(V, vh + (ulong)(j0 + 8 * c) * D + 8 * d, D);+ simdgroup_multiply_accumulate(O[d], P[c], V, O[d]);+ }+ }+ }++ if (qi < p.queries) {+ const float inv = 1.0f / l;+ device float *o = out + (ulong)qi * stride + head * D + col;+ for (uint d = 0; d < 16; d++) {+ float2 e = elements(O[d]) * inv;+ o[8 * d] = e.x;+ o[8 * d + 1] = e.y;+ }+ }+}diff --git a/engine-mac/Sources/KokonEngine/QwenDiT.swift b/engine-mac/Sources/KokonEngine/QwenDiT.swiftindex 63c0de5..cc1fc2e 100644--- a/engine-mac/Sources/KokonEngine/QwenDiT.swift+++ b/engine-mac/Sources/KokonEngine/QwenDiT.swift@@ -42,6 +42,9 @@ public final class QwenDiT {let x, normed, q, k, v, attended, o, h1, h2: Arena.Slicelet reserves: [Arena.Slice]let rope, modulation, qkNorms, textNorm, textIn, textOut, latent, output: Arena.Slice+ /// K and V packed for the flash kernel (`attention_pack_kv`): fp16, heads first, keys padded to 64.+ let kPacked, vPacked: Arena.Slice+ let paddedKeys: Intprivate var nextReserve = 0private var products: [String: MPSMatrixMultiplication] = [:]/// The AMX and the Neural Engine beside the GPU on the large products and the target's attention@@ -66,7 +69,8 @@ public final class QwenDiT {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]+ s * QwenDiT.channels, s * QwenDiT.channels,+ QwenDiT.heads * (n + 63) / 64 * 64 * QwenDiT.headDim / 2, QwenDiT.heads * (n + 63) / 64 * 64 * QwenDiT.headDim / 2]let arena = try Arena(device: context.device, bytes: Arena.bytes(sizes.map { $0 * 4 }))self.arena = arenavar slices = try sizes.map { try arena.slice(floats: $0) }.makeIterator()@@ -75,6 +79,8 @@ public final class QwenDiT {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()!+ kPacked = slices.next()!; vPacked = slices.next()!+ paddedKeys = (n + 63) / 64 * 64let environment = ProcessInfo.processInfo.environmentif environment["KOKON_COEXEC"] != "0", sequence.count >= 1024 {@@ -475,8 +481,14 @@ public final class QwenDiT {/// fp16 operands by default (Gabriele 10-25: 76.0 s against 79.9 s per 1024² image, the velocity within 6e-4 of/// fp64 instead of 1e-5); `KOKON_ATTENTION=fp32` keeps the fp32 kernel (the accuracy checks).let graphAttention = ProcessInfo.processInfo.environment["KOKON_ATTENTION"] == "graph"- let flashKernel = ProcessInfo.processInfo.environment["KOKON_ATTENTION"] == "fp32" ? "flash_attention" : "flash_attention_half"+ let flashKernel = ProcessInfo.processInfo.environment["KOKON_ATTENTION"] == "fp32" ? "flash_attention" : "flash_attention_half" // "unpacked": no K/V packingstruct FlashParams { var queries, keys, causal, stride: UInt32; var scale: Float; var headBase: UInt32 }+ struct PackParams { var keys, paddedKeys, stride, heads: UInt32 }+ /// The target's attention (not causal) on K and V packed first to fp16, heads first: 1024², 32 heads, M2 Pro+ /// (`probe-attention`, 2026-10-25): 91.0 ms with the packing against 95.2 for `flash_attention_half`, the same+ /// accuracy. Apple9+ GPUs (M3 and later) read the packed K and V straight from memory (`flash_attention_direct`),+ /// as MFA's and libnnc's tables do there; on the M2 Pro that variant takes 142 ms. Not yet measured on an M3+.+ lazy var packedKernel = context.device.supportsFamily(.apple9) ? "flash_attention_direct" : "flash_attention_packed"/// Queries `[queries, queries + count)` against keys `[0, keys)`, into the same rows of `attended`. The target's/// queries are cut by heads with the Neural Engine and the CPU when the co-executor runs (`AttentionSplit.swift`).@@ -515,15 +527,28 @@ public final class QwenDiT {func flash(queries: Int, count: Int, keys: Int, causal: Bool, heads: Int, commands: MTLCommandBuffer) throws {guard heads > 0 else { return }let row = QwenDiT.dim * 4- try compute(flashKernel, commands: commands) { e in+ let packed = !causal && flashKernel == "flash_attention_half" && ProcessInfo.processInfo.environment["KOKON_ATTENTION"] != "unpacked"+ if packed {+ try compute("attention_pack_kv", commands: commands) { e in+ e.setBuffer(arena.buffer, offset: k.offset, index: 0); e.setBuffer(arena.buffer, offset: v.offset, index: 1)+ e.setBuffer(arena.buffer, offset: kPacked.offset, index: 2); e.setBuffer(arena.buffer, offset: vPacked.offset, index: 3)+ var pp = PackParams(keys: UInt32(keys), paddedKeys: UInt32(paddedKeys), stride: UInt32(QwenDiT.dim), heads: UInt32(heads))+ e.setBytes(&pp, length: MemoryLayout<PackParams>.stride, index: 4)+ e.dispatchThreads(MTLSize(width: QwenDiT.headDim / 4, height: paddedKeys, depth: heads),+ threadsPerThreadgroup: MTLSize(width: 32, height: 8, depth: 1))+ }+ }+ try compute(packed ? packedKernel : flashKernel, commands: commands) { e ine.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: packed ? kPacked.offset : k.offset, index: 1)+ e.setBuffer(arena.buffer, offset: packed ? vPacked.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)+ var padded = UInt32(paddedKeys)+ if packed { e.setBytes(&padded, length: 4, index: 5) }e.dispatchThreadgroups(MTLSize(width: (count + 63) / 64, height: heads, depth: 1),threadsPerThreadgroup: MTLSize(width: 256, height: 1, depth: 1))}diff --git a/engine-mac/Tests/KokonEngineTests/AttentionTests.swift b/engine-mac/Tests/KokonEngineTests/AttentionTests.swiftindex 56c1fef..f86708e 100644--- a/engine-mac/Tests/KokonEngineTests/AttentionTests.swift+++ b/engine-mac/Tests/KokonEngineTests/AttentionTests.swift@@ -7,7 +7,11 @@ import XCTestfinal 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) {+ struct PackParams { var keys, paddedKeys, stride, heads: UInt32 }++ /// `kernel` on K and V packed by `attention_pack_kv` when `packed`.+ func run(queries: Int, keys: Int, causal: Bool, heads: Int = 2, magnitude: Float = 4,+ kernel: String = "flash_attention", packed: Bool = false) throws -> (worst: Double, untouched: Bool) {let context = try MetalContext()let stride = heads * 128, padding = 64let rows = max(queries, keys) + padding@@ -27,9 +31,22 @@ final class AttentionTests: XCTestCase {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 paddedKeys = (keys + 63) / 64 * 64+ let kp = try context.scratch(heads * paddedKeys * 128 * 2, label: "kp"), vp = try context.scratch(heads * paddedKeys * 128 * 2, label: "vp")+ if packed {+ let e = commands.makeComputeCommandEncoder()!+ e.setComputePipelineState(try context.pipeline("attention_pack_kv"))+ for (i, b) in [kb, vb, kp, vp].enumerated() { e.setBuffer(b, offset: 0, index: i) }+ var pp = PackParams(keys: UInt32(keys), paddedKeys: UInt32(paddedKeys), stride: UInt32(stride), heads: UInt32(heads))+ e.setBytes(&pp, length: MemoryLayout<PackParams>.stride, index: 4)+ e.dispatchThreads(MTLSize(width: 32, height: paddedKeys, depth: heads), threadsPerThreadgroup: MTLSize(width: 32, height: 8, depth: 1))+ e.endEncoding()+ }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) }+ e.setComputePipelineState(try context.pipeline(kernel))+ for (i, b) in [qb, packed ? kp : kb, packed ? vp : vb, ob].enumerated() { e.setBuffer(b, offset: 0, index: i) }+ var padded = UInt32(paddedKeys)+ if packed { e.setBytes(&padded, length: 4, index: 5) }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)@@ -88,4 +105,15 @@ final class AttentionTests: XCTestCase {XCTAssertTrue(r.untouched, "\(q)×\(k) causal wrote past its queries")}}++ /// The fp16 kernels on packed K and V (the target's attention): within fp16's rounding of exact.+ func testPacked() throws {+ for kernel in ["flash_attention_packed", "flash_attention_direct"] {+ for (q, k) in [(32, 32), (40, 70), (100, 130), (7, 300)] {+ let r = try run(queries: q, keys: k, causal: false, kernel: kernel, packed: true)+ XCTAssertLessThan(r.worst, 5e-3, "\(kernel) \(q)×\(k)")+ XCTAssertTrue(r.untouched, "\(kernel) \(q)×\(k) wrote past its queries")+ }+ }+ }}