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: per-chip paths and a benchmark for testers
Gabriele Lozupone4ee4bfda0437
diff --git a/README.md b/README.mdindex 2022133..02291a7 100644--- a/README.md+++ b/README.md@@ -753,6 +753,8 @@ or macOS version and the log from `KokonData/logs` (see the table above).- [x] **0.11:** the interface in a browser on your other devices, served by Kokon itself, with a password,and a Docker image for NVIDIA ([#15](https://github.com/GabrieleLozupone/kokon/issues/15))- [ ] Docker image for AMD and Intel (Vulkan); the desktop app as a client of a Kokon server elsewhere+- [ ] Kokon's own engine for Apple Silicon (GPU, CPU matrix unit and Neural Engine together; in development, text to+ image ~3.5× faster on an M2 Pro so far)- [ ] Intel GPUs through Vulkan (to verify)- [ ] Background removal and transparent cutouts- [ ] Batch edits: one instruction for a whole folderdiff --git a/docs/STATUS.md b/docs/STATUS.mdindex 63ec81c..f298915 100644--- a/docs/STATUS.md+++ b/docs/STATUS.md@@ -24,8 +24,9 @@ Windows, macOS (Apple Silicon, 15+) and Linux (`.deb`, `.rpm`). Installed copies- **LoRA is beta** and tested on Windows only; reports from macOS and Linux are welcome([#33](https://github.com/GabrieleLozupone/kokon/issues/33) has a product-shot test).- **Macs are slow** compared with NVIDIA cards (about 4 minutes for 1 MP on an M2 Pro 16 GB). Kokon's own Mac- engine is in development (`engine-mac/`, text to image only so far: about 68 s for 1 MP on the same Mac); it is- not in the app yet.+ engine is in development on the `macos-optimization` branch (`engine-mac/`, not released): text to image only,+ about 71–74 s for 1 MP on the same Mac through the app's API, as an experimental switch in Settings → Performance+ (off by default). Edits, LoRAs, Prompt+ and the upscaler still need the standard engine.- The Windows installer is not code-signed: SmartScreen or Smart App Control may block it (README FAQ: Unblock).- HEIC photos can't be opened on Linux yet.@@ -37,6 +38,8 @@ Windows, macOS (Apple Silicon, 15+) and Linux (`.deb`, `.rpm`). Installed copies- AMD RDNA3/RDNA4 owners who know HIP: compare a ROCm engine with Vulkan([#38](https://github.com/GabrieleLozupone/kokon/issues/38)).- Hardware reports: AMD and Intel on Windows and Linux, Linux on NVIDIA outside WSL, Macs other than an M2 Pro.+ For the Mac engine: `bash engine-mac/tools/bench.sh` on the `macos-optimization` branch prints a report to paste+ (M1, M3, M4 and M5 Macs are the most useful; see [engine-mac/README.md](../engine-mac/README.md#testing-on-your-mac-bench)).- Model proposals that meet the switch rule: [Discussion #35](https://github.com/GabrieleLozupone/kokon/discussions/35).## Recently shippeddiff --git a/engine-mac/README.md b/engine-mac/README.mdindex e64d959..39d95a4 100644--- a/engine-mac/README.md+++ b/engine-mac/README.md@@ -15,8 +15,17 @@ swift test # no model needed.build/release/kokon-engine-mac check-dequant <file.gguf> [tensor...].build/release/kokon-engine-mac generate <encoder.gguf> <dit.gguf> <vae.safetensors> "a red fox in the snow" \[--size 1024x1024] [--seed 42] [--out out.png]+.build/release/kokon-engine-mac serve --diffusion-model <dit.gguf> --vae <vae.safetensors> --llm <encoder.gguf> \+ [--listen-port 1234] # sd-server's /sdcpp/v1 API, text to image+.build/release/kokon-engine-mac bench # a few minutes: speed and accuracy of this Mac's paths, a report+.build/release/kokon-engine-mac check-na # the Metal 4 matrix product against MPS+.build/release/kokon-engine-mac check-ane8 # the int8 Neural Engine programs against the fp16 one```+In the app: `bash tools/install-dev.sh` puts the build where Kokon looks for it, then Settings → Performance →+"Kokon's Mac engine (experimental)". Off by default; sd.cpp stays the default, the fallback, and the engine on+Windows and Linux.+## What is here| File | What |@@ -37,7 +46,11 @@ swift test # no model needed| `QwenVAE.swift`, `Safetensors.swift` | the VAE decoder as one MPSGraph, from Kokon's VAE file (Wan 2.2 names) || `QwenTokenizer.swift` | Qwen's byte-level BPE tokenizer, read from the encoder GGUF's metadata || `QwenTextEncoder.swift`, `Kernels/text.metal` | the text encoder: Qwen3-VL-8B's text decoder on the GPU, diffusers' prompt template |-| `QwenPipeline.swift` | text to image: noise, Turbo's 8 flow-Euler steps (`planner::TURBO_SIGMAS`), VAE, PNG |+| `QwenPipeline.swift` | text to image: noise, Turbo's 8 flow-Euler steps (`planner::TURBO_SIGMAS`), VAE, PNG; models kept loaded for the server |+| `EngineServer.swift`, `HTTPServer.swift` | `serve`: sd-server's `/sdcpp/v1` API (capabilities, img_gen, jobs, cancel) and its log lines |+| `Chip.swift` | this Mac's chip, GPU family, cores and memory; each unit's estimated speed against the M2 Pro's |+| `NeuralAccelerators.swift`, `Kernels/metal4/na_matmul.metal` | the GPU's rows of a product on Metal 4 tensor operations (the M5's neural accelerators) |+| `Bench.swift` | `bench`: the report testers paste in GitHub |Tests check the CPU and GPU unpacking against gguf-py's values (`tools/make_quant_fixtures.py` writes thefixture), and the sequence layout against diffusers' rules worked out by hand.@@ -179,7 +192,9 @@ inputs 2–2.7×). The three units share one limit when they run together (memoran evaluation only 8.54 → 8.3–8.5 s), so halving the bytes is what pays. One evaluation at 1024²: **8.54 → 7.45–7.55s** (fp16 weights alone 8.0–8.1). The velocity at 896² against diffusers fp32 (old Q4_K file, `dit-t2i-896`): 7.0e-4,against 5.1e-4 before (fp16 weights alone 5.7e-4; the Neural Engine's rows were already fp16); 256² end to end-(GPU only, fp16 weights and attention) against fp64: image within 2.4e-3, at most 13 levels off (fp32 path 7.6e-5).+(GPU only, fp16 weights and attention) against fp64: image within 2.4e-3, at most 13 levels off (fp32 path 7.6e-5);+re-measured at f4a8334 and after this pass (2026-10-25): 6.9e-3, at most 35 levels, the fp32 path 9.6e-5 (914 values+off by 1), the same at both.The 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).@@ -228,6 +243,60 @@ fp16 attention). `MTLBinaryArchive` was not added: the engine's kernels compilecaches compiled shaders), and the first image's real extra costs, the VAE's first run at a size and the NeuralEngine's programs, are not pipelines an archive holds. Only an M2 Pro has been measured.+## The engine as a server (`serve`)++`kokon-engine-mac serve` answers sd-server's `/sdcpp/v1` API (capabilities, img_gen, jobs/{id}, cancel), so+qls-core, the app, remote access and MCP use it as they use sd-server; it prints the log lines qls-core's+`ProgressParser` reads. Text to image only for now: reference images, masks, LoRAs and second passes are refused+with 400 (qls-core says so before submitting), upscaling falls back to Lanczos, Prompt+ is off. A running image+cancels within a DiT layer (sd-server answers 409 and qls-core restarts it). A new prompt length rebuilds the DiT's+working memory in ~0.5 s.++What stays loaded between images depends on the Mac (`QwenPipeline.keep*`): from 32 GB everything; below, only the+files' mappings, since on the M2 Pro 16 GB the compiled VAE keeps 7–8 GB of GPU memory after a 1024² decode. With+everything kept there the second image took 121–129 s (pages evicted and read again); now, through the API+(`tools/api_check.py`, 2026-10-25): **first 1024² image 71.1 s, the next ones 73.7 s**, 1.1 GB of footprint while idle,+peak 9.6 GB during the VAE's decode (the one-shot CLI peaks the same; a tiled decode is the next step for 16 GB Macs).++## Per-chip paths++Selected at run time from the GPU family and the chip (`Chip.swift`), each with the M2 path as its fallback and a+correctness test that runs on any Mac (`PerChipTests`). Only the M2 Pro has measured them; `bench` measures the rest.++- **GPU products on Metal 4 tensor operations** (`na_matmul`, MetalPerformancePrimitives' `matmul2d`; on the M5 they+ run on the GPU's neural accelerators, before it on the shader cores). Its source compiles at run time on macOS 27,+ so it is on wherever Metal 4 runs (`KOKON_NA=0` off). M2 Pro: 6.3 TFLOP/s against MPS's 5.6 at 1536 × 4096 × 4096,+ bit for bit the same result (`check-na`); per evaluation at 1024², 3 alternated rounds: 7.57 → 7.48 s.+- **int8 products on the Neural Engine** (libnnc's M3/M4 path; `KOKON_ANE_INT8=w8` int8 weights, `=1` int8 weights and+ rows). Opt-in on every chip, as their error does not depend on the chip. M2 Pro: one 1792 × 4096 × 4096 tile 10.1 ms+ in fp16, 8.3 ms with int8 weights, 7.0 ms in int8 (`check-ane8`); per evaluation 7.42 → 7.20 / 7.00 s; but the+ velocity at 896² goes from 7.6e-4 to 1.1e-2 / 4.1e-2 (one int8 scale per 4 096 weights where Q4_K has one per 32;+ activation rows with outliers). Finer weight scales are the way to try next.+- **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+.+- **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.++## Testing on your Mac (`bench`)++For anyone with an Apple Silicon Mac, to measure these paths on hardware we do not have (M1, M3, M4, M5, base chips):++```bash+git clone https://github.com/GabrieleLozupone/kokon.git && cd kokon && git checkout macos-optimization+bash engine-mac/tools/bench.sh # ~10 min; --quick: one image per run+```++It needs the Xcode command line tools and Kokon's model files (Kokon set up once, or `--encoder`, `--dit`, `--vae`),+and writes `kokon-bench-report.md`: chip, GPU family and cores, memory, macOS, the paths selected, the units' shares,+time per step and per image at 1024² (image 1 with the loading, image 2 with the engine already running), peak memory, and accuracy at+512² against the engine's own fp32 GPU path on the same Mac (the first step's velocity and the image, in 8-bit+levels), then the same with each chip-specific path off (and the int8 path on, on M3 and later). Paste it in the+GitHub discussion. A row with a path off that is faster than the default means that path should not be on for that+chip. Close other apps and keep the Mac plugged in: the units share one power and memory limit.++## Tried and not kept, the VAE, credits+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/AttentionSplit.swift b/engine-mac/Sources/KokonEngine/AttentionSplit.swiftindex d38b85f..c2d1459 100644--- a/engine-mac/Sources/KokonEngine/AttentionSplit.swift+++ b/engine-mac/Sources/KokonEngine/AttentionSplit.swift@@ -21,17 +21,6 @@ struct HeadSplit: CustomStringConvertible {var gpu: Int, ane: Int, cpu: Intvar description: String { "GPU \(gpu) / ANE \(ane) / CPU \(cpu) heads" }- /// From `time-dit` and `probe-attention` on the M2 Pro (ms per head at 1024² beside the others: GPU 4.5, CPU 7.0;- /// the Neural Engine 6.0 and the GPU 6.3 when it runs), the Neural Engine in groups of 4. The balancing loop moves it.- static func `default`(ane: Bool, cpu: Bool) -> HeadSplit {- switch (ane, cpu) {- case (true, true): return HeadSplit(gpu: 14, ane: 8, cpu: 10)- case (true, false): return HeadSplit(gpu: 16, ane: 16, cpu: 0)- case (false, true): return HeadSplit(gpu: 19, ane: 0, cpu: 13)- case (false, false): return HeadSplit(gpu: QwenDiT.heads, ane: 0, cpu: 0)- }- }-/// `KOKON_HEADS=gpu,ane,cpu` (the Neural Engine's a multiple of 4, the three summing to 32).static func fromEnvironment() -> HeadSplit? {guard let text = ProcessInfo.processInfo.environment["KOKON_HEADS"] else { return nil }diff --git a/engine-mac/Sources/KokonEngine/Balancer.swift b/engine-mac/Sources/KokonEngine/Balancer.swiftindex 88f447a..a42c88a 100644--- a/engine-mac/Sources/KokonEngine/Balancer.swift+++ b/engine-mac/Sources/KokonEngine/Balancer.swift@@ -27,11 +27,50 @@ struct Balancer: Codable {static let smoothing = 0.5, margin = 0.985/// Seeds from `time-dit` at 1024² (1856 / 256 / 2048 rows; attention 19 GPU / 13 CPU heads) and `probe-attention`- /// (the Neural Engine's heads), M2 Pro, 2026-10-25.- init(aneAttention: Bool) {+ /// (the Neural Engine's heads), M2 Pro, 2026-10-25; on another chip scaled by `Chip.unitScale` (estimates).+ init(aneAttention: Bool, chip: Chip? = nil) {self.aneAttention = aneAttentionrates = ["4096×4096": Rates(gpu: 149, amx: 28, ane: 172), "4096×12288": Rates(gpu: 48, amx: 9.8, ane: 58),"12288×4096": Rates(gpu: 43.5, amx: 8.8, ane: 57.5), "attention": Rates(gpu: 0.224, amx: 0.142, ane: 0.195)]+ if let scale = chip?.unitScale {+ for (kind, r) in rates { rates[kind] = Rates(gpu: r.gpu * scale.gpu, amx: r.amx * scale.amx, ane: r.ane * scale.ane) }+ }+ }++ /// The products of one DiT evaluation, by kind: per layer q, k, v, out (4096 × 4096), gate, proj, MLP out.+ static let evaluationCounts = ["4096×4096": 4 * QwenDiT.layers, "4096×12288": 2 * QwenDiT.layers, "12288×4096": QwenDiT.layers]++ /// The Neural Engine's rows (steps of 256, from 1 024 to `rows` − 512) minimizing the predicted products of an+ /// evaluation with `counts` products of each kind.+ func bestAneRows(rows: Int, amx: Bool, counts: [String: Int] = Balancer.evaluationCounts) -> Int? {+ stride(from: 1024, through: rows - 512, by: 256).min {+ productCost(rows: rows, ane: $0, amx: amx, counts: counts) < productCost(rows: rows, ane: $1, amx: amx, counts: counts)+ }+ }++ /// The AMX's rows of a product of `kind` (a multiple of 64) for `rest` rows shared with the GPU.+ func amxRows(kind: String, rest: Int) -> Int? {+ guard let r = rates[kind] else { return nil }+ // Of the two multiples of 64 around the ideal cut, the one whose slower unit is faster.+ let ideal = Double(rest) * r.amx / (r.gpu + r.amx)+ let low = Int(ideal / 64) * 64+ func time(_ a: Int) -> Double {+ max(a > 0 ? Double(a) / (amxAt[kind]?[a] ?? r.amx) : 0, Double(rest - a) / r.gpu)+ }+ return [low - 64, low, low + 64].filter { $0 >= 0 && $0 <= rest }.min { time($0) < time($1) }+ }++ /// The cut of the 32 heads whose slowest unit is fastest (the GPU keeps at least one: its text segments run there).+ func bestHeads(ane: Bool, cpu: Bool) -> HeadSplit {+ let maxAne = ane && aneAttention ? QwenDiT.heads - Coexecutor.aneHeadGroup : 0+ var best = HeadSplit(gpu: QwenDiT.heads, ane: 0, cpu: 0)+ for a in stride(from: 0, through: maxAne, by: Coexecutor.aneHeadGroup) {+ for c in 0...(cpu ? QwenDiT.heads - 1 - a : 0) {+ let h = HeadSplit(gpu: QwenDiT.heads - a - c, ane: a, cpu: c)+ if attentionCost(h) < attentionCost(best) { best = h }+ }+ }+ return best}/// Folds an evaluation's timeline into the rates: per kind, each unit's rows over its seconds.@@ -87,32 +126,16 @@ extension Coexecutor {if !counts.isEmpty {if aneEnabled {func cost(_ e: Int) -> Double { balancer.productCost(rows: rows, ane: e, amx: amxEnabled, counts: counts) }- let best = stride(from: 1024, through: rows - 512, by: 256).min { cost($0) < cost($1) } ?? aneRows+ let best = balancer.bestAneRows(rows: rows, amx: amxEnabled, counts: counts) ?? aneRowsif cost(best) < cost(aneRows) * Balancer.margin { try setAneRows(best) }}- for kind in counts.keys {- guard amxEnabled, let r = balancer.rates[kind] else { continue }- // Of the two multiples of 64 around the ideal cut, the one whose slower unit is faster.- let rest = rows - aneRows- let ideal = Double(rest) * r.amx / (r.gpu + r.amx)- let low = Int(ideal / 64) * 64- func time(_ a: Int) -> Double {- max(a > 0 ? Double(a) / (balancer.amxAt[kind]?[a] ?? r.amx) : 0, Double(rest - a) / r.gpu)- }- amxRows[kind] = [low - 64, low, low + 64].filter { $0 >= 0 }.min { time($0) < time($1) }!+ for kind in counts.keys where amxEnabled {+ if let a = balancer.amxRows(kind: kind, rest: rows - aneRows) { amxRows[kind] = a }}}if lastTimeline.contains(where: { $0.kind == "attention" }), HeadSplit.fromEnvironment() == nil {- // The GPU keeps at least one head (its text segments run there anyway).- let maxAne = aneEnabled && balancer.aneAttention ? QwenDiT.heads - Coexecutor.aneHeadGroup : 0- var best = heads- for ane in stride(from: 0, through: maxAne, by: Coexecutor.aneHeadGroup) {- for cpu in 0...(amxEnabled ? QwenDiT.heads - 1 - ane : 0) {- let h = HeadSplit(gpu: QwenDiT.heads - ane - cpu, ane: ane, cpu: cpu)- if balancer.attentionCost(h) < balancer.attentionCost(best) { best = h }- }- }+ let best = balancer.bestHeads(ane: aneEnabled, cpu: amxEnabled)if balancer.attentionCost(best) < balancer.attentionCost(heads) * Balancer.margin {heads = besttry prepareAttention(queries: attentionShape.queries, keys: attentionShape.keys)@@ -146,14 +169,14 @@ extension Coexecutor {}var memoryKey: String {- "\(context.device.name) rows \(rows) ane \(aneEnabled) amx \(amxEnabled) ane-attention \(balancer.aneAttention)"+ "\(context.device.name) rows \(rows) ane \(aneEnabled)\(aneInt8 ? aneHalfRows ? " w8" : " int8" : "") 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+ amxRows = m.amxRows.filter { Balancer.evaluationCounts[$0.key] != nil } // kinds this engine still runsif 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) }}diff --git a/engine-mac/Sources/KokonEngine/Bench.swift b/engine-mac/Sources/KokonEngine/Bench.swiftnew file mode 100644index 0000000..0c9fdbb--- /dev/null+++ b/engine-mac/Sources/KokonEngine/Bench.swift@@ -0,0 +1,192 @@+import Foundation+import Metal++/// **`kokon-engine-mac bench`: a few minutes that measure the per-chip paths on the Mac that runs it**, for testers+/// to paste in a GitHub issue or discussion. Needs only Kokon's model files.+///+/// The engine reads its settings (`KOKON_*`) once at start, so each configuration runs in a child process+/// (`bench-run`) and prints one JSON line; the parent compares them and prints the report:+///+/// - accuracy at 512² (1 024 target rows, so every unit and path is in use): the first step's velocity and the+/// 8-step image, against the engine's own fp32 path on the GPU alone, on the same Mac, the same noise and prompt;+/// - speed at 1024²: two images in one process (the first pays the loading and the Neural Engine's programs),+/// time per step and per image, peak memory;+/// - the same with each experimental path this Mac selected turned off, one at a time.+public enum Bench {+ public static let prompt = "A red fox in fresh snow at dawn, a wooden sign that says KOKON, soft golden light, photo"++ /// A configuration: its name in the report and the settings it changes.+ struct Run { let name: String; let environment: [String: String] }++ /// The experimental paths this Mac selects, as (what, the setting that turns it off).+ static func selectedPaths(device: MTLDevice) -> [(String, String, String)] {+ let chip = Chip.current+ var paths: [(String, String, String)] = []+ if Coexecutor.int8Selected(chip), #available(macOS 26, *) {+ paths.append(("int8 products on the Neural Engine (M3/M4 path)", "KOKON_ANE_INT8", "0"))+ }+ 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 QwenDiT.directAttention(device: device) {+ paths.append(("attention reading K/V straight from memory (Apple9+ path)", "KOKON_ATTENTION_DIRECT", "0"))+ }+ return paths+ }++ /// The fp32 path, GPU only: the reference for accuracy.+ static let reference = ["KOKON_WEIGHTS": "fp32", "KOKON_ACTIVATIONS": "fp32", "KOKON_ATTENTION": "fp32",+ "KOKON_COEXEC": "0", "KOKON_NA": "0"]++ // MARK: - parent++ public static func run(encoder: String, dit: String, vae: String, quick: Bool, out: String?) throws {+ let context = try MetalContext()+ let chip = Chip.current+ let paths = selectedPaths(device: context.device)+ print("kokon-engine-mac bench: \(chip)")+ print("selected: " + (paths.isEmpty ? "the M2 path (nothing chip-specific)" : paths.map(\.0).joined(separator: "; ")))+ let scratch = FileManager.default.temporaryDirectory.appendingPathComponent("kokon-bench-\(ProcessInfo.processInfo.processIdentifier)")+ try FileManager.default.createDirectory(at: scratch, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: scratch) }++ var runs = [Run(name: "default (paths above)", environment: [:])]+ for path in paths { runs.append(Run(name: "\(path.1)=\(path.2)", environment: [path.1: path.2])) }+ // The opt-in int8 Neural Engine path where it may pay (libnnc's M3/M4 path; less accurate everywhere).+ if (chip.generation ?? 5) >= 3, #available(macOS 26, *) {+ for mode in ["w8", "1"] { runs.append(Run(name: "KOKON_ANE_INT8=\(mode)", environment: ["KOKON_ANE_INT8": mode])) }+ }++ func child(_ mode: String, _ environment: [String: String], tag: String) throws -> [String: Any] {+ let process = Process()+ process.executableURL = URL(fileURLWithPath: Bundle.main.executablePath ?? CommandLine.arguments[0])+ process.arguments = ["bench-run", mode, encoder, dit, vae, scratch.appendingPathComponent(tag).path] + (quick ? ["--quick"] : [])+ process.environment = ProcessInfo.processInfo.environment.merging(environment) { $1 }+ let pipe = Pipe()+ process.standardOutput = pipe+ try process.run()+ let data = pipe.fileHandleForReading.readDataToEndOfFile()+ process.waitUntilExit()+ let text = String(decoding: data, as: UTF8.self)+ guard process.terminationStatus == 0, let line = text.split(separator: "\n").last(where: { $0.hasPrefix("BENCH ") }),+ let json = try JSONSerialization.jsonObject(with: Data(line.dropFirst(6).utf8)) as? [String: Any] else {+ throw MetalContext.Failure.kernel("bench-run \(mode) \(environment) failed (status \(process.terminationStatus)):\n" + text.suffix(2000))+ }+ return json+ }++ print("accuracy at 512²: the fp32 reference (GPU alone, ~1 min)…")+ let reference = try child("accuracy", Bench.reference, tag: "reference")+ var rows: [[String: Any]] = []+ for (i, run) in runs.enumerated() {+ print("[\(i + 1)/\(runs.count)] \(run.name): accuracy at 512², then two images at 1024²…")+ var row = try child("accuracy", run.environment, tag: "run\(i)")+ row.merge(try child("timing", run.environment, tag: "run\(i)")) { a, _ in a }+ row["name"] = run.name+ rows.append(row)+ }+ let report = Bench.report(chip: chip, paths: paths, reference: reference, rows: rows, quick: quick)+ print("\n" + report)+ if let out {+ try report.write(toFile: out, atomically: true, encoding: .utf8)+ print("(written to \(out))")+ }+ }++ static func report(chip: Chip, paths: [(String, String, String)], reference: [String: Any], rows: [[String: Any]], quick: Bool) -> String {+ func number(_ row: [String: Any], _ key: String) -> Double { (row[key] as? NSNumber)?.doubleValue ?? .nan }+ let refVelocity = reference["velocity"] as? String, refImage = reference["image"] as? String+ var lines = [+ "### Kokon Mac engine bench",+ "",+ "- Chip: \(chip.name), \(chip.gpuCores) GPU cores (GPU family Apple\(chip.gpuFamily)\(chip.supportsMetal4 ? ", Metal 4" : "")), "+ + "\(chip.performanceCores) performance + \(chip.efficiencyCores) efficiency cores, \(Int(chip.memoryGB.rounded())) GB",+ "- macOS \(chip.macOS); engine \(EngineVersion.string)",+ "- Paths selected: " + (paths.isEmpty ? "none chip-specific (the M2 path)" : paths.map(\.0).joined(separator: "; ")),+ "- Shares after the run (1024²): \(rows.first?["shares"] as? String ?? "?")",+ "",+ "| Run | Image 1 | Image 2 | Step (2–8) | VAE | Peak memory | Velocity vs fp32 | Image vs fp32 |",+ "|---|---|---|---|---|---|---|---|",+ ]+ for row in rows {+ var velocity = "?", image = "?"+ if let a = refVelocity, let b = row["velocity"] as? String, let e = Bench.relativeError(b, a) { velocity = String(format: "%.1e", e) }+ if let a = refImage, let b = row["image"] as? String, let d = Bench.levels(b, a) {+ image = String(format: "mean %.2f, max %d levels", d.mean, d.max)+ }+ let second = number(row, "image2")+ lines.append(String(format: "| %@ | %.1f s | %@ | %.2f s | %.2f s | %.1f GB | %@ | %@ |", row["name"] as? String ?? "?",+ number(row, "image1"), second.isNaN ? "–" : String(format: "%.1f s", second), number(row, "step"),+ number(row, "vae"), number(row, "peak"), velocity, image))+ }+ lines += ["", "Image 1 includes loading the models and building the Neural Engine's programs; image 2 is the engine "+ + "already running, as in the app. Accuracy at 512² against the engine's fp32 GPU path"+ + (quick ? "; --quick: one image per run." : ".")]+ return lines.joined(separator: "\n")+ }++ /// ‖a − b‖ / ‖b‖ of two files of floats.+ static func relativeError(_ a: String, _ b: String) -> Double? {+ guard let x = try? Data(contentsOf: URL(fileURLWithPath: a)), let y = try? Data(contentsOf: URL(fileURLWithPath: b)),+ x.count == y.count, !x.isEmpty else { return nil }+ return x.withUnsafeBytes { xb in y.withUnsafeBytes { yb in+ let p = xb.bindMemory(to: Float.self), q = yb.bindMemory(to: Float.self)+ var d = 0.0, n = 0.0+ for i in 0..<p.count { d += Double(p[i] - q[i]) * Double(p[i] - q[i]); n += Double(q[i]) * Double(q[i]) }+ return (d / max(n, 1e-30)).squareRoot()+ } }+ }++ /// Mean and largest difference of two files of 8-bit values.+ static func levels(_ a: String, _ b: String) -> (mean: Double, max: Int)? {+ guard let x = try? Data(contentsOf: URL(fileURLWithPath: a)), let y = try? Data(contentsOf: URL(fileURLWithPath: b)),+ x.count == y.count, !x.isEmpty else { return nil }+ var sum = 0, worst = 0+ for i in 0..<x.count { let d = abs(Int(x[i]) - Int(y[i])); sum += d; worst = max(worst, d) }+ return (Double(sum) / Double(x.count), worst)+ }++ // MARK: - child++ /// `bench-run accuracy|timing <encoder> <dit> <vae> <file prefix> [--quick]`: prints `BENCH {json}`.+ public static func child(mode: String, encoder: String, dit: String, vae: String, prefix: String, quick: Bool) throws {+ let pipeline = try QwenPipeline(encoder: encoder, dit: dit, vae: vae)+ pipeline.keepModels = true+ pipeline.log = { _ in }+ var result: [String: Any] = [:]+ if mode == "accuracy" {+ // The first step's velocity from the noise, and the image.+ let (w, h, seed) = (512, 512, UInt64(42))+ let noise = QwenPipeline.pack(Noise.philox(seed: seed, count: QwenDiT.channels * (h / 16) * (w / 16)), height: h / 16, width: w / 16)+ var velocity: [Float] = []+ let sigmas = QwenPipeline.turboSigmas+ let image = try pipeline.textToImage(prompt: Bench.prompt, width: w, height: h, seed: seed) { i, x in+ if i == 0 { velocity = zip(x, noise).map { ($0 - $1) / (sigmas[1] - sigmas[0]) } }+ }+ let pixels = QwenPipeline.pixels(image, width: w, height: h)+ try velocity.withUnsafeBytes { try Data($0).write(to: URL(fileURLWithPath: prefix + "-velocity.f32")) }+ try Data(pixels).write(to: URL(fileURLWithPath: prefix + "-image.u8"))+ result = ["velocity": prefix + "-velocity.f32", "image": prefix + "-image.u8"]+ } else {+ var images: [Double] = [], steps: [Double] = [], vae = 0.0+ for i in 0..<(quick ? 1 : 2) {+ _ = try pipeline.textToImage(prompt: Bench.prompt, width: 1024, height: 1024, seed: 42 + UInt64(i))+ let t = pipeline.timings+ images.append(t["total"] ?? .nan)+ vae = t["vae"] ?? .nan+ steps = (2...8).compactMap { t["step \($0)"] }+ }+ let memory = MemoryUsage.now()+ result = ["image1": images[0], "step": steps.reduce(0, +) / Double(max(1, steps.count)), "vae": vae,+ "peak": memory.footprintPeak, "shares": pipeline.shares ?? "GPU only"]+ if images.count > 1 { result["image2"] = images[1] }+ }+ let data = try JSONSerialization.data(withJSONObject: result)+ print("BENCH " + String(decoding: data, as: UTF8.self))+ }+}++/// The engine's version in reports (the bench script adds the commit).+public enum EngineVersion {+ public static let string = ProcessInfo.processInfo.environment["KOKON_ENGINE_VERSION"] ?? "0.1 (experimental)"+}diff --git a/engine-mac/Sources/KokonEngine/Checks.swift b/engine-mac/Sources/KokonEngine/Checks.swiftindex 520105d..19d0662 100644--- a/engine-mac/Sources/KokonEngine/Checks.swift+++ b/engine-mac/Sources/KokonEngine/Checks.swift@@ -1,5 +1,7 @@import Foundationimport Metal+import MetalPerformanceShaders+import CoreVideo/// Developer checks on real files, printed (the unit tests use small synthetic files instead).public enum Checks {@@ -223,3 +225,130 @@ extension Checks {}}}++extension Checks {+ /// `na_matmul` (Metal 4 tensor operations, the M5's neural accelerators) against MPS on one of the DiT's products,+ /// fp16 operands, fp32 results: the largest difference and both timings.+ public static func neuralAccelerators(m: Int = 1536, k: Int = 4096, n: Int = 4096) throws {+ let context = try MetalContext()+ print(Chip.current)+ guard let na = NeuralAccelerators.make(device: context.device) else {+ print("na_matmul unavailable: \(NeuralAccelerators.unavailable ?? "?")")+ return+ }+ let a = try context.scratch(m * k * 2, label: "A"), b = try context.scratch(k * n * 2, label: "B")+ let c1 = try context.scratch(m * n * 4, label: "C na"), c2 = try context.scratch(m * n * 4, label: "C mps")+ var seed: UInt64 = 7+ for (buffer, count) in [(a, m * k), (b, k * n)] {+ let p = buffer.contents().assumingMemoryBound(to: Float16.self)+ for i in 0..<count {+ seed = seed &* 6364136223846793005 &+ 1442695040888963407+ p[i] = Float16((Float(seed >> 40) / Float(1 << 24) - 0.5) * (buffer === a ? 4 : 0.05))+ }+ }+ let product = MPSMatrixMultiplication(device: context.device, transposeLeft: false, transposeRight: false,+ resultRows: m, resultColumns: n, interiorColumns: k, alpha: 1, beta: 0)+ func run(_ body: (MTLCommandBuffer) throws -> Void) throws -> Double {+ var best = Double.infinity+ for _ in 0..<5 {+ let commands = context.queue.makeCommandBuffer()!+ try body(commands)+ best = min(best, try MetalContext.finish(commands, "check-na"))+ }+ return best+ }+ let tNA = try run { try na.encode(a: (a, 0), b: (b, 0), c: (c1, 0), m: m, n: n, k: k, commands: $0) }+ let tMPS = try run {+ product.encode(commandBuffer: $0,+ leftMatrix: MPSMatrix(buffer: a, descriptor: MPSMatrixDescriptor(rows: m, columns: k, rowBytes: k * 2, dataType: .float16)),+ rightMatrix: MPSMatrix(buffer: b, descriptor: MPSMatrixDescriptor(rows: k, columns: n, rowBytes: n * 2, dataType: .float16)),+ resultMatrix: MPSMatrix(buffer: c2, descriptor: MPSMatrixDescriptor(rows: m, columns: n, rowBytes: n * 4, dataType: .float32)))+ }+ let x = c1.contents().assumingMemoryBound(to: Float.self), y = c2.contents().assumingMemoryBound(to: Float.self)+ var diff = 0.0, norm = 0.0+ for i in 0..<(m * n) { diff += Double(x[i] - y[i]) * Double(x[i] - y[i]); norm += Double(y[i]) * Double(y[i]) }+ let flops = 2.0 * Double(m) * Double(n) * Double(k)+ print(String(format: "%d×%d×%d: na_matmul %.2f ms (%.1f TFLOP/s), MPS %.2f ms (%.1f TFLOP/s), relative difference %.2e",+ m, k, n, tNA * 1e3, flops / tNA / 1e12, tMPS * 1e3, flops / tMPS / 1e12, (diff / norm).squareRoot()))+ }+}++extension Checks {+ /// The int8 Neural Engine program (`NeuralEngineProduct.int8Program`) against the fp16 one on a tile of the DiT's+ /// products: time per run and the error of each against the exact product of the same fp32 operands.+ public static func aneInt8(rows: Int = 1792, k: Int = 4096, n: Int = 4096) throws {+ print(Chip.current)+ var seed: UInt64 = 5+ func random(_ count: Int, _ scale: Float) -> [Float] {+ (0..<count).map { _ in+ seed = seed &* 6364136223846793005 &+ 1442695040888963407+ let u = Float(seed >> 40) / Float(1 << 24) - 0.5+ return u * u * u * 8 * scale // heavier tails than uniform, as activations+ }+ }+ let a = random(rows * k, 4), w = random(k * n, 0.05)+ // Exact product of a few rows (all columns) in double.+ let check = Array(stride(from: 0, to: rows, by: rows / 16))+ var exact = [Double](repeating: 0, count: check.count * n)+ for (r, i) in check.enumerated() {+ for l in 0..<k { let x = Double(a[i * k + l]); if x != 0 { for j in 0..<n { exact[r * n + j] += x * Double(w[l * n + j]) } } }+ }+ func error(_ value: (Int, Int) -> Double) -> Double {+ var d = 0.0, s = 0.0+ for (r, i) in check.enumerated() { for j in 0..<n { let e = exact[r * n + j]; d += (value(i, j) - e) * (value(i, j) - e); s += e * e } }+ return (d / s).squareRoot()+ }+ func time(_ p: NeuralEngineProduct) throws -> Double {+ try p.run()+ var best = Double.infinity+ for _ in 0..<10 {+ let t = DispatchTime.now().uptimeNanoseconds+ try p.run()+ best = min(best, Double(DispatchTime.now().uptimeNanoseconds - t) * 1e-9)+ }+ return best+ }+ let flops = 2.0 * Double(rows) * Double(k) * Double(n)+ // fp16, lifted as the engine does (powers of two: column max of W into [1, 2), rows bounded).+ let fp16 = try NeuralEngineProduct(rows: rows, k: k, n: n)+ let columnPeak = (0..<n).map { j in (0..<k).reduce(Float(0)) { max($0, abs(w[$1 * n + j])) } }+ let lambda = columnPeak.map { $0 > 0 ? exp2(-floor(log2($0))) : 1 }+ let sigma = (0..<rows).map { i in exp2(floor(log2(32768 / max(1e-30, (0..<k).reduce(Float(0)) { max($0, abs(a[i * k + $1]) ) } * Float(k) * 2)))) }+ fp16.write(fp16.x) { p in for i in 0..<rows { for l in 0..<k { p[i * k + l] = Float16(a[i * k + l] * sigma[i]) } } }+ fp16.write(fp16.w) { p in for l in 0..<k { for j in 0..<n { p[l * n + j] = Float16(w[l * n + j] * lambda[j]) } } }+ let t16 = try time(fp16)+ var y16 = [Float](repeating: 0, count: rows * n)+ fp16.read { y in for i in 0..<(rows * n) { y16[i] = Float(y[i]) } }+ let e16 = error { i, j in Double(y16[i * n + j]) / Double(sigma[i] * lambda[j]) }+ print(String(format: "fp16 program %d×%d×%d: %.2f ms (%.1f TFLOP/s), relative error %.2e", rows, k, n, t16 * 1e3, flops / t16 / 1e12, e16))+ // int8: rows and columns quantized by their absmax / 127.+ let int8 = try NeuralEngineProduct(rows: rows, k: k, n: n, int8: true)+ let rowScale = (0..<rows).map { i in max(1e-30, (0..<k).reduce(Float(0)) { max($0, abs(a[i * k + $1])) }) / 127 }+ let columnScale = columnPeak.map { max(1e-30, $0) / 127 }+ func q(_ v: Float) -> Int8 { Int8(max(-127, min(127, (v).rounded(.toNearestOrEven)))) }+ for (surface, fill) in [(int8.x, { (p: UnsafeMutablePointer<Int8>) in for i in 0..<rows { for l in 0..<k { p[i * k + l] = q(a[i * k + l] / rowScale[i]) } } }),+ (int8.w, { (p: UnsafeMutablePointer<Int8>) in for l in 0..<k { for j in 0..<n { p[l * n + j] = q(w[l * n + j] / columnScale[j]) } } })] {+ CVPixelBufferLockBaseAddress(surface, [])+ fill(CVPixelBufferGetBaseAddress(surface)!.assumingMemoryBound(to: Int8.self))+ CVPixelBufferUnlockBaseAddress(surface, [])+ }+ let t8 = try time(int8)+ var y8 = [Float](repeating: 0, count: rows * n)+ int8.read { y in for i in 0..<(rows * n) { y8[i] = Float(y[i]) } }+ let e8 = error { i, j in Double(y8[i * n + j]) * Double(k) * Double(rowScale[i]) * Double(columnScale[j]) }+ print(String(format: "int8 program %d×%d×%d: %.2f ms (%.1f TOP/s), relative error %.2e", rows, k, n, t8 * 1e3, flops / t8 / 1e12, e8))+ // int8 weights, fp16 activations: x lifted so |y| = |Σ x w_q| / K <= max|x| · 127 stays under 2^15.+ let w8 = try NeuralEngineProduct(rows: rows, k: k, n: n, int8: true, halfActivations: true)+ let lift = (0..<rows).map { i in exp2(floor(log2(32768 / 127 / max(1e-30, (0..<k).reduce(Float(0)) { max($0, abs(a[i * k + $1])) })))) }+ w8.write(w8.x) { p in for i in 0..<rows { for l in 0..<k { p[i * k + l] = Float16(a[i * k + l] * lift[i]) } } }+ CVPixelBufferLockBaseAddress(w8.w, [])+ let pw = CVPixelBufferGetBaseAddress(w8.w)!.assumingMemoryBound(to: Int8.self)+ for l in 0..<k { for j in 0..<n { pw[l * n + j] = q(w[l * n + j] / columnScale[j]) } }+ CVPixelBufferUnlockBaseAddress(w8.w, [])+ let tw = try time(w8)+ var yw = [Float](repeating: 0, count: rows * n)+ w8.read { y in for i in 0..<(rows * n) { yw[i] = Float(y[i]) } }+ let ew = error { i, j in Double(yw[i * n + j]) * Double(k) * Double(columnScale[j]) / Double(lift[i]) }+ print(String(format: "int8 weights, fp16 activations %d×%d×%d: %.2f ms (%.1f TFLOP/s), relative error %.2e", rows, k, n, tw * 1e3, flops / tw / 1e12, ew))+ }+}diff --git a/engine-mac/Sources/KokonEngine/Coexecution.swift b/engine-mac/Sources/KokonEngine/Coexecution.swiftindex b7f45f6..1614c68 100644--- a/engine-mac/Sources/KokonEngine/Coexecution.swift+++ b/engine-mac/Sources/KokonEngine/Coexecution.swift@@ -62,6 +62,23 @@ final class Coexecutor {/// weight per evaluation, by only n threads, were most of the GPU's time alone between products.private var columnScales: [String: MTLBuffer] = [:]let aneEnabled: Bool, amxEnabled: Bool+ /// **int8 products on the Neural Engine** (`NeuralEngineProduct.int8Program`, `ane8_*` in `ane.metal`), the path+ /// libnnc (ccv) takes on the M3 and M4: W per column (its scales once per weight, the weight at each use as in+ /// fp16) and, with `KOKON_ANE_INT8=1`, A per row too; `KOKON_ANE_INT8=w8` keeps the rows fp16. Opt-in on every+ /// chip: the error does not depend on the chip, and on the M2 Pro (2026-10-25) one 1792 × 4096 × 4096 tile ran+ /// 7.0 ms in int8, 8.3 ms with int8 weights, 10.1 ms in fp16 (`check-ane8`), but the velocity at 896² went from+ /// 7.6e-4 to 4.1e-2 (int8) and 1.1e-2 (int8 weights; one scale per 4 096 values where Q4_K has one per 32).+ /// `bench` measures both on M3 and later. Falls back to fp16 when its programs cannot be built (macOS 26+).+ private(set) var aneInt8: Bool+ /// With `aneInt8`, the rows stay fp16 (int8 weights only, W8A16: `KOKON_ANE_INT8=w8`).+ let aneHalfRows: Bool+ static func int8Selected(_ chip: Chip) -> Bool {+ switch ProcessInfo.processInfo.environment["KOKON_ANE_INT8"] {+ case "1", "w8": return true+ default: return false+ }+ }+ static var int8Rows: Bool { ProcessInfo.processInfo.environment["KOKON_ANE_INT8"] != "w8" }/// 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).@@ -83,9 +100,6 @@ final class Coexecutor {var attentionGroups: [[AttentionSlot]] = []var attentionShape = (queries: 0, keys: 0)- /// Starting shares measured on the M2 Pro 16 GB, 1024² + 32 text rows (`time-dit`, 2026-10-25): 2 048 rows on the- /// Neural Engine and 1/16 on the AMX (AMX 512 rows 12.8 s per evaluation, 256 rows 11.3 s, none 11.8 s; GPU alone- /// 16.2 s). The balancing loop moves them from the first evaluation on.init(context: MetalContext, rows: Int, maxRows: Int? = nil, ane: Bool = true, amx: Bool = true, aneAttention: Bool = false,halfWeights: Bool = false) throws {self.context = context@@ -94,9 +108,16 @@ final class Coexecutor {self.maxRows = max(rows, maxRows ?? rows)self.aneEnabled = aneself.amxEnabled = amx- aneRows = ane ? min(2048, max(0, (rows - 512) / 256 * 256)) : 0- heads = HeadSplit.fromEnvironment() ?? HeadSplit.default(ane: ane && aneAttention, cpu: amx)- balancer = Balancer(aneAttention: ane && aneAttention)+ aneInt8 = ane && Coexecutor.int8Selected(Chip.current)+ aneHalfRows = !Coexecutor.int8Rows+ // 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)+ aneRows = ane ? balancer.bestAneRows(rows: rows, amx: amx) ?? min(2048, max(0, (rows - 512) / 256 * 256)) : 0+ if amx {+ for kind in Balancer.evaluationCounts.keys { amxRows[kind] = balancer.amxRows(kind: kind, rest: rows - aneRows) }+ }+ heads = HeadSplit.fromEnvironment() ?? balancer.bestHeads(ane: ane, cpu: amx)let device = context.deviceguard let r = device.makeSharedEvent(), let a = device.makeSharedEvent(), let e = device.makeSharedEvent(),let g = device.makeSharedEvent() else {@@ -105,7 +126,13 @@ final class Coexecutor {(ready, amxDone, aneDone, gpuDone) = (r, a, e, g)scales = try context.scratch(rows * 4, label: "ane row scales")slots = [[], []]- slots = try productSlots(aneRows)+ do {+ slots = try productSlots(aneRows)+ } catch where aneInt8 {+ FileHandle.standardError.write(Data("int8 Neural Engine programs unavailable (\(error)); fp16 instead\n".utf8))+ aneInt8 = false+ slots = try productSlots(aneRows)+ }}/// Two sets of three programs of `rows` rows (the tiles of a product, at most 3), compiled and warmed.@@ -113,12 +140,13 @@ final class Coexecutor {guard rows > 0 else { return [[], []] }let device = context.devicelet first: [ProductSlot] = try (0..<3).map { _ in- let p = try NeuralEngineProduct(rows: rows, k: Coexecutor.tile, n: Coexecutor.tile)+ let p = try NeuralEngineProduct(rows: rows, k: Coexecutor.tile, n: Coexecutor.tile, int8: aneInt8, halfActivations: aneHalfRows)try p.run()return (p, try p.gpuBuffer(p.x, device: device), try p.gpuBuffer(p.w, device: device), try p.gpuBuffer(p.y, device: device))}let second: [ProductSlot] = try first.map { f in- let p = try NeuralEngineProduct(rows: rows, k: Coexecutor.tile, n: Coexecutor.tile, sharing: f.product)+ let p = try NeuralEngineProduct(rows: rows, k: Coexecutor.tile, n: Coexecutor.tile, int8: aneInt8, halfActivations: aneHalfRows,+ sharing: f.product)try p.run()return (p, f.x, try p.gpuBuffer(p.w, device: device), f.y)}@@ -198,25 +226,34 @@ final class Coexecutor {packedAhead = nilcurrentSet = setlet slots = self.slots[set]+ // int8 rows are scaled per row alone, so any reader's packing serves the others from the first evaluation.let shared = sharedRows && readers.count > 1 && readers.count <= 3 && readers.contains(weight)- && readers.allSatisfy { columnScales[$0] != nil }+ && (aneInt8 || readers.allSatisfy { columnScales[$0] != nil })let packed = shared && packedRows.map { $0.offset == a.offset && $0.readers == readers } ?? falseif s.ane > 0, !packed {var sh = shape()- let bounds = shared ? readers.map { columnScales[$0]! } : [columns]+ let bounds = shared && !aneInt8 ? readers.map { columnScales[$0]! } : [columns] // L: fp16 onlypackedRows = shared ? (a.offset, readers) : nil- try kernel("ane_row_scales") { e in- 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))+ if aneInt8 {+ try kernel(aneHalfRows ? "ane8w_row_scales" : "ane8_row_scales") { e in+ e.setBuffer(a.buffer, offset: a.offset, index: 0); e.setBuffer(scales, offset: sigma, index: 1)+ e.setBytes(&sh, length: MemoryLayout<Shape>.stride, index: 2)+ e.dispatchThreadgroups(MTLSize(width: s.ane, height: 1, depth: 1), threadsPerThreadgroup: MTLSize(width: 256, height: 1, depth: 1))+ }+ } else {+ try kernel("ane_row_scales") { e in+ 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))+ }}for kp in 0..<kParts {for np in 0..<nParts {let slot = slots[kp * nParts + np]var t = shape(kp: kp, np: np)- try kernel("ane_pack_rows") { e in+ try kernel(aneInt8 && !aneHalfRows ? "ane8_pack_rows" : "ane_pack_rows") { e ine.setBuffer(a.buffer, offset: a.offset, index: 0); e.setBuffer(scales, offset: sigma, index: 1)e.setBuffer(slot.x, offset: 0, index: 2)e.setBytes(&t, length: MemoryLayout<Shape>.stride, index: 3)@@ -270,7 +307,7 @@ final class Coexecutor {for np in 0..<nParts {var t = shape(np: np)let ys = (0..<3).map { kp in slots[min(kp, kParts - 1) * nParts + np].y }- try kernel("ane_unpack") { e in+ try kernel(aneInt8 ? aneHalfRows ? "ane8w_unpack" : "ane8_unpack" : "ane_unpack") { e infor (i, y) in ys.enumerated() { e.setBuffer(y, offset: 0, index: i) }e.setBuffer(columns, offset: lambda, index: 3); e.setBuffer(scales, offset: sigma, index: 4)e.setBuffer(c.buffer, offset: c.offset, index: 5)@@ -307,6 +344,15 @@ final class Coexecutor {let columns = try context.scratch((2 * n + 16) * 4, label: "λ \(weight)")columnScales[weight] = columnsvar sh = Shape(k: UInt32(k), n: UInt32(n), k0: 0, kPart: 0, n0: 0, nPart: 0, row0: 0, rows: 0, kParts: 0)+ if aneInt8 { // [s (n)]: each column's int8 scale+ try kernel(halfWeights ? "ane8_columns_h" : "ane8_columns", commands) { e in+ e.setBuffer(w.buffer, offset: w.offset, index: 0); e.setBuffer(columns, offset: 0, index: 1)+ e.setBytes(&sh, length: MemoryLayout<Shape>.stride, index: 2)+ e.dispatchThreadgroups(MTLSize(width: (n + 63) / 64, height: 1, depth: 1),+ threadsPerThreadgroup: MTLSize(width: 64, height: 16, depth: 1))+ }+ return columns+ }try kernel(halfWeights ? "ane_columns_h" : "ane_columns", commands) { e ine.setBuffer(w.buffer, offset: w.offset, index: 0)e.setBuffer(columns, offset: 0, index: 1); e.setBuffer(columns, offset: n * 4, index: 2)@@ -330,7 +376,8 @@ final class Coexecutor {for np in 0..<nParts {var t = Shape(k: UInt32(k), n: UInt32(n), k0: UInt32(kp * Coexecutor.tile), kPart: UInt32(Coexecutor.tile),n0: UInt32(np * Coexecutor.tile), nPart: UInt32(Coexecutor.tile), row0: 0, rows: 0, kParts: UInt32(kParts))- try kernel(halfWeights ? "ane_pack_weight_h" : "ane_pack_weight", commands) { e in+ try kernel(aneInt8 ? (halfWeights ? "ane8_pack_weight_h" : "ane8_pack_weight")+ : halfWeights ? "ane_pack_weight_h" : "ane_pack_weight", commands) { e ine.setBuffer(w.buffer, offset: w.offset, index: 0); e.setBuffer(columns, offset: 0, index: 1)e.setBuffer(slots[set][kp * nParts + np].w, offset: 0, index: 2)e.setBytes(&t, length: MemoryLayout<Shape>.stride, index: 3)diff --git a/engine-mac/Sources/KokonEngine/Kernels/ane.metal b/engine-mac/Sources/KokonEngine/Kernels/ane.metalindex 5d45e0c..5c1e008 100644--- a/engine-mac/Sources/KokonEngine/Kernels/ane.metal+++ b/engine-mac/Sources/KokonEngine/Kernels/ane.metal@@ -162,3 +162,119 @@ kernel void ane_heads_unpack(device const half *src [[buffer(0)]], device floatif (c >= 128 || r >= s.valid || h >= s.heads) return;dst[(ulong)(s.row0 + r) * s.stride + s.column0 + h * 128 + c] = float(src[((ulong)h * s.rows + r) * 128 + c]);}++// The int8 products (`NeuralEngineProduct.int8Program`, for the Neural Engines with an int8 path): W quantized per+// column, s_j = max_k |W_kj| / 127; A per row, t_i = max_k |A_ik| / 127; the program returns y = (A_q · W_q) / K per+// 4 096 × 4 096 tile; C_ij = K · t_i · s_j · Σ_tiles y_ij in fp32. Following libnnc's row-wise int8 GEMM (ccv, BSD-3).++static inline char quantize8(float v, float scale) { return char(clamp(rint(v / scale), -127.0f, 127.0f)); }++// s_j per column of W [k, n] (as ane_columns: 64 columns, 16 row slices each).+template <typename T>+kernel void ane8_columns(device const T *w [[buffer(0)]], device float *scale [[buffer(1)]],+ constant AneShape &s [[buffer(2)]],+ uint2 tg [[threadgroup_position_in_grid]], uint2 t [[thread_position_in_threadgroup]]) {+ threadgroup float peaks[16][64];+ uint j = tg.x * 64 + t.x;+ float peak = 0;+ if (j < s.n) {+ for (uint r = t.y; r < s.k; r += 16) peak = max(peak, fabs(float(w[(ulong)r * s.n + j])));+ }+ peaks[t.y][t.x] = peak;+ 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]);+ scale[j] = (peak > 0 && isfinite(peak)) ? peak / 127.0f : 1.0f;+ }+}+template [[host_name("ane8_columns")]] kernel void ane8_columns<float>(device const float *, device float *, constant AneShape &, uint2, uint2);+template [[host_name("ane8_columns_h")]] kernel void ane8_columns<half>(device const half *, device float *, constant AneShape &, uint2, uint2);++// One weight tile, quantized, into its surface [kPart, nPart] int8.+template <typename T>+kernel void ane8_pack_weight(device const T *w [[buffer(0)]], device const float *scale [[buffer(1)]],+ device char *tile [[buffer(2)]], constant AneShape &s [[buffer(3)]],+ uint2 g [[thread_position_in_grid]]) {+ uint jj = g.x, kk = g.y;+ if (jj >= s.nPart || kk >= s.kPart) return;+ uint j = s.n0 + jj;+ tile[(ulong)kk * s.nPart + jj] = quantize8(float(w[(ulong)(s.k0 + kk) * s.n + j]), scale[j]);+}+template [[host_name("ane8_pack_weight")]] kernel void ane8_pack_weight<float>(device const float *, device const float *, device char *, constant AneShape &, uint2);+template [[host_name("ane8_pack_weight_h")]] kernel void ane8_pack_weight<half>(device const half *, device const float *, device char *, constant AneShape &, uint2);++// t_i of each Neural Engine row. One threadgroup of 256 per row.+kernel void ane8_row_scales(device const float *a [[buffer(0)]], device float *scale [[buffer(1)]],+ constant AneShape &s [[buffer(2)]],+ 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;+ float m = 0;+ for (uint c = tid; c < s.k; c += 256) m = max(m, fabs(row[c]));+ m = simd_max(m);+ if (tid % 32 == 0) shared[tid / 32] = m;+ threadgroup_barrier(mem_flags::mem_threadgroup);+ if (tid == 0) {+ float peak = 0;+ for (uint q = 0; q < 8; q++) peak = max(peak, shared[q]);+ scale[i] = (peak > 0 && isfinite(peak)) ? peak / 127.0f : 1.0f;+ }+}++// The Neural Engine's rows of A, quantized, into a tile's input surface [rows, kPart] int8.+kernel void ane8_pack_rows(device const float *a [[buffer(0)]], device const float *scale [[buffer(1)]],+ device char *x [[buffer(2)]], constant AneShape &s [[buffer(3)]],+ uint2 g [[thread_position_in_grid]]) {+ uint kk = g.x, i = g.y;+ if (kk >= s.kPart || i >= s.rows) return;+ x[(ulong)i * s.kPart + kk] = quantize8(a[(ulong)(s.row0 + i) * s.k + s.k0 + kk], scale[i]);+}++// C rows from the int8 tiles' outputs of one N range (up to 3 along K), scaled back.+kernel void ane8_unpack(device const half *y0 [[buffer(0)]], device const half *y1 [[buffer(1)]],+ device const half *y2 [[buffer(2)]], device const float *columnScale [[buffer(3)]],+ device const float *rowScale [[buffer(4)]], device float *c [[buffer(5)]],+ constant AneShape &s [[buffer(6)]], uint2 g [[thread_position_in_grid]]) {+ uint jj = g.x, i = g.y;+ if (jj >= s.nPart || i >= s.rows) return;+ ulong at = (ulong)i * s.nPart + jj;+ float sum = float(y0[at]);+ if (s.kParts > 1) sum += float(y1[at]);+ if (s.kParts > 2) sum += float(y2[at]);+ uint j = s.n0 + jj;+ c[(ulong)(s.row0 + i) * s.n + j] = sum * float(s.kPart) * rowScale[i] * columnScale[j];+}++// int8 weights with fp16 rows (W8A16): the rows lifted by σ_i = 2^floor(log2(2^15 / (127 max_k |A_ik|))), since+// |y| = |Σ_k x_k w_q,kj| / K <= max |x| · 127; then packed by `ane_pack_rows`; C_ij = K s_j Σ_tiles y_ij / σ_i.+kernel void ane8w_row_scales(device const float *a [[buffer(0)]], device float *sigma [[buffer(1)]],+ constant AneShape &s [[buffer(2)]],+ 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;+ float m = 0;+ for (uint c = tid; c < s.k; c += 256) m = max(m, fabs(row[c]));+ m = simd_max(m);+ if (tid % 32 == 0) shared[tid / 32] = m;+ threadgroup_barrier(mem_flags::mem_threadgroup);+ if (tid == 0) {+ float peak = 0;+ for (uint q = 0; q < 8; q++) peak = max(peak, shared[q]);+ float bound = peak * 127.0f;+ sigma[i] = (bound > 0 && isfinite(bound)) ? exp2(floor(log2(32768.0f / bound))) : 1.0f;+ }+}++kernel void ane8w_unpack(device const half *y0 [[buffer(0)]], device const half *y1 [[buffer(1)]],+ device const half *y2 [[buffer(2)]], device const float *columnScale [[buffer(3)]],+ device const float *sigma [[buffer(4)]], device float *c [[buffer(5)]],+ constant AneShape &s [[buffer(6)]], uint2 g [[thread_position_in_grid]]) {+ uint jj = g.x, i = g.y;+ if (jj >= s.nPart || i >= s.rows) return;+ ulong at = (ulong)i * s.nPart + jj;+ float sum = float(y0[at]);+ if (s.kParts > 1) sum += float(y1[at]);+ if (s.kParts > 2) sum += float(y2[at]);+ uint j = s.n0 + jj;+ c[(ulong)(s.row0 + i) * s.n + j] = sum * float(s.kPart) * columnScale[j] / sigma[i];+}diff --git a/engine-mac/Sources/KokonEngine/Kernels/metal4/na_matmul.metal b/engine-mac/Sources/KokonEngine/Kernels/metal4/na_matmul.metalnew file mode 100644index 0000000..31914f8--- /dev/null+++ b/engine-mac/Sources/KokonEngine/Kernels/metal4/na_matmul.metal@@ -0,0 +1,32 @@+#include <metal_stdlib>+#include <metal_tensor>+#include <MetalPerformancePrimitives/MetalPerformancePrimitives.h>+using namespace metal;+using namespace mpp::tensor_ops;++// C[m, n] = A[m, k] · B[k, n] through Metal 4's tensor operations (MetalPerformancePrimitives' matmul2d): on the M5's+// GPU they run on its neural accelerators, on older Metal 4 GPUs on the shader cores. Compiled apart from the other+// kernels (Metal 4, `NeuralAccelerators.swift`). The approach follows libnnc's NAMatMul (ccv, BSD-3, Liu Liu); this+// kernel is written for Kokon.+//+// A and B fp16, C fp32, row-major and dense; m and n multiples of 64 (the DiT pads every product to 64 rows, its+// widths are multiples of 4 096). One threadgroup of 4 SIMD groups per 64 × 64 tile of C, the whole K in one run.+// Tensor extents list the innermost dimension first: A is (k, m), B (n, k), C (n, m).++struct NAParams {+ uint m, n, k;+};++kernel void na_matmul(device half *A [[buffer(0)]], device half *B [[buffer(1)]], device float *C [[buffer(2)]],+ constant NAParams &p [[buffer(3)]], uint2 tg [[threadgroup_position_in_grid]]) {+ auto a = tensor<device half, dextents<int32_t, 2>, tensor_inline>(A, dextents<int32_t, 2>(p.k, p.m));+ auto b = tensor<device half, dextents<int32_t, 2>, tensor_inline>(B, dextents<int32_t, 2>(p.n, p.k));+ auto c = tensor<device float, dextents<int32_t, 2>, tensor_inline>(C, dextents<int32_t, 2>(p.n, p.m));+ constexpr auto descriptor = matmul2d_descriptor(64, 64, dynamic_length_v<int>, false, false, false,+ matmul2d_descriptor::mode::multiply);+ matmul2d<descriptor, execution_simdgroups<4>> op;+ auto mA = a.slice(0, int(tg.y) * 64);+ auto mB = b.slice(int(tg.x) * 64, 0);+ auto mC = c.slice(int(tg.x) * 64, int(tg.y) * 64);+ op.run(mA, mB, mC);+}diff --git a/engine-mac/Sources/KokonEngine/NeuralAccelerators.swift b/engine-mac/Sources/KokonEngine/NeuralAccelerators.swiftnew file mode 100644index 0000000..cd84dca--- /dev/null+++ b/engine-mac/Sources/KokonEngine/NeuralAccelerators.swift@@ -0,0 +1,73 @@+import Foundation+import Metal++/// **The GPU's rows of a product on its neural accelerators** (`Kernels/metal4/na_matmul.metal`: Metal 4's tensor+/// operations, MetalPerformancePrimitives' `matmul2d`). On the M5 (Apple10 GPUs) they run on the matrix units each GPU+/// core gained; on older Metal 4 GPUs the same source runs on the shader cores, so its results can be checked on any+/// Mac with macOS 26 or later (`swift test`, `check-na`), only not its speed.+///+/// Selected for the split products' GPU rows wherever Metal 4 runs (fp16 A and weights, the defaults), MPS when the+/// source does not compile or with `KOKON_NA=0`. On the M2 Pro's shader cores it beats MPS too: 6.3 against 5.6+/// TFLOP/s at 1536 × 4096 × 4096, bit for bit the same result (`check-na`), and per evaluation at 1024², 3 alternated+/// rounds of 4, 7.57 → 7.48 s (2026-10-25). Not yet run on an M5, M1, M3 or M4; the attention stays on the engine's+/// own kernels.+public final class NeuralAccelerators: @unchecked Sendable {+ let pipeline: MTLComputePipelineState+ /// Why `make` returned nil, for the bench's report.+ nonisolated(unsafe) public private(set) static var unavailable: String?++ struct Params { var m, n, k: UInt32 }++ /// Compiles the kernel; nil without Metal 4 or when the compiler refuses the source.+ public static func make(device: MTLDevice) -> NeuralAccelerators? {+ guard #available(macOS 26, *), device.supportsFamily(.metal4) else {+ unavailable = "no Metal 4 on this GPU or macOS"+ return nil+ }+ do {+ guard let url = Bundle.module.url(forResource: "Kernels", withExtension: nil)?+ .appendingPathComponent("metal4/na_matmul.metal") else { throw MetalContext.Failure.noKernelSource }+ let options = MTLCompileOptions()+ options.languageVersion = .version4_0+ options.mathMode = .safe+ let library = try device.makeLibrary(source: try String(contentsOf: url, encoding: .utf8), options: options)+ guard let function = library.makeFunction(name: "na_matmul") else { throw MetalContext.Failure.kernel("na_matmul not found") }+ return NeuralAccelerators(pipeline: try device.makeComputePipelineState(function: function))+ } catch {+ unavailable = "the kernel did not compile: \(error.localizedDescription)"+ return nil+ }+ }++ init(pipeline: MTLComputePipelineState) { self.pipeline = pipeline }++ /// Whether the split products' GPU rows go through them on this device.+ public static func selected(device: MTLDevice) -> Bool {+ switch ProcessInfo.processInfo.environment["KOKON_NA"] {+ case "0": return false+ case "1": return true+ default: if #available(macOS 26, *) { return device.supportsFamily(.metal4) } else { return false }+ }+ }++ /// Whether a product fits the kernel (no edge tiles).+ static func fits(m: Int, n: Int, k: Int) -> Bool { m % 64 == 0 && n % 64 == 0 && m > 0 && n > 0 && k > 0 }++ /// Encodes `C[m, n] = A[m, k] · B[k, n]`, A and B fp16, C fp32, dense rows.+ func encode(a: (MTLBuffer, Int), b: (MTLBuffer, Int), c: (MTLBuffer, Int), m: Int, n: Int, k: Int,+ commands: MTLCommandBuffer) throws {+ guard NeuralAccelerators.fits(m: m, n: n, k: k), let e = commands.makeComputeCommandEncoder() else {+ throw MetalContext.Failure.kernel("na_matmul \(m)×\(n)×\(k)")+ }+ e.label = "na_matmul"+ e.setComputePipelineState(pipeline)+ e.setBuffer(a.0, offset: a.1, index: 0)+ e.setBuffer(b.0, offset: b.1, index: 1)+ e.setBuffer(c.0, offset: c.1, index: 2)+ var p = Params(m: UInt32(m), n: UInt32(n), k: UInt32(k))+ e.setBytes(&p, length: MemoryLayout<Params>.stride, index: 3)+ e.dispatchThreadgroups(MTLSize(width: n / 64, height: m / 64, depth: 1),+ threadsPerThreadgroup: MTLSize(width: pipeline.threadExecutionWidth * 4, height: 1, depth: 1))+ e.endEncoding()+ }+}diff --git a/engine-mac/Sources/KokonEngine/NeuralEngine.swift b/engine-mac/Sources/KokonEngine/NeuralEngine.swiftindex 0d19f68..cda9410 100644--- a/engine-mac/Sources/KokonEngine/NeuralEngine.swift+++ b/engine-mac/Sources/KokonEngine/NeuralEngine.swift@@ -21,6 +21,8 @@ import Foundation/// - rows in units of 256.public final class NeuralEngineProduct: @unchecked Sendable {public let rows: Int, k: Int, n: Int+ /// int8 `w` (`int8Program`), and int8 `x` too unless `halfActivations`; the output fp16.+ public let int8: Bool, halfActivations: Boolprivate let model: MLModelprivate let features: MLFeatureProviderprivate let options: MLPredictionOptions@@ -38,13 +40,15 @@ public final class NeuralEngineProduct: @unchecked Sendable {}/// `sharing`: a program of the same shape whose `x` and `y` surfaces this one uses too (its own weight only).- public init(rows: Int, k: Int, n: Int, sharing: NeuralEngineProduct? = nil) throws {- self.rows = rows; self.k = k; self.n = n+ public init(rows: Int, k: Int, n: Int, int8: Bool = false, halfActivations: Bool = false, sharing: NeuralEngineProduct? = nil) throws {+ self.rows = rows; self.k = k; self.n = n; self.int8 = int8; self.halfActivations = int8 && halfActivations+ let int8x = int8 && !halfActivations(model, directory) = try NeuralEngineProduct.compile(- "\(rows)x\(k)x\(n)", program: NeuralEngineProduct.program(rows: rows, k: k, n: n),- inputs: [("x", [rows, k]), ("w", [k, n])], outputs: [("y", [rows, n])])- x = try sharing?.x ?? NeuralEngineProduct.surface(rows: rows, columns: k)- w = try NeuralEngineProduct.surface(rows: k, columns: n)+ "\(rows)x\(k)x\(n)\(int8 ? int8x ? "-int8" : "-w8" : "")",+ program: int8 ? NeuralEngineProduct.int8Program(rows: rows, k: k, n: n, int8x: int8x) : NeuralEngineProduct.program(rows: rows, k: k, n: n),+ inputs: [("x", [rows, k]), ("w", [k, n])], outputs: [("y", [rows, n])], int8Inputs: int8 ? (int8x ? ["x", "w"] : ["w"]) : [])+ x = try sharing?.x ?? NeuralEngineProduct.surface(rows: rows, columns: k, int8: int8x)+ w = try NeuralEngineProduct.surface(rows: k, columns: n, int8: int8)y = try sharing?.y ?? NeuralEngineProduct.surface(rows: rows, columns: n)func shape(_ dims: Int...) -> [NSNumber] { dims.map { NSNumber(value: $0) } }options = MLPredictionOptions()@@ -76,13 +80,13 @@ public final class NeuralEngineProduct: @unchecked Sendable {CVPixelBufferUnlockBaseAddress(y, .readOnly)}- /// A dense fp16 surface `rows × columns` (no row padding: the program reads it dense).- static func surface(rows: Int, columns: Int) throws -> CVPixelBuffer {+ /// A dense fp16 (or int8) surface `rows × columns` (no row padding: the program reads it dense).+ static func surface(rows: Int, columns: Int, int8: Bool = false) throws -> CVPixelBuffer {var buffer: CVPixelBuffer?let attributes = [kCVPixelBufferIOSurfacePropertiesKey: [:]] as CFDictionary- guard CVPixelBufferCreate(kCFAllocatorDefault, columns, rows, kCVPixelFormatType_OneComponent16Half,+ guard CVPixelBufferCreate(kCFAllocatorDefault, columns, rows, int8 ? kCVPixelFormatType_OneComponent8 : kCVPixelFormatType_OneComponent16Half,attributes, &buffer) == kCVReturnSuccess, let buffer,- CVPixelBufferGetBytesPerRow(buffer) == columns * 2 else {+ CVPixelBufferGetBytesPerRow(buffer) == columns * (int8 ? 1 : 2) else {throw Failure.surface("\(rows)×\(columns) is not dense")}return buffer@@ -103,16 +107,87 @@ public final class NeuralEngineProduct: @unchecked Sendable {"""}+ /// **The int8 product**, for the Neural Engines with an int8 path (M3, M4; `Coexecutor.aneInt8`): `x` and `w` int8,+ /// each dequantized by 1/√K inside the program (a power of two for K = 4 096), so |y| ≤ 127² stays in fp16, and K+ /// cut into pieces of at most 2 688 summed in fp16. The caller quantizes A per row and W per column and scales y back+ /// (`ane8_*` in `ane.metal`). The program's form follows libnnc's Core ML int8 GEMM (ccv, BSD-3, Liu Liu:+ /// `ccv_nnc_mfa_ane_rowwise_coreml.mm`, which measured the K limit on an M4), in this engine's layout: x [rows, K]+ /// and w [K, N] row-major, as the fp16 program, where libnnc multiplies W [N, K] by X [K, M].+ static func int8Program(rows: Int, k: Int, n: Int, int8x: Bool = true) -> String {+ let pieces = k <= 2688 ? 1 : (k + 2047) / 2048+ let part = k / pieces+ let xType = int8x ? "int8" : "fp16"+ // int8 x: both operands by 1/√K; fp16 x (W8A16): the weight alone by 1/K, x as the caller scaled it.+ let (dx, dw) = int8x ? (1 / Float(k).squareRoot(), 1 / Float(k).squareRoot()) : (1, 1 / Float(k))+ var body = """+ fp16 dx = const()[name = string("dx"), val = fp16(\(String(format: "%a", dx)))];+ fp16 dw = const()[name = string("dw"), val = fp16(\(String(format: "%a", dw)))];+ bool f = const()[name = string("f"), val = bool(false)];++ """+ func operands(_ x: String, _ w: String, _ suffix: String, _ xRows: Int, _ kk: Int) -> String {+ (int8x ? """+ tensor<fp16, [\(xRows), \(kk)]> xh\(suffix) = dequantize(input = \(x), scale = dx)[name = string("xh\(suffix)")];++ """ : "") + """+ tensor<fp16, [\(kk), \(n)]> wh\(suffix) = dequantize(input = \(w), scale = dw)[name = string("wh\(suffix)")];++ """+ }+ func xh(_ x: String, _ suffix: String) -> String { int8x ? "xh\(suffix)" : x }+ if pieces == 1 {+ body += operands("x", "w", "", rows, k) + """+ tensor<fp16, [\(rows), \(n)]> y = matmul(transpose_x = f, transpose_y = f, x = \(xh("x", "")), y = wh)[name = string("y")];++ """+ } else {+ body += """+ tensor<int32, [2]> xs = const()[name = string("xs"), val = tensor<int32, [2]>([\(rows), \(part)])];+ tensor<int32, [2]> ws = const()[name = string("ws"), val = tensor<int32, [2]>([\(part), \(n)])];++ """+ for i in 0..<pieces {+ body += """+ tensor<int32, [2]> xb\(i) = const()[name = string("xb\(i)"), val = tensor<int32, [2]>([0, \(i * part)])];+ tensor<int32, [2]> wb\(i) = const()[name = string("wb\(i)"), val = tensor<int32, [2]>([\(i * part), 0])];+ tensor<\(xType), [\(rows), \(part)]> xq\(i) = slice_by_size(x = x, begin = xb\(i), size = xs)[name = string("xq\(i)")];+ tensor<int8, [\(part), \(n)]> wq\(i) = slice_by_size(x = w, begin = wb\(i), size = ws)[name = string("wq\(i)")];++ """ + operands("xq\(i)", "wq\(i)", "\(i)", rows, part) + """+ tensor<fp16, [\(rows), \(n)]> m\(i) = matmul(transpose_x = f, transpose_y = f, x = \(xh("xq\(i)", "\(i)")), y = wh\(i))[name = string("m\(i)")];++ """+ }+ var sum = "m0"+ for i in 1..<pieces {+ let out = i == pieces - 1 ? "y" : "s\(i)"+ body += """+ tensor<fp16, [\(rows), \(n)]> \(out) = add(x = \(sum), y = m\(i))[name = string("\(out)")];++ """+ sum = out+ }+ }+ return """+ program(1.3)+ [buildInfo = dict<string, string>({{"coremlc-component-MIL", "3600.16.1"}, {"coremlc-version", "3600.25.2"}})]+ {+ func main<ios19>(tensor<int8, [\(k), \(n)]> w, tensor<\(xType), [\(rows), \(k)]> x) {+ \(body) } -> (y);+ }+ """+ }+/// Writes `program` and its description as a compiled model in a temporary directory and loads it for the- /// CPU and the Neural Engine. `tag` names the directory.+ /// CPU and the Neural Engine. `tag` names the directory; `int8Inputs`: the inputs are int8 arrays.static func compile(_ tag: String, program: String, inputs: [(String, [Int])],- outputs: [(String, [Int])]) throws -> (MLModel, URL) {+ outputs: [(String, [Int])], int8Inputs: Set<String> = []) throws -> (MLModel, URL) {let directory = FileManager.default.temporaryDirectory.appendingPathComponent("kokon-ane-\(ProcessInfo.processInfo.processIdentifier)-\(tag)-\(UUID().uuidString)").appendingPathExtension("mlmodelc")try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)try program.write(to: directory.appendingPathComponent("model.mil"), atomically: true, encoding: .utf8)- try description(inputs: inputs, outputs: outputs).write(to: directory.appendingPathComponent("coremldata.bin"))+ try description(inputs: inputs, outputs: outputs, int8Inputs: int8Inputs).write(to: directory.appendingPathComponent("coremldata.bin"))let configuration = MLModelConfiguration()configuration.computeUnits = .cpuAndNeuralEnginedo {@@ -125,7 +200,7 @@ public final class NeuralEngineProduct: @unchecked Sendable {/// `coremldata.bin`: a fixed header with the description's length (little-endian u64 at 0x4b), the/// model description as protobuf (named fp16 multi-arrays in and out), a fixed trailer.- static func description(inputs: [(String, [Int])], outputs: [(String, [Int])]) -> Data {+ static func description(inputs: [(String, [Int])], outputs: [(String, [Int])], int8Inputs: Set<String> = []) -> Data {func varint(_ value: Int) -> [UInt8] {var v = UInt64(value), out: [UInt8] = []repeat {@@ -136,13 +211,13 @@ public final class NeuralEngineProduct: @unchecked Sendable {return out}func field(_ tag: UInt8, _ body: [UInt8]) -> [UInt8] { [tag] + varint(body.count) + body }- // A feature: name, then a multi-array type of `dims` in FLOAT16 (ArrayDataType 65 552).- func feature(_ tag: UInt8, _ name: String, _ dims: [Int]) -> [UInt8] {+ // A feature: name, then a multi-array type of `dims` in FLOAT16 (ArrayDataType 65 552) or INT8 (131 080).+ func feature(_ tag: UInt8, _ name: String, _ dims: [Int], int8: Bool = false) -> [UInt8] {let shape = field(0x0a, dims.flatMap(varint))- let array = field(0x2a, shape + [0x10] + varint(65_552))+ let array = field(0x2a, shape + [0x10] + varint(int8 ? 0x20008 : 65_552))return field(tag, field(0x0a, Array(name.utf8)) + field(0x1a, array))}- let payload: [UInt8] = inputs.flatMap { feature(0x0a, $0.0, $0.1) } + outputs.flatMap { feature(0x52, $0.0, $0.1) }+ let payload: [UInt8] = inputs.flatMap { feature(0x0a, $0.0, $0.1, int8: int8Inputs.contains($0.0)) } + outputs.flatMap { feature(0x52, $0.0, $0.1) }+ [0xa2, 0x06, 0x00]var header = [UInt8](repeating: 0, count: 0x53)header[0] = 0xf6; header[1] = 0x01; header[4] = 0x09; header[0x1c] = 0x07diff --git a/engine-mac/Sources/KokonEngine/QwenDiT.swift b/engine-mac/Sources/KokonEngine/QwenDiT.swiftindex 0a390dc..1827015 100644--- a/engine-mac/Sources/KokonEngine/QwenDiT.swift+++ b/engine-mac/Sources/KokonEngine/QwenDiT.swift@@ -62,6 +62,9 @@ public final class QwenDiT {/// **Weights unpacked to fp16** (`KOKON_WEIGHTS=fp32`: fp32, for the accuracy checks): half the bytes the unpacking/// writes and every unit reads; the GPU's products are MPS fp32 × fp16 with fp32 accumulation, the AMX's BNNS the same.let halfWeights = ProcessInfo.processInfo.environment["KOKON_WEIGHTS"] != "fp32"+ /// The split products' GPU rows on the GPU's neural accelerators (M5; `NeuralAccelerators.swift`), else MPS.+ lazy var accelerators: NeuralAccelerators? = halfWeights && NeuralAccelerators.selected(device: context.device)+ ? NeuralAccelerators.make(device: context.device) : nilprivate var attentions: [String: GraphAttention] = [:]/// Seconds per phase of the last evaluation.public private(set) var timings: [String: Double] = [:]@@ -428,6 +431,11 @@ public final class QwenDiT {let reserve = reserves[index]// The GPU's rows: all of them, or its share of a split product.func gpuRows(_ rows: Int, _ half: MTLBuffer? = nil) throws {+ if let half, let accelerators, NeuralAccelerators.fits(m: rows, n: nn, k: kk) {+ try accelerators.encode(a: (half, 0), b: (arena.buffer, reserve.offset), c: (arena.buffer, c.offset + cRow * nn * 4),+ m: rows, n: nn, k: kk, commands: commands)+ return+ }let key = "\(rows)×\(kk)×\(nn)"let product: MPSMatrixMultiplicationif let existing = products[key] { product = existing } else {@@ -601,7 +609,15 @@ public final class QwenDiT {/// (`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"+ lazy var packedKernel = QwenDiT.directAttention(device: context.device) ? "flash_attention_direct" : "flash_attention_packed"+ /// `flash_attention_direct` on Apple9+ GPUs; `KOKON_ATTENTION_DIRECT=0` / `=1` to choose.+ static func directAttention(device: MTLDevice) -> Bool {+ switch ProcessInfo.processInfo.environment["KOKON_ATTENTION_DIRECT"] {+ case "0": return false+ case "1": return true+ default: return device.supportsFamily(.apple9)+ }+ }/// 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`).diff --git a/engine-mac/Sources/KokonEngine/QwenPipeline.swift b/engine-mac/Sources/KokonEngine/QwenPipeline.swiftindex 103108b..0ae5063 100644--- a/engine-mac/Sources/KokonEngine/QwenPipeline.swift+++ b/engine-mac/Sources/KokonEngine/QwenPipeline.swift@@ -57,8 +57,8 @@ public final class QwenPipeline {/// What the server reports while an image runs.public enum Event { case encoded(tokens: Int, seconds: Double), step(Int, of: Int, seconds: Double), decoding }public var events: ((Event) -> Void)?- /// The co-executor's shares for the next evaluation of the kept DiT (`keepModels`).- public var shares: String? { dit?.coexecutor?.shares }+ /// The co-executor's shares after the last image's steps (nil: the GPU alone).+ public private(set) var shares: String?public init(encoder: String, dit: String, vae: String) throws {encoderPath = encoder@@ -148,6 +148,7 @@ public final class QwenPipeline {events?(.step(i + 1, of: sigmas.count - 1, seconds: timings["step \(i + 1)"]!))step?(i, x)}+ shares = dit.coexecutor?.shares}()// 4. The image.diff --git a/engine-mac/Sources/kokon-engine-mac/main.swift b/engine-mac/Sources/kokon-engine-mac/main.swiftindex d0185c9..a6652ab 100644--- a/engine-mac/Sources/kokon-engine-mac/main.swift+++ b/engine-mac/Sources/kokon-engine-mac/main.swift@@ -21,6 +21,11 @@ kokon-engine-mac: Kokon's Apple Silicon engine (in development)text to image, Turbo's 8 steps (default 1024x1024, seed 42, out.png)serve --diffusion-model <dit.gguf> --vae <vae.safetensors> --llm <encoder.gguf> [--listen-ip 127.0.0.1] [--listen-port 1234]the engine as a server speaking sd-server's /sdcpp/v1 API (text to image)+ bench [--quick] [--out report.md] [--encoder P --dit P --vae P]+ a few minutes: this Mac's paths, speed at 1024², accuracy against the fp32 path;+ prints a report to paste in a GitHub issue (Kokon's model files by default)+ check-ane8 the M3/M4 path (int8 Neural Engine program) against the fp16 one+ check-na the M5 path (Metal 4 tensor operations) against MPS on one productprobe this Mac's matrix throughput: GPU, AMX, Neural Engine, togetherprobe-attention the target's attention at 1024² on the GPU, the Neural Engine, the CPU"""@@ -126,6 +131,38 @@ do {let server = try HTTPServer(host: ip, port: port) { engine.handle($0) }print("[INFO ] engine-mac - listening on: http://\(ip):\(server.port)")server.run()+ case "bench":+ // bench [--encoder P] [--dit P] [--vae P] [--quick] [--out report.md]; Kokon's files by default.+ let models = FileManager.default.homeDirectoryForCurrentUser+ .appendingPathComponent("Library/Application Support/KokonData/sdcpp/models/qwen21").path+ func existing(_ names: [String]) -> String { names.map { models + "/" + $0 }.first { FileManager.default.fileExists(atPath: $0) } ?? models + "/" + names[0] }+ var encoder = existing(["Qwen3VL-8B-Instruct-Q4_K_M.gguf"])+ var dit = existing(["qwen-image-2.1-turbo-Q4_K_M.gguf", "qwen-image-2.1-turbo-Q4_K.gguf"])+ var vae = existing(["texture_fix_vae_for_qwen_image_2.1_bf16.safetensors", "qwen_image_2.1_vae_bf16.safetensors"])+ var (quick, out): (Bool, String?) = (false, nil)+ var options = arguments.dropFirst().makeIterator()+ while let option = options.next() {+ switch option {+ case "--quick": quick = true+ case "--encoder": encoder = options.next() ?? encoder+ case "--dit": dit = options.next() ?? dit+ case "--vae": vae = options.next() ?? vae+ case "--out": out = options.next()+ default: fail("unknown option \(option)\n\n" + usage)+ }+ }+ for path in [encoder, dit, vae] where !FileManager.default.fileExists(atPath: path) {+ fail("\(path) not found: install Kokon's models, or pass --encoder, --dit and --vae")+ }+ try Bench.run(encoder: encoder, dit: dit, vae: vae, quick: quick, out: out)+ case "bench-run":+ guard arguments.count >= 6 else { fail(usage) }+ try Bench.child(mode: arguments[1], encoder: arguments[2], dit: arguments[3], vae: arguments[4], prefix: arguments[5],+ quick: arguments.contains("--quick"))+ case "check-ane8":+ try Checks.aneInt8()+ case "check-na":+ try Checks.neuralAccelerators()case "probe":try Probe.run()case "probe-attention":diff --git a/engine-mac/Tests/KokonEngineTests/PerChipTests.swift b/engine-mac/Tests/KokonEngineTests/PerChipTests.swiftnew file mode 100644index 0000000..df1dcca--- /dev/null+++ b/engine-mac/Tests/KokonEngineTests/PerChipTests.swift@@ -0,0 +1,103 @@+import CoreVideo+import Metal+import XCTest+@testable import KokonEngine++/// The per-chip paths, checked for correctness on whatever Mac runs the tests: their speed needs the chip they are+/// for (`kokon-engine-mac bench`), their results do not.+final class PerChipTests: XCTestCase {+ /// `na_matmul` (the M5's neural accelerators; shader cores on older Metal 4 GPUs) against a product in double of+ /// the same fp16 operands, on shapes with several tiles along m and n and a K that is not a power of two.+ func testNeuralAcceleratorProduct() throws {+ let device = try XCTUnwrap(MTLCreateSystemDefaultDevice())+ guard let na = NeuralAccelerators.make(device: device) else {+ throw XCTSkip("Metal 4 tensor operations unavailable: \(NeuralAccelerators.unavailable ?? "?")")+ }+ let context = try MetalContext()+ let (m, k, n) = (192, 320, 128)+ var seed: UInt64 = 11+ func random() -> Float16 {+ seed = seed &* 6364136223846793005 &+ 1442695040888963407+ return Float16(Float(seed >> 40) / Float(1 << 24) - 0.5)+ }+ let a = (0..<(m * k)).map { _ in random() }, b = (0..<(k * n)).map { _ in random() }+ let ab = try context.scratch(a.count * 2, label: "A"), bb = try context.scratch(b.count * 2, label: "B")+ ab.contents().copyMemory(from: a, byteCount: a.count * 2)+ bb.contents().copyMemory(from: b, byteCount: b.count * 2)+ let cb = try context.scratch(m * n * 4, label: "C")+ let commands = context.queue.makeCommandBuffer()!+ try na.encode(a: (ab, 0), b: (bb, 0), c: (cb, 0), m: m, n: n, k: k, commands: commands)+ try MetalContext.finish(commands, "na_matmul")+ let c = cb.contents().assumingMemoryBound(to: Float.self)+ var worst = 0.0, scale = 0.0+ for i in 0..<m {+ for j in 0..<n {+ var s = 0.0+ for l in 0..<k { s += Double(a[i * k + l]) * Double(b[l * n + j]) }+ worst = max(worst, abs(Double(c[i * n + j]) - s))+ scale = max(scale, abs(s))+ }+ }+ XCTAssertLessThan(worst / scale, 1e-5, "fp16 products accumulated in fp32")+ }++ func testChipNames() {+ XCTAssertEqual(Chip.generation(of: "Apple M2 Pro"), 2)+ XCTAssertEqual(Chip.generation(of: "Apple M4 Max"), 4)+ XCTAssertEqual(Chip.generation(of: "Apple M10"), 10)+ XCTAssertNil(Chip.generation(of: "Intel(R) Core(TM) i9"))+ let here = Chip.current+ XCTAssertGreaterThan(here.gpuFamily, 6)+ XCTAssertGreaterThan(here.performanceCores, 0)+ }++ /// The first evaluation's shares from the cost model: on any chip they add up and keep each unit in its range.+ func testStartingShares() throws {+ let balancer = Balancer(aneAttention: false, chip: Chip.current)+ let rows = 4096+ let ane = try XCTUnwrap(balancer.bestAneRows(rows: rows, amx: true))+ XCTAssertTrue((1024...(rows - 512)).contains(ane) && ane % 256 == 0, "\(ane)")+ for kind in Balancer.evaluationCounts.keys {+ let amx = try XCTUnwrap(balancer.amxRows(kind: kind, rest: rows - ane))+ XCTAssertTrue(amx % 64 == 0 && amx >= 0 && amx < rows - ane, "\(kind): \(amx)")+ }+ let heads = balancer.bestHeads(ane: true, cpu: true)+ XCTAssertEqual(heads.gpu + heads.ane + heads.cpu, QwenDiT.heads)+ XCTAssertGreaterThan(heads.gpu, 0)+ }+}++extension PerChipTests {+ /// The int8 Neural Engine program (the M3/M4 path) against the exact product of its int8 operands, with K in one+ /// piece and cut in two (over 2 688).+ func testNeuralEngineInt8Product() throws {+ guard #available(macOS 26, *) else { throw XCTSkip("the int8 program needs macOS 26") }+ for (rows, k, n) in [(256, 512, 128), (256, 3072, 128)] {+ let p = try NeuralEngineProduct(rows: rows, k: k, n: n, int8: true)+ var seed = UInt64(k)+ func random() -> Int8 {+ seed = seed &* 6364136223846793005 &+ 1442695040888963407+ return Int8(Int(seed >> 56) - 128 == -128 ? 0 : Int(seed >> 56) - 128)+ }+ let x = (0..<(rows * k)).map { _ in random() }, w = (0..<(k * n)).map { _ in random() }+ for (surface, values) in [(p.x, x), (p.w, w)] {+ CVPixelBufferLockBaseAddress(surface, [])+ CVPixelBufferGetBaseAddress(surface)!.copyMemory(from: values, byteCount: values.count)+ CVPixelBufferUnlockBaseAddress(surface, [])+ }+ try p.run()+ var worst = 0.0+ p.read { y in+ for i in stride(from: 0, to: rows, by: 17) {+ for j in 0..<n {+ var s = 0+ for l in 0..<k { s += Int(x[i * k + l]) * Int(w[l * n + j]) }+ let want = Double(s) / Double(k) // the program's 1/√K on each operand+ worst = max(worst, abs(Double(y[i * n + j]) - want) / 16129)+ }+ }+ }+ XCTAssertLessThan(worst, 2e-3, "\(rows)×\(k)×\(n): fp16 output of a sum bounded by 127²")+ }+ }+}diff --git a/engine-mac/tools/bench.sh b/engine-mac/tools/bench.shnew file mode 100755index 0000000..a59377e--- /dev/null+++ b/engine-mac/tools/bench.sh@@ -0,0 +1,14 @@+#!/bin/bash+# The Mac engine's benchmark for testers: builds kokon-engine-mac, runs `bench` on Kokon's model files (a few+# minutes; the Mac should be plugged in and otherwise idle) and writes kokon-bench-report.md to paste in GitHub.+#+# bash engine-mac/tools/bench.sh [--quick] [--encoder P --dit P --vae P]+#+# Needs the Xcode command line tools (`xcode-select --install`) and Kokon's models (Kokon set up once, or the three+# files passed by hand). Nothing is uploaded: the report is a text file.+set -euo pipefail+here="$(cd "$(dirname "$0")/.." && pwd)"+(cd "$here" && swift build -c release 2>&1 | tail -1)+commit="$(git -C "$here" rev-parse --short HEAD 2>/dev/null || echo unknown)"+out="$PWD/kokon-bench-report.md"+KOKON_ENGINE_VERSION="0.1 (experimental), commit $commit" "$here/.build/release/kokon-engine-mac" bench --out "$out" "$@"