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: contributor guide, fixed test set, bench JSON and CI (#45)

Gabriele Lozuponeca4072ba121a
diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md
index 2bfb300..90c54b1 100644
--- a/.github/pull_request_template.md
+++ b/.github/pull_request_template.md
@@ -10,6 +10,7 @@
- [ ] `npm test` (UI logic)
- [ ] `cd mcp && npm test` (only if `mcp/` changed)
- [ ] Tried it in the app (`npx tauri dev`), if it changes behavior or the UI
+- [ ] `engine-mac/` changed: `swift test`, and the report from [engine-mac/AGENTS.md](https://github.com/GabrieleLozupone/kokon/blob/master/engine-mac/AGENTS.md#the-pull-request-report) below
## Notes
diff --git a/.github/workflows/engine-mac.yml b/.github/workflows/engine-mac.yml
new file mode 100644
index 0000000..50889ee
--- /dev/null
+++ b/.github/workflows/engine-mac.yml
@@ -0,0 +1,30 @@
+name: Mac engine
+
+# Builds kokon-engine-mac and runs `swift test` (no model) on pull requests that touch engine-mac/.
+# GitHub's macOS runners are virtual machines: Metal is paravirtualized and the Neural Engine is likely missing, so
+# tests that need real hardware may fail or skip there; the maintainer's `swift test` on a Mac stays the reference.
+on:
+ pull_request:
+ paths: ["engine-mac/**", ".github/workflows/engine-mac.yml"]
+ push:
+ branches: [master]
+ paths: ["engine-mac/**", ".github/workflows/engine-mac.yml"]
+
+permissions:
+ contents: read
+
+jobs:
+ build-and-test:
+ # The engine uses the macOS 26 SDK (Metal 4, Apple10): it needs Xcode 26.
+ runs-on: macos-26
+ defaults:
+ run:
+ working-directory: engine-mac
+ steps:
+ - uses: actions/checkout@v4
+ - name: Toolchain
+ run: swift --version && xcodebuild -version
+ - name: Build
+ run: swift build -c release
+ - name: Test
+ run: swift test
diff --git a/AGENTS.md b/AGENTS.md
index 4c628ac..f43f5a1 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -41,6 +41,9 @@ Kokon app (Tauri 2 + React, src-tauri/ + src/) kokon-mcp (mcp/, stdio) scr
Module map and the measured facts behind each default: [docs/engineering-notes.md](docs/engineering-notes.md).
+Working on the Mac engine (`engine-mac/`): read [engine-mac/AGENTS.md](engine-mac/AGENTS.md) first: optimize for
+your own Mac without changing other chips, how to measure, and the report every engine PR carries.
+
## Build and test
Setup, prerequisites and the full commands are in [CONTRIBUTING.md](CONTRIBUTING.md). In short:
diff --git a/docs/STATUS.md b/docs/STATUS.md
index a928ed4..2d429a8 100644
--- a/docs/STATUS.md
+++ b/docs/STATUS.md
@@ -1,6 +1,6 @@
# Status
-**Updated 2026-10-26.** What is in progress, what comes next, and where help is welcome. Kept current at the end
+**Updated 2026-10-27.** What is in progress, what comes next, and where help is welcome. Kept current at the end
of every task (see [AGENTS.md](../AGENTS.md#keeping-docsstatusmd-current)); GitHub is the source of truth.
## Current version: [0.11.1](https://github.com/GabrieleLozupone/kokon/releases/tag/v0.11.1) (2026-10-26)
@@ -48,6 +48,8 @@ Windows, macOS (Apple Silicon, 15+) and Linux (`.deb`, `.rpm`). Installed copies
`bash engine-mac/tools/bench.sh` there, gives a report to paste in
[Discussion #43](https://github.com/GabrieleLozupone/kokon/discussions/43) (M1, M3, M4 and M5 Macs are the most
useful; see [engine-mac/README.md](../engine-mac/README.md#testing-on-your-mac-bench)).
+- Mac engine optimizations for your own Mac (the chip you develop on, nothing changed on the others): rules,
+ measuring and the pull request report in [engine-mac/AGENTS.md](../engine-mac/AGENTS.md).
- Model proposals that meet the switch rule: [Discussion #35](https://github.com/GabrieleLozupone/kokon/discussions/35).
## Recently shipped
diff --git a/engine-mac/AGENTS.md b/engine-mac/AGENTS.md
new file mode 100644
index 0000000..aa0dce9
--- /dev/null
+++ b/engine-mac/AGENTS.md
@@ -0,0 +1,170 @@
+# Working on the Mac engine (people and coding agents)
+
+Read this before changing anything in `engine-mac/`. It applies to you and to the agent you work with (Claude Code,
+Codex, Cursor…): give it this file. The root [AGENTS.md](../AGENTS.md) still applies; the engine itself is explained in
+[docs/mac-engine.md](docs/mac-engine.md) (start with chapters 7, 8, 13, 26–29) and measured in [README.md](README.md).
+
+## The rule in one line
+
+**Make the engine faster on the Mac you develop on, and change nothing on every other Mac.**
+
+The engine was tuned on one M2 Pro (16 GB). Every other chip runs paths that were never measured on it. Your Mac is
+the hardware you can measure, so a contribution is an optimization *for that chip*, chosen at run time from
+`Chip.current`, with everything else left exactly as it is.
+
+## What a change must look like
+
+1. **Gated by the chip.** Select the new path in `Chip.swift` or where the per-chip paths are chosen (see chapter 26),
+ by GPU family, generation, GPU cores or memory: the narrowest condition you measured. Do not widen it to chips you
+ have not run ("M4 Max" measured → not "Apple9+").
+2. **Behind a switch.** A `KOKON_*` variable that turns it off (and on, to compare). Add it to chapter 32 of the guide.
+3. **The current path as its fallback.** When the condition does not hold, or the path cannot run (compile error,
+ size it does not cover, memory), the engine takes the existing path. Never a crash, never a silent wrong image.
+4. **Listed in `bench`.** Add it to `Bench.swift`'s chip paths, so that its row with the path off appears in every
+ report, and others can confirm or refute it on their Macs.
+5. **A test that runs on any Mac.** In `Tests/KokonEngineTests/PerChipTests.swift`: the new path's result against the
+ existing path's on a small case, forced on even where the chip would not pick it (when it can run there). Plus a
+ test of the selection itself (which chip gets it, which does not).
+6. **One idea per pull request.** Two optimizations in one PR cannot be measured apart.
+
+Changing a default for *every* chip (a tile size, a share, a memory threshold) is a different kind of change: open an
+issue or post in [Discussion #43](https://github.com/GabrieleLozupone/kokon/discussions/43) first, because it needs
+measurements on several Macs.
+
+## What must not break
+
+- **Accuracy.** Measured against the reference, not against itself: `bench`'s accuracy rows (the engine's fp32 path on
+ the same Mac) and the `check-*` of the part you changed (fp64 oracle, chapter 28). The default path today is
+ ~6–7 · 10⁻⁴ on the velocity and 0.05–0.25 levels mean on the image. **A default path stays in the order of
+ 10⁻⁴ on the velocity** (below 1 · 10⁻³). Report the new path's error next to the default's, as a ratio. A path that
+ reaches 10⁻³ or more stays opt-in, however fast: int8 on the Neural Engine (1.1–4.1 · 10⁻²) is opt-in for that
+ reason. A path that multiplies the error for a small gain stays opt-in too: Neural Engine heads were ~1.5 % faster
+ for 2.5× the error.
+- **Seeds and API.** The same seed gives the same image as before up to that error; `/sdcpp/v1` keeps its requests and
+ answers; Prompt+, edits, brushed edits and references still work.
+- **Memory.** Peak footprint does not grow on a 16 GB Mac. If your Mac has more memory, say so and do not change what
+ happens below it.
+- **Everything outside `engine-mac/`.** Windows, Linux, sd.cpp and the app are untouched unless the change needs it;
+ if you touch `src/`, `src-tauri/` or `crates/`, run the root tests too.
+
+## The workflow
+
+```bash
+git checkout master && git pull
+git checkout -b mac-<chip>-<idea> # e.g. mac-m4max-attention-tiles
+cd engine-mac && swift build -c release && swift test
+
+# 1. the baseline, before any change
+bash tools/bench.sh # ~10 min: rename kokon-bench-report.md/.json to baseline-report.md/.json
+bash tools/ab.sh snapshot base
+
+# 2. find where the time goes on this Mac
+.build/release/kokon-engine-mac probe
+KOKON_PROFILE=1 .build/release/kokon-engine-mac time-dit <dit.gguf> 64 32
+
+# 3. change, build, check
+swift build -c release && swift test
+.build/release/kokon-engine-mac check-<the part you changed> ... # chapter 28: check-dit, check-generate, check-na…
+bash tools/ab.sh snapshot new
+
+# 4. measure, alternated
+bash tools/ab.sh run 3 "base|base|" "new|new|" -- time-dit <dit.gguf> 64 32
+bash tools/testset.sh 3 "base|base|" "new|new|" # the fixed test set, below
+bash tools/bench.sh # the final report, with the new path's off row
+python3 -I tools/compare_bench.py baseline-report.json kokon-bench-report.json # the PR's bench tables
+```
+
+**The fixed test set** (`tools/testset.sh`): the same prompts, sizes and seeds for everyone, so results compare across
+branches and Macs. Text to image at 1024², a wide image at 1344×768 (the engine was tuned at 1024² only), and an edit
+with a reference. A brushed edit is not in the command line: try one in the app with the branch's engine.
+
+**Before you start, read [chips.md](chips.md)**: what has been measured on each Mac. Add your Mac's row with the PR.
+
+How to measure so the numbers mean something:
+
+- **Alternated, at least 3 rounds, medians**, with the spread (min–max). One run against one run proves nothing: a
+ Mac's speed drifts with temperature, other apps and the file cache.
+- Plugged in, other apps closed, no `asitop`, no build while it runs. Start the A/B with the Mac cold or warm, the
+ same for both arms.
+- **A change is kept when its gain shows in every round, beyond the spread between runs.** Small gains count when
+ they are that steady: Metal 4 products (7.57 → 7.48 s per evaluation) and the packed attention (~1 %) were kept on
+ alternated rounds. A gain inside the spread is not a gain: report it, do not keep it.
+- Measure the whole image (`generate` or `bench`), not only the part you changed: a faster product can slow the units
+ beside it (chapter 13).
+- Nothing tuned on one prompt or one size: every case of the test set, not only the one that got faster.
+- **Say which Mac, not only which chip.** A MacBook Air has no fan and slows down when warm: on an Air a "gain" can be
+ the heat. There, run fewer rounds with a pause between them (a minute or two) and say so in the report.
+
+## For agents
+
+- **Ask the person before every run that uses the GPU** (`bench`, `ab.sh`, `generate`, `time-dit`, `probe`, `check-*`
+ with the model): it takes minutes and the Mac is unusable meanwhile. Give the exact command; run it in the
+ background and wait for it to finish, never in a loop of short polls.
+- **Never write a number you did not measure.** Every number in the PR comes from a run in this branch, with its
+ command. If a run failed or was skipped, the report says so.
+- Read the relevant chapter of [docs/mac-engine.md](docs/mac-engine.md) and **chapter 29 (Tried and not kept)** before
+ proposing an idea: many have been measured and dropped.
+- Keep the code like the code around it: Swift, comments that say *why* and on what it was measured
+ ("M4 Max 40-core, 64 GB, macOS 27, ab.sh 3 rounds: 7.1 → 6.6 s per evaluation").
+- `bench` writes a `.json` next to its report: build the PR's bench tables with `tools/compare_bench.py`, never by
+ copying numbers by hand. The `ab.sh` lines are pasted as they printed.
+- A negative result is a valid PR: add it to chapter 29 and to the README's notes, with its numbers, and change no code.
+
+## The pull request report
+
+Paste this in the PR description, filled in. Attach both bench reports, `.md` and `.json` (or paste them in a
+collapsed `<details>` block). The "Mac engine" check (GitHub Actions) builds the engine and runs `swift test` on every
+PR that touches `engine-mac/`; it runs in a virtual Mac, so your own `swift test` still counts.
+
+```markdown
+## Mac engine: <what, in one line>
+
+**Mac:** <chip, GPU cores, CPU cores, memory, macOS, model (MacBook Air / Pro, mini, Studio…): fan or not> · **Branch:** <name> · **Base:** master @ <commit>
+
+### Idea
+<Where the time went on this Mac (profile, probe), what the change does, why it should help this chip.>
+
+### Scope
+- Chosen when: <the exact condition in Chip / the selection code>
+- Switch: `KOKON_<NAME>` (<default on this chip>, `0` off)
+- Other chips: unchanged (<how you know: the condition, the selection test>)
+- Fallback: <what runs when it does not apply or fails>
+
+### Correctness
+| Check | Before | After |
+|---|---|---|
+| `swift test` | pass | pass (+ <new tests>) |
+| `check-<...>` | | |
+| bench: velocity error, 512² | | (× the default) |
+| bench: image, mean / max levels | | |
+
+### Speed: the test set (alternated, <n> rounds, median and min–max)
+| Case | base | new | change |
+|---|---|---|---|
+| `time-dit` per evaluation | | | |
+| 1. text to image 1024² | | | |
+| 2. wide 1344×768 | | | |
+| 3. edit with a reference | | | |
+| peak footprint | | | |
+| brushed edit in the app | | | works / not tried |
+
+<details><summary>ab.sh and testset.sh output</summary>
+
+ <pasted as printed>
+</details>
+
+### Bench (tools/compare_bench.py)
+<its output>
+
+### Not done / risks
+<What you did not measure (edits, other sizes, memory sizes), what could behave differently on other chips,
+anything you tried and dropped.>
+
+### Docs
+- [ ] docs/mac-engine.md chapter 26 (per-chip paths) and 32 (switches)
+- [ ] README.md "Per-chip paths" with the numbers
+- [ ] chapter 29 for what was tried and not kept
+- [ ] chips.md: your Mac's row
+```
+
+The maintainer reruns `bench` on the M2 Pro before merging, to confirm nothing changed there.
diff --git a/engine-mac/CLAUDE.md b/engine-mac/CLAUDE.md
new file mode 100644
index 0000000..43c994c
--- /dev/null
+++ b/engine-mac/CLAUDE.md
@@ -0,0 +1 @@
diff --git a/engine-mac/README.md b/engine-mac/README.md
index 2653544..8708452 100644
--- a/engine-mac/README.md
+++ b/engine-mac/README.md
@@ -24,6 +24,8 @@ swift test # no model needed
.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
bash tools/ab.sh snapshot base; bash tools/ab.sh run 2 "base|base|X=1" "new|new|X=1" -- time-dit <dit.gguf> 64 32
+bash tools/testset.sh 3 "base|base|" "new|new|" # the fixed test set of an engine PR (see AGENTS.md)
+python3 -I tools/compare_bench.py baseline-report.json kokon-bench-report.json # two bench reports → PR tables
# alternated A/B of build snapshots and settings (steps, page-ins)
```
diff --git a/engine-mac/Sources/KokonEngine/AttentionProbe.swift b/engine-mac/Sources/KokonEngine/AttentionProbe.swift
index 611e8d1..25b5470 100644
--- a/engine-mac/Sources/KokonEngine/AttentionProbe.swift
+++ b/engine-mac/Sources/KokonEngine/AttentionProbe.swift
@@ -93,8 +93,11 @@ extension Probe {
return try MetalContext.finish(commands, "flash")
}
let gpuError = error { i, c in f(ob)[(offset + i) * stride + c] }
- print(String(format: "GPU %@%@, 32 heads: %.1f ms, %.2f ms/head, %.2f TFLOP/s; head 0 rel %.1e", kernel, packed ? " (with packing)" : "",
- gpu * 1e3, gpu * 1e3 / Double(heads), 4 * Double(queries) * Double(keys) * Double(d) * Double(heads) / gpu / 1e12, gpuError))
+ // In parts: Xcode 26's compiler times out on the whole expression.
+ let flops: Double = 4 * Double(queries) * Double(keys) * Double(d) * Double(heads)
+ let note = packed ? " (with packing)" : ""
+ print(String(format: "GPU %@%@, 32 heads: %.1f ms, %.2f ms/head, %.2f TFLOP/s; head 0 rel %.1e", kernel, note,
+ gpu * 1e3, gpu * 1e3 / Double(heads), flops / gpu / 1e12, gpuError))
}
if ProcessInfo.processInfo.environment["KOKON_PROBE_GPU_ONLY"] == "1" { return }
diff --git a/engine-mac/Sources/KokonEngine/Bench.swift b/engine-mac/Sources/KokonEngine/Bench.swift
index 7f740dd..b5b5922 100644
--- a/engine-mac/Sources/KokonEngine/Bench.swift
+++ b/engine-mac/Sources/KokonEngine/Bench.swift
@@ -104,7 +104,17 @@ public enum Bench {
print("\n" + report)
if let out {
try report.write(toFile: out, atomically: true, encoding: .utf8)
- print("(written to \(out))")
+ // The same numbers for tools/compare_bench.py, which writes a pull request's tables from two reports.
+ let json = (out as NSString).deletingPathExtension + ".json"
+ let summary = Bench.summary(chip: chip, paths: paths, reference: reference, rows: rows, quick: quick)
+ // Never fails the bench: the report above is what testers and the app need.
+ if JSONSerialization.isValidJSONObject(summary),
+ let data = try? JSONSerialization.data(withJSONObject: summary, options: [.prettyPrinted, .sortedKeys]),
+ (try? data.write(to: URL(fileURLWithPath: json))) != nil {
+ print("(written to \(out) and \(json))")
+ } else {
+ print("(written to \(out); \(json) could not be written)")
+ }
}
}
@@ -116,7 +126,7 @@ public enum 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)",
+ "- Mac \(chip.model), 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 ?? "?")",
"",
@@ -149,6 +159,27 @@ public enum Bench {
return lines.joined(separator: "\n")
}
+ /// The report's numbers as JSON: the Mac, the paths, and per run its times, peak memory and accuracy (the files
+ /// the children wrote are read here, before they are deleted).
+ static func summary(chip: Chip, paths: [(String, String, String)], reference: [String: Any], rows: [[String: Any]],
+ quick: Bool) -> [String: Any] {
+ let runs: [[String: Any]] = rows.map { row in
+ var run = row.filter { ["name", "image1", "image2", "step", "vae", "peak", "parts", "shares"].contains($0.key) }
+ if let a = reference["velocity"] as? String, let b = row["velocity"] as? String, let e = Bench.relativeError(b, a), e.isFinite {
+ run["velocityError"] = e
+ }
+ if let a = reference["image"] as? String, let b = row["image"] as? String, let d = Bench.levels(b, a) {
+ run["imageMeanLevels"] = d.mean
+ run["imageMaxLevels"] = d.max
+ }
+ return run
+ }
+ return ["chip": chip.name, "model": chip.model, "gpuCores": chip.gpuCores, "gpuFamily": chip.gpuFamily,
+ "performanceCores": chip.performanceCores, "efficiencyCores": chip.efficiencyCores,
+ "memoryGB": Int(chip.memoryGB.rounded()), "macOS": chip.macOS, "engine": EngineVersion.string,
+ "paths": paths.map(\.0), "quick": quick, "runs": runs]
+ }
+
/// ‖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)),
diff --git a/engine-mac/Sources/KokonEngine/Chip.swift b/engine-mac/Sources/KokonEngine/Chip.swift
index c8ded3a..e2e534a 100644
--- a/engine-mac/Sources/KokonEngine/Chip.swift
+++ b/engine-mac/Sources/KokonEngine/Chip.swift
@@ -7,6 +7,9 @@ import Metal
public struct Chip: Sendable, CustomStringConvertible {
/// `machdep.cpu.brand_string`, e.g. "Apple M2 Pro".
public let name: String
+ /// `hw.model`, e.g. "Mac14,12": tells a fanless MacBook Air from a Mac mini with the same chip, which matters
+ /// for timings (the Air slows down when warm).
+ public let model: String
/// 1 for M1 … 5 for M5, from the name; nil for a name the engine does not know (a newer chip: treated as the
/// newest known one where a path depends on it).
public let generation: Int?
@@ -32,6 +35,7 @@ public struct Chip: Sendable, CustomStringConvertible {
return sysctlbyname(key, &value, &size, nil, 0) == 0 ? Int(value) : 0
}
name = sysctl("machdep.cpu.brand_string")
+ model = sysctl("hw.model")
generation = Chip.generation(of: name)
performanceCores = number("hw.perflevel0.physicalcpu")
efficiencyCores = number("hw.perflevel1.physicalcpu")
diff --git a/engine-mac/Sources/KokonEngine/QwenPipeline.swift b/engine-mac/Sources/KokonEngine/QwenPipeline.swift
index 8b9df54..8eda5f8 100644
--- a/engine-mac/Sources/KokonEngine/QwenPipeline.swift
+++ b/engine-mac/Sources/KokonEngine/QwenPipeline.swift
@@ -428,8 +428,10 @@ public final class QwenPipeline {
return (out, w, h)
}
let rgba = try decodeImage(data)
- let gray = (0..<(rgba.width * rgba.height)).map { p in
- UInt8((77 * Int(rgba.rgba[p * 4]) + 150 * Int(rgba.rgba[p * 4 + 1]) + 29 * Int(rgba.rgba[p * 4 + 2])) >> 8)
+ let gray = (0..<(rgba.width * rgba.height)).map { p -> UInt8 in
+ // In parts: Xcode 26's compiler times out on the whole expression.
+ let r: Int = 77 * Int(rgba.rgba[p * 4]), g: Int = 150 * Int(rgba.rgba[p * 4 + 1]), b: Int = 29 * Int(rgba.rgba[p * 4 + 2])
+ return UInt8((r + g + b) >> 8)
}
return (gray, rgba.width, rgba.height)
}
diff --git a/engine-mac/Tests/KokonEngineTests/BenchReportTests.swift b/engine-mac/Tests/KokonEngineTests/BenchReportTests.swift
index a8615f9..402e1a1 100644
--- a/engine-mac/Tests/KokonEngineTests/BenchReportTests.swift
+++ b/engine-mac/Tests/KokonEngineTests/BenchReportTests.swift
@@ -12,4 +12,16 @@ final class BenchReportTests: XCTestCase {
XCTAssertTrue(report.contains("| default (paths above) | 1 | 2.50 | 0.40 | 9.10 | 50.0 | 4.30 | 63.7 |"), report)
XCTAssertTrue(report.contains("| default (paths above) | 2 | 2.50 | 0.40 | 9.10 | 50.0 | 4.30 | 72.1 |"), report)
}
+
+ func testSummaryCarriesTheNumbers() throws {
+ let row: [String: Any] = ["name": "default (paths above)", "image1": 63.7, "step": 7.15, "vae": 4.31, "peak": 8.5,
+ "velocity": "/nonexistent-velocity.f32"]
+ let summary = Bench.summary(chip: Chip.current, paths: [], reference: [:], rows: [row], quick: true)
+ XCTAssertTrue(JSONSerialization.isValidJSONObject(summary))
+ let run = try XCTUnwrap((summary["runs"] as? [[String: Any]])?.first)
+ XCTAssertEqual(run["image1"] as? Double, 63.7)
+ XCTAssertNil(run["velocity"], "the children's file paths stay out")
+ XCTAssertNil(run["velocityError"], "no reference, no error")
+ XCTAssertEqual(summary["model"] as? String, Chip.current.model)
+ }
}
diff --git a/engine-mac/Tests/KokonEngineTests/PerChipTests.swift b/engine-mac/Tests/KokonEngineTests/PerChipTests.swift
index df1dcca..c23b9bb 100644
--- a/engine-mac/Tests/KokonEngineTests/PerChipTests.swift
+++ b/engine-mac/Tests/KokonEngineTests/PerChipTests.swift
@@ -47,8 +47,11 @@ final class PerChipTests: XCTestCase {
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)
+ // A virtual Mac (GitHub's runners) has a paravirtual GPU that reports no Apple family.
+ if MTLCreateSystemDefaultDevice()?.name.contains("Paravirtual") != true {
+ XCTAssertGreaterThan(here.gpuFamily, 6)
+ }
}
/// The first evaluation's shares from the cost model: on any chip they add up and keep each unit in its range.
diff --git a/engine-mac/chips.md b/engine-mac/chips.md
new file mode 100644
index 0000000..b543daa
--- /dev/null
+++ b/engine-mac/chips.md
@@ -0,0 +1,18 @@
+# Macs measured
+
+One row per Mac the engine has been measured on: what it selects, how fast and how exact. Add yours with your pull
+request or bench report ([engine-mac/AGENTS.md](AGENTS.md)); every number links to where it comes from.
+
+Before working on a chip, look here and in [docs/mac-engine.md](docs/mac-engine.md) chapter 29 (tried and not kept).
+
+| 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 |
+
+## Per-chip notes
+
+### M2 Pro, 19-core GPU, 16 GB
+
+- 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.
diff --git a/engine-mac/docs/mac-engine.md b/engine-mac/docs/mac-engine.md
index 5ae2ac5..437c341 100644
--- a/engine-mac/docs/mac-engine.md
+++ b/engine-mac/docs/mac-engine.md
@@ -1303,6 +1303,8 @@ A row with a path off that is faster than the default means that path should not
| `time-dit <dit> 64 32` | DiT evaluations at 1024² with 32 text rows, plus the timeline per operation and the time between operations |
| `time-vae`, `time-matvec` | the VAE's time and memory; the decode's products in GB/s |
| `tools/ab.sh` | **alternated A/B** of build snapshots and settings: `ab.sh snapshot base`, then `ab.sh run 2 "base\|base\|X=1" "new\|new\|X=1" -- time-dit …` |
+| `tools/testset.sh` | the fixed test set of an engine pull request through `ab.sh`: 1024², 1344×768 and an edit, same prompts and seeds for everyone |
+| `tools/compare_bench.py` | two `bench` reports (the `.json` written next to each) → the before/after tables of a pull request |
Why alternated: a Mac's speed drifts with temperature, other apps and page cache. Running A, B, A, B… in rounds and
comparing medians is the only way a 1 % change can be trusted. Every "kept" change in this guide was decided that way.
diff --git a/engine-mac/tools/compare_bench.py b/engine-mac/tools/compare_bench.py
new file mode 100644
index 0000000..8286996
--- /dev/null
+++ b/engine-mac/tools/compare_bench.py
@@ -0,0 +1,88 @@
+#!/usr/bin/env python3
+"""The tables of a Mac engine pull request, from two bench reports of the same Mac: the baseline (master) and the
+branch. `bench --out X.md` (and tools/bench.sh) writes X.json next to the report; pass those two files.
+
+ python3 -I tools/compare_bench.py baseline-report.json kokon-bench-report.json > tables.md
+
+Prints markdown: the Mac, then per run (default and each path off) the times, peak memory and accuracy, before and
+after, with the change. The velocity error is also given as a ratio to the baseline default's, the number the
+review looks at (engine-mac/AGENTS.md: a default path stays in the order of 1e-4). Standard library only.
+"""
+import json, sys
+
+
+def load(path):
+ with open(path) as f:
+ return json.load(f)
+
+
+def mac(r):
+ return (f"{r.get('chip', '?')} ({r.get('model', '?')}), {r.get('gpuCores', '?')} GPU cores (Apple{r.get('gpuFamily', '?')}), "
+ f"{r.get('performanceCores', '?')}+{r.get('efficiencyCores', '?')} CPU cores, {r.get('memoryGB', '?')} GB, "
+ f"macOS {r.get('macOS', '?')}")
+
+
+def change(a, b):
+ # No verdict mark: one run per side cannot say whether a change is real.
+ if a is None or b is None or a == 0:
+ return "–"
+ return f"{(b - a) / a * 100:+.1f} %"
+
+
+def fmt(v, f):
+ return "–" if v is None else f.format(v)
+
+
+def main():
+ if len(sys.argv) != 3:
+ sys.exit(__doc__)
+ base, new = load(sys.argv[1]), load(sys.argv[2])
+ out = []
+ out.append(f"**Mac:** {mac(new)}")
+ if mac(base) != mac(new):
+ out.append(f"\n⚠️ The baseline ran on a different Mac or macOS: {mac(base)}. The two reports cannot be compared.")
+ if base.get("quick") != new.get("quick"):
+ out.append("\n⚠️ One report is --quick and the other is not: image 2 is missing from one side.")
+ out.append(f"\nBaseline engine: {base.get('engine', '?')} \nBranch engine: {new.get('engine', '?')}")
+ out.append(f"\nPaths selected on the branch: {'; '.join(new.get('paths', [])) or 'none chip-specific'}")
+ if base.get("paths") != new.get("paths"):
+ out.append(f"(baseline: {'; '.join(base.get('paths', [])) or 'none chip-specific'})")
+
+ base_runs = {r["name"]: r for r in base.get("runs", [])}
+ new_runs = {r["name"]: r for r in new.get("runs", [])}
+ default = next(iter(base.get("runs", [])), {})
+ ref_error = default.get("velocityError")
+
+ out.append("\n### Speed at 1024² (bench)\n")
+ out.append("| Run | Measure | Baseline | Branch | Change |")
+ out.append("|---|---|---|---|---|")
+ for name, n in new_runs.items():
+ b = base_runs.get(name, {})
+ for key, label, f in [("image1", "image 1", "{:.1f} s"), ("image2", "image 2", "{:.1f} s"),
+ ("step", "step (2–8)", "{:.2f} s"), ("vae", "VAE", "{:.2f} s"), ("peak", "peak memory", "{:.1f} GB")]:
+ if key in n or key in b:
+ out.append(f"| {name} | {label} | {fmt(b.get(key), f)} | {fmt(n.get(key), f)} | {change(b.get(key), n.get(key))} |")
+
+ out.append("\n### Accuracy at 512² against the fp32 path (bench)\n")
+ out.append("| Run | Velocity error: baseline | branch | × baseline default | Image levels (mean / max): baseline | branch |")
+ out.append("|---|---|---|---|---|---|")
+ for name, n in new_runs.items():
+ b = base_runs.get(name, {})
+ e = n.get("velocityError")
+ ratio = "–" if e is None or not ref_error else f"{e / ref_error:.2f}×"
+ warn = " ⚠️ ≥ 1e-3" if e is not None and e >= 1e-3 else ""
+
+ def levels(r):
+ return "–" if r.get("imageMeanLevels") is None else f"{r['imageMeanLevels']:.2f} / {r['imageMaxLevels']}"
+ out.append(f"| {name} | {fmt(b.get('velocityError'), '{:.1e}')} | {fmt(e, '{:.1e}')}{warn} | {ratio} | "
+ f"{levels(b)} | {levels(n)} |")
+
+ missing = [name for name in base_runs if name not in new_runs]
+ if missing:
+ out.append(f"\nRuns only in the baseline: {', '.join(missing)}")
+ out.append("\nOne bench run per side: confirm speed changes with tools/ab.sh (alternated rounds) before trusting them.")
+ print("\n".join(out))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/engine-mac/tools/testset.sh b/engine-mac/tools/testset.sh
new file mode 100644
index 0000000..b7ce55b
--- /dev/null
+++ b/engine-mac/tools/testset.sh
@@ -0,0 +1,52 @@
+#!/bin/bash
+# The fixed test set of a Mac engine pull request (engine-mac/AGENTS.md): the same prompts, sizes and seeds for
+# everyone, run alternated through tools/ab.sh, so results from different branches and Macs can be compared.
+#
+# bash tools/ab.sh snapshot base # on master; then on the branch: swift build -c release; bash tools/ab.sh snapshot new
+# bash tools/testset.sh 3 "base|base|" "new|new|"
+#
+# The cases: text to image at 1024², a wide image (1344×768: not tuned so far), an edit with a reference image (made
+# once by the first arm and kept in $AB_DIR/testset). A brushed edit (mask) is not in the command line: try one in the
+# app with the branch's engine and say so in the report. Model files: Kokon's (KOKON_MODELS to point elsewhere).
+# Minutes per run and per arm: plugged in, other apps closed, no build while it runs.
+set -euo pipefail
+here="$(cd "$(dirname "$0")" && pwd)"
+dir="${AB_DIR:-$HOME/kokon-bench/ab}"
+models="${KOKON_MODELS:-$HOME/Library/Application Support/KokonData/sdcpp/models/qwen21}"
+[ $# -ge 2 ] || { sed -n 2,11p "$0"; exit 1; }
+rounds="$1"; shift
+arms=("$@")
+
+first() { for f in "$@"; do [ -f "$models/$f" ] && { echo "$models/$f"; return; }; done; echo "$models/$1"; }
+enc="$(first Qwen3VL-8B-Instruct-Q4_K_M.gguf)"
+dit="$(first qwen-image-2.1-turbo-Q4_K_M.gguf qwen-image-2.1-turbo-Q4_K.gguf)"
+vae="$(first texture_fix_vae_for_qwen_image_2.1_bf16.safetensors qwen_image_2.1_vae_bf16.safetensors)"
+mmproj="$(first mmproj-Qwen3VL-8B-Instruct-F16.gguf)"
+for f in "$enc" "$dit" "$vae" "$mmproj"; do
+ [ -f "$f" ] || { echo "$f not found: set up Kokon's models once, or set KOKON_MODELS"; exit 1; }
+done
+
+work="$dir/testset"
+mkdir -p "$work"
+ref="$work/reference.png"
+if [ ! -f "$ref" ]; then
+ IFS='|' read -r _ snapshot _ <<< "${arms[0]}"
+ echo "== the edit's reference image (once, with $snapshot)"
+ "$dir/$snapshot/kokon-engine-mac" generate "$enc" "$dit" "$vae" \
+ "A cozy wooden cabin by a lake in autumn, a red canoe on the shore, afternoon light, photo" \
+ --size 1024x768 --seed 7 --out "$ref" > /dev/null
+fi
+
+echo "== 1. text to image, 1024x1024"
+bash "$here/ab.sh" run "$rounds" "${arms[@]}" -- generate "$enc" "$dit" "$vae" \
+ "A red fox in fresh snow at dawn, a wooden sign that says KOKON, soft golden light, photo" \
+ --size 1024x1024 --seed 42 --out "$work/t2i.png"
+echo "== 2. wide image, 1344x768"
+bash "$here/ab.sh" run "$rounds" "${arms[@]}" -- generate "$enc" "$dit" "$vae" \
+ "A narrow street at night after the rain, a yellow tram, a neon sign that says CAFE, reflections, photo" \
+ --size 1344x768 --seed 42 --out "$work/wide.png"
+echo "== 3. edit with a reference"
+bash "$here/ab.sh" run "$rounds" "${arms[@]}" -- generate "$enc" "$dit" "$vae" \
+ "Make it a winter evening with falling snow, keep the cabin, the lake and the canoe" \
+ --ref "$ref" --mmproj "$mmproj" --seed 42 --out "$work/edit.png"
+echo "Images of the last arm in $work. A brushed edit: try one in the app and note it in the report."