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: remember balanced shares per Mac and shape; parallel column scales

Gabriele Lozupone01c78b9e7157
diff --git a/engine-mac/Sources/KokonEngine/Balancer.swift b/engine-mac/Sources/KokonEngine/Balancer.swift
index 9d311fc..88f447a 100644
--- a/engine-mac/Sources/KokonEngine/Balancer.swift
+++ b/engine-mac/Sources/KokonEngine/Balancer.swift
@@ -13,9 +13,12 @@ import Foundation
/// A new cut is taken only when it is predicted 1.5 % faster, so the shares settle instead of flickering. Rates are
/// smoothed over evaluations and start from the M2 Pro's, so a unit without a share keeps an estimate. Moving a
/// share moves which rows go through the Neural Engine's fp16: images stay within its accuracy, not bit for bit.
-struct Balancer {
+///
+/// The shares and rates are remembered per Mac and shape (`Memory`), so the next run starts balanced: at 1024² on the
+/// M2 Pro the first evaluation took ~11.5 s at the starting shares against ~8.9 balanced.
+struct Balancer: Codable {
/// Rows (heads, for attention) per millisecond.
- struct Rates { var gpu: Double, amx: Double, ane: Double }
+ struct Rates: Codable { var gpu: Double, amx: Double, ane: Double }
var rates: [String: Rates]
/// The AMX's measured rate at each row count tried, per kind: it is not linear in rows (MLP out on the M2 Pro:
/// 320 rows 31 ms, 384 rows 43 ms), so a measured count beats the extrapolated rate.
@@ -115,6 +118,7 @@ extension Coexecutor {
try prepareAttention(queries: attentionShape.queries, keys: attentionShape.keys)
}
}
+ remember()
}
/// The shares the next evaluation takes.
@@ -123,3 +127,42 @@ extension Coexecutor {
return "products ANE \(aneRows) rows, AMX \(amx.isEmpty ? "default" : amx); attention \(heads)"
}
}
+
+extension Coexecutor {
+ /// What the balancing loop learned, per Mac, shape and units on: `~/Library/Caches/kokon-engine-mac/balance.json`.
+ struct Memory: Codable {
+ var aneRows: Int
+ var amxRows: [String: Int]
+ var heads: [Int]
+ var balancer: Balancer
+
+ static let url = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0]
+ .appendingPathComponent("kokon-engine-mac/balance.json")
+
+ static func all() -> [String: Memory] {
+ guard let data = try? Data(contentsOf: url) else { return [:] }
+ return (try? JSONDecoder().decode([String: Memory].self, from: data)) ?? [:]
+ }
+ }
+
+ var memoryKey: String {
+ "\(context.device.name) rows \(rows) ane \(aneEnabled) amx \(amxEnabled) ane-attention \(balancer.aneAttention)"
+ }
+
+ /// Takes the remembered shares for this Mac and shape, if any.
+ func recall() throws {
+ guard let m = Memory.all()[memoryKey], m.heads.count == 3, m.heads.reduce(0, +) == QwenDiT.heads else { return }
+ balancer = m.balancer
+ amxRows = m.amxRows
+ if HeadSplit.fromEnvironment() == nil { heads = HeadSplit(gpu: m.heads[0], ane: m.heads[1], cpu: m.heads[2]) }
+ if aneEnabled, m.aneRows >= 1024, m.aneRows <= rows - 512 { try setAneRows(m.aneRows) }
+ }
+
+ /// Writes the current shares (failures only cost the next run its head start).
+ func remember() {
+ var all = Memory.all()
+ all[memoryKey] = Memory(aneRows: aneRows, amxRows: amxRows, heads: [heads.gpu, heads.ane, heads.cpu], balancer: balancer)
+ try? FileManager.default.createDirectory(at: Memory.url.deletingLastPathComponent(), withIntermediateDirectories: true)
+ if let data = try? JSONEncoder().encode(all) { try? data.write(to: Memory.url, options: .atomic) }
+ }
+}
diff --git a/engine-mac/Sources/KokonEngine/Coexecution.swift b/engine-mac/Sources/KokonEngine/Coexecution.swift
index 4b09c9f..4724329 100644
--- a/engine-mac/Sources/KokonEngine/Coexecution.swift
+++ b/engine-mac/Sources/KokonEngine/Coexecution.swift
@@ -147,7 +147,8 @@ final class Coexecutor {
e.setBuffer(w.buffer, offset: w.offset, index: 0)
e.setBuffer(columns, offset: lambda, index: 1); e.setBuffer(columns, offset: norm, index: 2)
e.setBytes(&sh, length: MemoryLayout<Shape>.stride, index: 3)
- e.dispatchThreads(MTLSize(width: n, height: 1, depth: 1), threadsPerThreadgroup: MTLSize(width: 64, height: 1, depth: 1))
+ e.dispatchThreadgroups(MTLSize(width: (n + 63) / 64, height: 1, depth: 1),
+ threadsPerThreadgroup: MTLSize(width: 64, height: 16, depth: 1))
}
try kernel("ane_norm") { e in
e.setBuffer(columns, offset: norm, index: 0); e.setBuffer(columns, offset: state, index: 1)
diff --git a/engine-mac/Sources/KokonEngine/Kernels/ane.metal b/engine-mac/Sources/KokonEngine/Kernels/ane.metal
index 0e7e6a5..553af89 100644
--- a/engine-mac/Sources/KokonEngine/Kernels/ane.metal
+++ b/engine-mac/Sources/KokonEngine/Kernels/ane.metal
@@ -27,20 +27,31 @@ struct AneShape {
uint kParts; // tiles along K (unpack)
};
-// Per column of W [k, n]: λ_j and the lifted column's L1 norm. One thread per column (coalesced rows).
+// Per column of W [k, n]: λ_j and the lifted column's L1 norm. A threadgroup takes 64 columns, 16 row slices of
+// each (coalesced rows), combined in threadgroup memory: one thread per column walking every row took ~8 ms per
+// 4096 × 12288 weight (M2 Pro).
kernel void ane_columns(device const float *w [[buffer(0)]], device float *lambda [[buffer(1)]],
device float *norm [[buffer(2)]], constant AneShape &s [[buffer(3)]],
- uint j [[thread_position_in_grid]]) {
- if (j >= s.n) return;
+ uint2 tg [[threadgroup_position_in_grid]], uint2 t [[thread_position_in_threadgroup]]) {
+ threadgroup float peaks[16][64], sums[16][64];
+ uint j = tg.x * 64 + t.x;
float peak = 0, sum = 0;
- for (uint r = 0; r < s.k; r++) {
- float v = fabs(w[(ulong)r * s.n + j]);
- peak = max(peak, v);
- sum += v;
+ if (j < s.n) {
+ for (uint r = t.y; r < s.k; r += 16) {
+ float v = fabs(w[(ulong)r * s.n + j]);
+ peak = max(peak, v);
+ sum += v;
+ }
+ }
+ peaks[t.y][t.x] = peak;
+ sums[t.y][t.x] = sum;
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ if (t.y == 0 && j < s.n) {
+ for (uint i = 1; i < 16; i++) { peak = max(peak, peaks[i][t.x]); sum += sums[i][t.x]; }
+ float l = (peak > 0 && isfinite(peak)) ? exp2(-floor(log2(peak))) : 1.0f;
+ lambda[j] = l;
+ norm[j] = sum * l;
}
- float l = (peak > 0 && isfinite(peak)) ? exp2(-floor(log2(peak))) : 1.0f;
- lambda[j] = l;
- norm[j] = sum * l;
}
// L = max_j norm[j], into state[0]. One threadgroup of 1 024.
diff --git a/engine-mac/Sources/KokonEngine/QwenDiT.swift b/engine-mac/Sources/KokonEngine/QwenDiT.swift
index 20f6f53..24cd782 100644
--- a/engine-mac/Sources/KokonEngine/QwenDiT.swift
+++ b/engine-mac/Sources/KokonEngine/QwenDiT.swift
@@ -81,6 +81,7 @@ public final class QwenDiT {
} else {
coexecutor = nil
}
+ if let coexecutor, environment["KOKON_BALANCE"] != "0" { try coexecutor.recall() }
if let coexecutor, coexecutor.attentionApplies(queries: sequence.target) {
try coexecutor.prepareAttention(queries: sequence.target, keys: sequence.count)
}