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 Neural Engine's rows packed once per input (q/k/v, gate/proj)

Gabriele Lozupone57986b385142
diff --git a/engine-mac/README.md b/engine-mac/README.md
index 5ea6ef0..e64d959 100644
--- a/engine-mac/README.md
+++ b/engine-mac/README.md
@@ -216,6 +216,12 @@ worse). Between operations 0.60 → 0.53 s, but per evaluation, 3 alternated rou
instead of 66). With the three units at their shared limit, the GPU-alone time moved into the products; what pays
is fewer bytes moved, as with the fp16 cast above.
+**The Neural Engine's rows packed once per input** (`KOKON_SHARED_ROWS=0` for the comparison): q, k and v read the
+same rows, and so do gate and proj, but each product scaled and packed them again with its own σ. From the second
+evaluation on (when every weight's L is known), an input's rows get one σ from the largest L of its readers and are
+packed for the first only. Velocity at 896²: 6.36–7.02e-4 (6.74–6.88e-4 before). 1024², 3 alternated rounds of 4
+evaluations (M2 Pro, 2026-10-25): 7.64 → 7.58 s, between operations 0.65 → 0.60 s.
+
**1024² image after this pass (M2 Pro, `generate`, 2026-10-25): 67.3–68.0 s** (text encoder 2.0 s, step 1 8.35 s,
steps 2–8 7.3–7.7 s, VAE 5.0–5.3 s with its first run at the size; 79.9 s at the start of the fp16 work, 76.0 with
fp16 attention). `MTLBinaryArchive` was not added: the engine's kernels compile from source in 0.1 s at start (macOS
diff --git a/engine-mac/Sources/KokonEngine/Coexecution.swift b/engine-mac/Sources/KokonEngine/Coexecution.swift
index 5504866..b7f45f6 100644
--- a/engine-mac/Sources/KokonEngine/Coexecution.swift
+++ b/engine-mac/Sources/KokonEngine/Coexecution.swift
@@ -37,6 +37,14 @@ final class Coexecutor {
/// The set of the last product encoded; the weight packed ahead and its set.
private var currentSet = 0
private var packedAhead: (weight: String, set: Int)?
+ /// **The Neural Engine's rows packed once per input**: q, k, v read the same rows, and so do gate and proj. Once the
+ /// L of all of an input's readers is known (from their first use), its rows are scaled with one σ, from the largest L
+ /// (the bound holds for each; a power of two less only moves where fp16 flushes, far below the row's values), and
+ /// packed for the first reader only: the others find them in the row surfaces, which both sets share.
+ /// `KOKON_SHARED_ROWS=0`: every product packs its own.
+ let sharedRows = ProcessInfo.processInfo.environment["KOKON_SHARED_ROWS"] != "0"
+ /// The input the row surfaces hold for its readers (A's offset), when packed with their shared σ.
+ private var packedRows: (offset: Int, readers: [String])?
var balancer: Balancer
/// The timeline of the last evaluation, once the balancing loop has read it.
var lastTimeline: [Timeline.Entry] = []
@@ -124,6 +132,7 @@ final class Coexecutor {
if aneRows > 0 { spareSlots = [aneRows: slots] } // the last one only: 288 MB of surfaces at 2 048 rows
(slots, aneRows) = (next, rows)
packedAhead = nil
+ packedRows = nil
}
/// Whether a product takes the split: the Neural Engine's tiles need K and N in multiples of 4 096 with at
@@ -156,7 +165,7 @@ final class Coexecutor {
func encode(weight: String, a: (buffer: MTLBuffer, offset: Int, pointer: UnsafeMutablePointer<Float>),
w: (buffer: MTLBuffer, offset: Int, pointer: UnsafeMutablePointer<Float>),
c: (buffer: MTLBuffer, offset: Int, pointer: UnsafeMutablePointer<Float>),
- m: Int, k: Int, n: Int, commands: MTLCommandBuffer,
+ m: Int, k: Int, n: Int, commands: MTLCommandBuffer, readers: [String] = [],
castReady: Bool = false, ahead: ((MTLCommandBuffer) throws -> Void)? = nil,
gpuRows: (Int, MTLBuffer?) throws -> Void) throws {
let s = split(m: m, k: k, n: n)
@@ -189,10 +198,16 @@ final class Coexecutor {
packedAhead = nil
currentSet = set
let slots = self.slots[set]
- if s.ane > 0 {
+ let shared = sharedRows && readers.count > 1 && readers.count <= 3 && readers.contains(weight)
+ && readers.allSatisfy { columnScales[$0] != nil }
+ let packed = shared && packedRows.map { $0.offset == a.offset && $0.readers == readers } ?? false
+ if s.ane > 0, !packed {
var sh = shape()
+ let bounds = shared ? readers.map { columnScales[$0]! } : [columns]
+ packedRows = shared ? (a.offset, readers) : nil
try kernel("ane_row_scales") { e in
- e.setBuffer(a.buffer, offset: a.offset, index: 0); e.setBuffer(columns, offset: state, index: 1)
+ e.setBuffer(a.buffer, offset: a.offset, index: 0)
+ for i in 0..<3 { e.setBuffer(bounds[min(i, bounds.count - 1)], offset: state, index: i == 0 ? 1 : 3 + i) }
e.setBuffer(scales, offset: sigma, index: 2)
e.setBytes(&sh, length: MemoryLayout<Shape>.stride, index: 3)
e.dispatchThreadgroups(MTLSize(width: s.ane, height: 1, depth: 1), threadsPerThreadgroup: MTLSize(width: 256, height: 1, depth: 1))
diff --git a/engine-mac/Sources/KokonEngine/Kernels/ane.metal b/engine-mac/Sources/KokonEngine/Kernels/ane.metal
index 1d8bcec..5d45e0c 100644
--- a/engine-mac/Sources/KokonEngine/Kernels/ane.metal
+++ b/engine-mac/Sources/KokonEngine/Kernels/ane.metal
@@ -91,9 +91,11 @@ template [[host_name("ane_pack_weight")]] kernel void ane_pack_weight<float>(dev
template [[host_name("ane_pack_weight_h")]] kernel void ane_pack_weight<half>(device const half *, device const float *,
device half *, constant AneShape &, uint2);
-// σ_i of each Neural Engine row. One threadgroup of 256 per row.
+// σ_i of each Neural Engine row, for up to three weights reading the same rows (their L in `state`, `state1`,
+// `state2`; the same buffer again for fewer): the largest L bounds them all. One threadgroup of 256 per row.
kernel void ane_row_scales(device const float *a [[buffer(0)]], device const float *state [[buffer(1)]],
device float *sigma [[buffer(2)]], constant AneShape &s [[buffer(3)]],
+ device const float *state1 [[buffer(4)]], device const float *state2 [[buffer(5)]],
uint i [[threadgroup_position_in_grid]], uint tid [[thread_index_in_threadgroup]]) {
threadgroup float shared[8];
device const float *row = a + (ulong)(s.row0 + i) * s.k;
@@ -105,7 +107,7 @@ kernel void ane_row_scales(device const float *a [[buffer(0)]], device const flo
if (tid == 0) {
float peak = 0;
for (uint q = 0; q < 8; q++) peak = max(peak, shared[q]);
- float bound = peak * state[0];
+ float bound = peak * max(state[0], max(state1[0], state2[0]));
sigma[i] = (bound > 0 && isfinite(bound)) ? exp2(floor(log2(32768.0f / bound))) : 1.0f;
}
}
diff --git a/engine-mac/Sources/KokonEngine/QwenDiT.swift b/engine-mac/Sources/KokonEngine/QwenDiT.swift
index 5517208..cb9b1e6 100644
--- a/engine-mac/Sources/KokonEngine/QwenDiT.swift
+++ b/engine-mac/Sources/KokonEngine/QwenDiT.swift
@@ -307,10 +307,11 @@ public final class QwenDiT {
let band = 5 * d // the target's modulation row follows the prefix's
try layerNorm(x, into: normed, rows: rows, prefixMod: 0, targetMod: band,
half: halfOutput(count: count, k: d, n: d), commands: commands)
- try linear(block + "attn.to_q.weight", a: normed, aRow: first, c: q, m: count, cRow: first, next: block + "attn.to_k.weight", commands: commands)
- try linear(block + "attn.to_k.weight", a: normed, aRow: first, c: k, m: count, cRow: first, next: block + "attn.to_v.weight", commands: commands)
+ let qkv = ["to_q", "to_k", "to_v"].map { block + "attn.\($0).weight" }
+ try linear(qkv[0], a: normed, aRow: first, c: q, m: count, cRow: first, next: qkv[1], readers: qkv, commands: commands)
+ try linear(qkv[1], a: normed, aRow: first, c: k, m: count, cRow: first, next: qkv[2], readers: qkv, commands: commands)
try mark("norm1", normed)
- try linear(block + "attn.to_v.weight", a: normed, aRow: first, c: v, m: count, cRow: first, next: block + "attn.to_out.0.weight", commands: commands)
+ try linear(qkv[2], a: normed, aRow: first, c: v, m: count, cRow: first, next: block + "attn.to_out.0.weight", readers: qkv, commands: commands)
try headNormRope(q, weightOffset: (layer * 2) * QwenDiT.headDim, rows: rows, commands: commands)
try headNormRope(k, weightOffset: (layer * 2 + 1) * QwenDiT.headDim, rows: rows, commands: commands)
try mark("q", q); try mark("k", k); try mark("v", v)
@@ -331,8 +332,9 @@ public final class QwenDiT {
try layerNorm(x, into: normed, rows: rows, prefixMod: 2 * d, targetMod: band + 2 * d,
half: halfOutput(count: count, k: d, n: QwenDiT.hidden), commands: commands)
try mark("norm2", normed)
- try linear(block + "img_mlp.gate_layer.weight", a: normed, aRow: first, c: h1, m: count, cRow: first, next: block + "img_mlp.proj.weight", commands: commands)
- try linear(block + "img_mlp.proj.weight", a: normed, aRow: first, c: h2, m: count, cRow: first, next: block + "img_mlp.out.weight", commands: commands)
+ let gateProj = ["gate_layer", "proj"].map { block + "img_mlp.\($0).weight" }
+ try linear(gateProj[0], a: normed, aRow: first, c: h1, m: count, cRow: first, next: gateProj[1], readers: gateProj, commands: commands)
+ try linear(gateProj[1], a: normed, aRow: first, c: h2, m: count, cRow: first, next: block + "img_mlp.out.weight", readers: gateProj, commands: commands)
try swiglu(first: first, count: count, half: halfOutput(count: count, k: QwenDiT.hidden, n: d), commands: commands)
try linear(block + "img_mlp.out.weight", a: h1, aRow: first, c: o, m: count, cRow: first,
next: layer + 1 < QwenDiT.layers ? "transformer_blocks.\(layer + 1).attn.to_q.weight" : nil, commands: commands)
@@ -394,8 +396,9 @@ public final class QwenDiT {
/// `aRow`, `cRow`: first row of A and C in their slices. `next`: the weight of the product that follows, unpacked
/// into the other reserve and packed for the Neural Engine while the AMX and the Neural Engine run this one (the
/// GPU's ~1.8 ms per 4096 × 4096 weight otherwise ran alone between products).
+ /// `readers`: every weight that reads this same A (q, k, v; gate, proj), so the Neural Engine's rows are packed once.
func linear(_ name: String, a: Arena.Slice, aRow: Int = 0, c: Arena.Slice, m: Int, cRow: Int = 0,
- next: String? = nil, commands: MTLCommandBuffer) throws {
+ next: String? = nil, readers: [String] = [], commands: MTLCommandBuffer) throws {
let tensor = try weight(name)
let (kk, nn) = (tensor.columns, tensor.rows)
let m = QwenDiT.padded(m)
@@ -452,7 +455,7 @@ public final class QwenDiT {
}
let ready = castInput.map { $0 == (a.offset, aRow, kk) } ?? false
try coexecutor.encode(weight: name, a: operand(a, aRow, kk), w: operand(reserve, 0, nn), c: operand(c, cRow, nn),
- m: m, k: kk, n: nn, commands: commands, castReady: ready, ahead: ahead, gpuRows: gpuRows)
+ m: m, k: kk, n: nn, commands: commands, readers: readers, castReady: ready, ahead: ahead, gpuRows: gpuRows)
castInput = c.offset == a.offset ? nil : (a.offset, aRow, kk)
} else {
try gpuRows(m)