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: on the M5 Pro, release each product to the AMX and the Neural Engine at once (#46)

Cesare Davide Pace1d071051d426
diff --git a/engine-mac/README.md b/engine-mac/README.md
index 8708452..ec170b7 100644
--- a/engine-mac/README.md
+++ b/engine-mac/README.md
@@ -435,6 +435,11 @@ correctness test that runs on any Mac (`PerChipTests`). Only the M2 Pro has meas
activation rows with outliers). **Finer scales do not fix it** (2026-10-25, below): int8 stays opt-in.
- **Attention reading K and V straight from memory** (`flash_attention_direct`) on Apple9+ GPUs (M3 and later), as
MFA's tables prefer there (`KOKON_ATTENTION_DIRECT=0` off); 142 ms on the M2 Pro against 91, unmeasured on an M3+.
+- **Each product released at once** on the M5 Pro (`KOKON_FLUSH_READY=0` off): a wait on `ready` right after its
+ signal. On the M5 Pro (macOS 26.6) a signal inside a command buffer reaches the CPU only at the next wait the
+ command buffer encodes, which was after the GPU's own rows: the AMX and the Neural Engine ran after the GPU instead of
+ beside it, and the balancer, reading ~1 ms for the GPU's rows, gave them almost nothing. M5 Pro 20-core, 24 GB,
+ `time-dit` at 1024², 3 alternated rounds (third evaluation): 5.50–5.89 → 4.44–4.46 s.
- **Starting shares per chip**: the balancer's M2 Pro rates scaled by the chip's estimated units (GPU cores × clock,
the Neural Engine's published TOPS, performance cores; `Chip.unitScale`), so the first image starts near balanced;
the loop measures the real rates from the first evaluation on.
diff --git a/engine-mac/Sources/KokonEngine/AttentionSplit.swift b/engine-mac/Sources/KokonEngine/AttentionSplit.swift
index c2d1459..8f9c094 100644
--- a/engine-mac/Sources/KokonEngine/AttentionSplit.swift
+++ b/engine-mac/Sources/KokonEngine/AttentionSplit.swift
@@ -112,7 +112,7 @@ extension Coexecutor {
shape(g, rows: slot.program.queries, valid: min(slot.program.queries, queries - row0), row0: row0, factor: scale))
}
}
- if split.ane > 0 || split.cpu > 0 { commands.encodeSignalEvent(ready, value: p) }
+ if split.ane > 0 || split.cpu > 0 { release(p, commands) }
if split.cpu > 0 {
nonisolated(unsafe) let (pq, pk, pv, po) = (q.pointer, k.pointer, v.pointer, out.pointer)
let range = (split.gpu + split.ane)..<QwenDiT.heads
diff --git a/engine-mac/Sources/KokonEngine/Balancer.swift b/engine-mac/Sources/KokonEngine/Balancer.swift
index a42c88a..006aef9 100644
--- a/engine-mac/Sources/KokonEngine/Balancer.swift
+++ b/engine-mac/Sources/KokonEngine/Balancer.swift
@@ -169,7 +169,7 @@ extension Coexecutor {
}
var memoryKey: String {
- "\(context.device.name) rows \(rows) ane \(aneEnabled)\(aneInt8 ? aneHalfRows ? " w8" : " int8" : "") amx \(amxEnabled) ane-attention \(balancer.aneAttention)"
+ "\(context.device.name) rows \(rows) ane \(aneEnabled)\(aneInt8 ? aneHalfRows ? " w8" : " int8" : "") amx \(amxEnabled) ane-attention \(balancer.aneAttention)\(flushRelease ? " flush" : "")"
}
/// Takes the remembered shares for this Mac and shape, if any.
diff --git a/engine-mac/Sources/KokonEngine/Bench.swift b/engine-mac/Sources/KokonEngine/Bench.swift
index b5b5922..f46a4cd 100644
--- a/engine-mac/Sources/KokonEngine/Bench.swift
+++ b/engine-mac/Sources/KokonEngine/Bench.swift
@@ -28,6 +28,9 @@ public enum Bench {
if NeuralAccelerators.selected(device: device), NeuralAccelerators.make(device: device) != nil {
paths.append(("GPU products on Metal 4 tensor operations (the M5's neural accelerators; shader cores before)", "KOKON_NA", "0"))
}
+ if Coexecutor.flushReleaseSelected(chipName: chip.name) {
+ paths.append(("each product released to the AMX and the Neural Engine at once (M5 Pro path)", "KOKON_FLUSH_READY", "0"))
+ }
if QwenDiT.directAttention(device: device) {
paths.append(("attention reading K/V straight from memory (Apple9+ path)", "KOKON_ATTENTION_DIRECT", "0"))
}
diff --git a/engine-mac/Sources/KokonEngine/Coexecution.swift b/engine-mac/Sources/KokonEngine/Coexecution.swift
index 308c36a..5977c9b 100644
--- a/engine-mac/Sources/KokonEngine/Coexecution.swift
+++ b/engine-mac/Sources/KokonEngine/Coexecution.swift
@@ -82,6 +82,29 @@ final class Coexecutor {
}
}
static var int8Rows: Bool { ProcessInfo.processInfo.environment["KOKON_ANE_INT8"] != "w8" }
+ /// **The release made visible at once**: a wait on `ready` right after its signal. On the M5 Pro (macOS 26.6) a
+ /// signal inside a command buffer reaches the CPU only at the command buffer's end or at the next wait it encodes
+ /// (a 3 × 20 ms test: the CPU saw the three signals at 60 / 60 / 60 ms, with a wait after each at 20 / 40 / 60).
+ /// Here the next wait is after the GPU's own rows, so the AMX and the Neural Engine started only when the GPU was
+ /// done, one after the other instead of together, and the timeline read the GPU's rows as ~1 ms. The wait is on a
+ /// value already reached: the GPU does not stop. Measured on the M5 Pro only; `KOKON_FLUSH_READY=0` / `=1`.
+ let flushRelease: Bool
+ static func flushReleaseSelected(chipName: String) -> Bool {
+ switch ProcessInfo.processInfo.environment["KOKON_FLUSH_READY"] {
+ case "0": return false
+ case "1": return true
+ default: return chipName == "Apple M5 Pro"
+ }
+ }
+
+ /// Releases operation `p` to the AMX and the Neural Engine.
+ func release(_ p: UInt64, _ commands: MTLCommandBuffer) {
+ Coexecutor.release(ready, p, flush: flushRelease, commands)
+ }
+ static func release(_ event: MTLSharedEvent, _ p: UInt64, flush: Bool, _ commands: MTLCommandBuffer) {
+ commands.encodeSignalEvent(event, value: p)
+ if flush { commands.encodeWaitForEvent(event, value: p) }
+ }
/// The reserves hold fp16 weights (`QwenDiT.halfWeights`): the AMX and the Neural Engine's packing read them so.
let halfWeights: Bool
/// **The GPU's and the AMX's rows of A read as fp16**, cast by the GPU into `aHalf` (`KOKON_ACTIVATIONS=fp32`: off).
@@ -113,6 +136,7 @@ final class Coexecutor {
self.amxEnabled = amx
aneInt8 = ane && Coexecutor.int8Selected(Chip.current)
aneHalfRows = !Coexecutor.int8Rows
+ flushRelease = Coexecutor.flushReleaseSelected(chipName: Chip.current.name)
// The first evaluation's shares from the cost model on this chip's estimated rates (`Chip.unitScale`; on the
// M2 Pro its measured ones). Remembered shares replace them (`recall`).
balancer = Balancer(aneAttention: ane && aneAttention, chip: Chip.current)
@@ -312,7 +336,7 @@ final class Coexecutor {
e.dispatchThreads(MTLSize(width: Int(count), height: 1, depth: 1), threadsPerThreadgroup: MTLSize(width: 256, height: 1, depth: 1))
}
}
- if s.amx > 0 || s.ane > 0 { commands.encodeSignalEvent(ready, value: p) }
+ if s.amx > 0 || s.ane > 0 { release(p, commands) }
// The next weight's own work while the AMX and the Neural Engine run this product.
try ahead?(commands)
if s.amx > 0 {
diff --git a/engine-mac/Tests/KokonEngineTests/PerChipTests.swift b/engine-mac/Tests/KokonEngineTests/PerChipTests.swift
index c23b9bb..d43b2f9 100644
--- a/engine-mac/Tests/KokonEngineTests/PerChipTests.swift
+++ b/engine-mac/Tests/KokonEngineTests/PerChipTests.swift
@@ -1,5 +1,6 @@
import CoreVideo
import Metal
+import QuartzCore
import XCTest
@testable import KokonEngine
@@ -104,3 +105,64 @@ extension PerChipTests {
}
}
}
+
+extension PerChipTests {
+ /// The release made visible at once (`KOKON_FLUSH_READY`): chosen on the M5 Pro only, where it was measured.
+ func testFlushReleaseSelection() throws {
+ guard ProcessInfo.processInfo.environment["KOKON_FLUSH_READY"] == nil else { throw XCTSkip("KOKON_FLUSH_READY is set") }
+ XCTAssertTrue(Coexecutor.flushReleaseSelected(chipName: "Apple M5 Pro"))
+ for name in ["Apple M1", "Apple M2 Pro", "Apple M3 Max", "Apple M4 Pro", "Apple M5", "Apple M5 Max", "Apple M6 Pro", ""] {
+ XCTAssertFalse(Coexecutor.flushReleaseSelected(chipName: name), name)
+ }
+ }
+
+ /// With the flush, the CPU sees the release while the GPU's work after it is still running, not at the command
+ /// buffer's end (on the M5 Pro without it: at the end). Any Mac: the flush is a wait on a value already reached.
+ func testFlushedReleaseReachesTheCPUBeforeTheEnd() throws {
+ let device = try XCTUnwrap(MTLCreateSystemDefaultDevice())
+ if device.name.contains("Paravirtual") { throw XCTSkip("a virtual GPU's timing says nothing") }
+ let context = try MetalContext()
+ let source = """
+ #include <metal_stdlib>
+ using namespace metal;
+ kernel void spin(device float *o [[buffer(0)]], constant uint &n [[buffer(1)]], uint i [[thread_position_in_grid]]) {
+ float x = float(i);
+ for (uint k = 0; k < n; k++) { x = fma(x, 1.0000001f, 0.5f); }
+ o[i] = x;
+ }
+ """
+ let pipeline = try device.makeComputePipelineState(function: try XCTUnwrap(
+ device.makeLibrary(source: source, options: nil).makeFunction(name: "spin")))
+ let out = try context.scratch(4 << 20, label: "spin")
+ func spin(_ commands: MTLCommandBuffer, _ n: UInt32) {
+ var n = n
+ let e = commands.makeComputeCommandEncoder()!
+ e.setComputePipelineState(pipeline); e.setBuffer(out, offset: 0, index: 0); e.setBytes(&n, length: 4, index: 1)
+ e.dispatchThreads(MTLSize(width: 1 << 20, height: 1, depth: 1), threadsPerThreadgroup: MTLSize(width: 256, height: 1, depth: 1))
+ e.endEncoding()
+ }
+ // About 60 ms of GPU work on each side of the release.
+ var n: UInt32 = 1000
+ for _ in 0..<3 {
+ let c = context.queue.makeCommandBuffer()!
+ spin(c, n)
+ try MetalContext.finish(c, "spin")
+ n = UInt32(min(Double(1 << 24), Double(n) * 0.06 / max(c.gpuEndTime - c.gpuStartTime, 1e-4)))
+ }
+ let event = try XCTUnwrap(device.makeSharedEvent())
+ let commands = context.queue.makeCommandBuffer()!
+ // GPU work before the release too, as in the engine (a signal first in its command buffer is seen at once).
+ spin(commands, n)
+ Coexecutor.release(event, 1, flush: true, commands)
+ spin(commands, n)
+ nonisolated(unsafe) var seen = 0.0
+ let watcher = Thread {
+ _ = event.wait(untilSignaledValue: 1, timeoutMS: 10_000)
+ seen = CACurrentMediaTime()
+ }
+ watcher.start()
+ try MetalContext.finish(commands, "release")
+ while seen == 0 { usleep(100) }
+ XCTAssertLessThan(seen, commands.gpuEndTime - 0.02, "the release reached the CPU only at the command buffer's end")
+ }
+}
diff --git a/engine-mac/chips.md b/engine-mac/chips.md
index b543daa..abbee9a 100644
--- a/engine-mac/chips.md
+++ b/engine-mac/chips.md
@@ -8,6 +8,7 @@ Before working on a chip, look here and in [docs/mac-engine.md](docs/mac-engine.
| Chip | Mac (model, cooling) | Memory | macOS | Paths on by default | 1024² text to image | Velocity error (default) | Source |
|---|---|---|---|---|---|---|---|
| M2 Pro, 19-core GPU | MacBook Pro (Mac14,10), fans | 16 GB | 27 | Metal 4 products (7.57 → 7.48 s per evaluation); direct attention off (142 ms vs 91) | ~64–67 s; 1 MP edit ~106 s, peak 5 GB | ~6–7 · 10⁻⁴ | [README.md](README.md), [docs/mac-engine.md](docs/mac-engine.md) chapters 26, 28, 30 |
+| M5 Pro, 20-core GPU | MacBook Pro 16" (Mac17,8), fans | 24 GB | 26.6.2 | Metal 4 products; direct attention; each product released at once (`KOKON_FLUSH_READY`) | ~40 s (test set, median of 3; master 49.0 s); edit ~43 s, peak 4.3–4.6 GB | 3.1 · 10⁻⁴ (bench, vs the engine's fp32 path) | [README.md](README.md) "Per-chip paths", [docs/mac-engine.md](docs/mac-engine.md) chapters 13, 26 |
## Per-chip notes
@@ -16,3 +17,12 @@ Before working on a chip, look here and in [docs/mac-engine.md](docs/mac-engine.
- The engine was built and tuned on it, at 1024² only: other sizes are not tuned yet.
- int8 on the Neural Engine: an evaluation 7.42 → 7.00 s, but 1.1–4.1 · 10⁻² velocity error: opt-in.
- Neural Engine heads in attention: ~1.5 % faster, 2.5× the error: opt-in.
+
+### M5 Pro, 20-core GPU, 24 GB
+
+- A signal inside a command buffer reaches the CPU only at the command buffer's next wait (chapter 13): before
+ `KOKON_FLUSH_READY` the AMX and the Neural Engine ran after the GPU's rows, and the balancer gave them almost nothing.
+ With it, test set (3 alternated rounds, median): 1024² 49.0 → 39.6 s, 1344×768 48.3 → 39.9 s, edit 51.6 → 43.0 s.
+- With the release fixed, `bench` still shows `KOKON_NA=0` (3.92 s per step) and `KOKON_ATTENTION_DIRECT=0` (3.86 s)
+ ahead of the default (4.08 s): one run each, not yet confirmed with alternated rounds.
+- `KOKON_ANE_INT8=w8` gives a NaN velocity and a wrong image (192 levels mean) on this Mac; `=1` works (1.7 · 10⁻²).
diff --git a/engine-mac/docs/mac-engine.md b/engine-mac/docs/mac-engine.md
index 437c341..f09c046 100644
--- a/engine-mac/docs/mac-engine.md
+++ b/engine-mac/docs/mac-engine.md
@@ -649,6 +649,15 @@ the [balancing loop](#15-the-balancing-loop).
A rule that keeps this safe: a reserve or a surface is rewritten only after the GPU has waited for the product that
read it. That is why there are two reserves and two sets of Neural Engine programs, alternating.
+**When the CPU sees a signal.** On the M5 Pro (macOS 26.6) a signal inside a command buffer reaches the CPU only at
+the next wait the command buffer encodes, or at its end: GPU work of 3 × 20 ms with a signal after each, the CPU saw
+them at 60 / 60 / 60 ms, and with a wait after each signal at 20 / 40 / 60. In the sequence above the first wait comes
+after the GPU's rows, so there the AMX and the Neural Engine started only when the GPU was done, and the timeline read
+the GPU's rows as ~1 ms (the balancer then gave the AMX nothing and the CPU no heads). On that chip `release` encodes a
+wait on `ready` right after its signal, on a value already reached ([chapter 26](#26-per-chip-paths),
+`KOKON_FLUSH_READY`). `PerChipTests` checks on every Mac that the flushed release reaches the CPU before the command
+buffer's end.
+
## 14. The Neural Engine in detail
*Source: `NeuralEngine.swift`, `Kernels/ane.metal`, the packing parts of `Coexecution.swift`.*
@@ -1264,6 +1273,7 @@ any Mac.**
| **GPU rows on Metal 4 tensor operations** (`na_matmul`, MetalPerformancePrimitives' `matmul2d`): on the M5 the GPU cores' matrix units, before it the shader cores | wherever Metal 4 runs | 6.3 vs MPS 5.6 TFLOP/s, bit for bit the same; an evaluation 7.57 → 7.48 s | `KOKON_NA=0` |
| **Attention reading K/V from memory** (`flash_attention_direct`) | Apple9+ GPUs (M3 and later) | 142 ms vs 91 (so not on M2) | `KOKON_ATTENTION_DIRECT=0/1` |
| **int8 products on the Neural Engine** (libnnc's M3/M4 path) | opt-in on every chip | a tile 10.1 → 7.0 ms, but 15–50× the error | `KOKON_ANE_INT8=1` or `w8` |
+| **Each product released at once** (`Coexecutor.release`: a wait on `ready` right after its signal, so the CPU sees it before the GPU's own rows) | the M5 Pro only (`Chip.name`) | not selected (M5 Pro: an evaluation 5.50–5.89 → 4.44–4.46 s) | `KOKON_FLUSH_READY=0/1` |
| **Starting shares** scaled by the chip's estimated units | always | — | `KOKON_BALANCE=0` keeps the defaults |
Only the M2 Pro has measured these. `bench` exists to measure them on the Macs we do not have.
@@ -1443,6 +1453,7 @@ All are environment variables read once at start. Defaults are what users run.
| `KOKON_ACTIVATIONS` | fp16 | `fp32`: fp32 inputs to the GPU's and AMX's products (checks) |
| `KOKON_ATTENTION` | fp16 packed kernel | `fp32`: fp32 kernel; `graph`: MPSGraph; `unpacked`: no K/V packing |
| `KOKON_ATTENTION_DIRECT` | on from Apple9 | `0`/`1`: choose the direct-load attention |
+| `KOKON_FLUSH_READY` | on the M5 Pro | `0`/`1`: a wait right after each release, so the AMX and the Neural Engine see it at once |
| `KOKON_FUSED_CAST`, `KOKON_FUSED_PACK`, `KOKON_FUSED_RESIDUAL`, `KOKON_SHARED_ROWS` | on | `0`: the separate passes, for comparison |
| `KOKON_PREFIX_CACHE` | fp16 or q8 | `0`: off; `fp32`, `fp16`, `q8`: choose the format |
| `KOKON_PREFIX_CACHE_MB` | 1536 below 32 GB, memory/8 above | the cache's limit |