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: prefetch after each image measured, not kept

Gabriele Lozupone49f9f207a1a8
diff --git a/docs/STATUS.md b/docs/STATUS.md
index 67964b0..6ac01c1 100644
--- a/docs/STATUS.md
+++ b/docs/STATUS.md
@@ -30,7 +30,7 @@ Windows, macOS (Apple Silicon, 15+) and Linux (`.deb`, `.rpm`). Installed copies
as an experimental switch in Settings → Performance (off by default). Since then (2026-10-26, not yet re-measured as
whole images): one denoising step ~5 % faster, the decoder ~1 s faster per image, an edit's image reading 2.6 → 1.7 s. LoRAs and the upscaler still need the standard
engine (not planned for its first release). A "Benchmark this Mac" button in Settings → Performance runs the engine's
- bench from the app (10–15 min) and gives the report to paste in
+ bench from the app (~10 min) and gives the report to paste in
[Discussion #43](https://github.com/GabrieleLozupone/kokon/discussions/43).
- 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.
diff --git a/engine-mac/README.md b/engine-mac/README.md
index 350954a..a345689 100644
--- a/engine-mac/README.md
+++ b/engine-mac/README.md
@@ -433,26 +433,33 @@ correctness test that runs on any Mac (`PerChipTests`). Only the M2 Pro has meas
## 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).
-In Kokon: Settings → Performance, turn on Kokon's Mac engine and save, then **Benchmark this Mac → Run** (10–15 min; the
+In Kokon: Settings → Performance, turn on Kokon's Mac engine and save, then **Benchmark this Mac → Run** (~10 min; the
server is stopped while it runs and images wait). It runs the same `bench` on the app's engine and model files, shows
the step it is on, and gives the report with Copy report and a link to
[Discussion #43](https://github.com/GabrieleLozupone/kokon/discussions/43). From the source:
```bash
git clone https://github.com/GabrieleLozupone/kokon.git && cd kokon && git checkout macos-optimization
-bash engine-mac/tools/bench.sh # 10–15 min; --quick: one image per run
+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, 10 s after image 1; each split into text encoder, DiT load, step 1, steps 2–8 and VAE), 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; below 32 GB, with `KOKON_PREFETCH=0`: the models not read back into the file cache after an image). Paste it in
+levels), then the same with each chip-specific path off (and the int8 path on, on M3 and later). Paste it in
[Discussion #43](https://github.com/GabrieleLozupone/kokon/discussions/43). 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
+**Reading the models back into the file cache after each image (prefetch): measured, not kept** (M2 Pro 16 GB,
+Benchmark button, 2026-10-26; commit ce9185f). Below 32 GB a second image takes 3–7 s more than the first, with the steps
+unchanged: text encoder ~2 s, step 1 0.5–3 s, VAE 0.3–0.8 s. Tried: after the decode, the files not kept (encoder, DiT,
+VAE, ~10 GB) read on a utility thread, 10 s before the next image. Image 2's text encoder 4.24 → 3.93–4.00 s only, step 1
+8.68 → 9.84–11.00 s and VAE 3.54 → 3.98–4.25 s: on 16 GB the files do not all fit with the engine's own memory, so the
+later files push out the earlier ones and the engine's memory. Where image 2's extra time goes is not measured yet.
+
**The Neural Engine on its own rows through the layer while the GPU attends (lanes): measured, not kept** (M2 Pro,
2026-10-26; patch in `~/kokon-bench/patches/lanes-2026-10-26.patch`). In the joint split the Neural Engine idles through
each layer's attention (~66 ms of ~230 at 1024²). Tried: the Neural Engine takes the target's last r rows through every
diff --git a/engine-mac/Sources/KokonEngine/Bench.swift b/engine-mac/Sources/KokonEngine/Bench.swift
index d6799c5..7f740dd 100644
--- a/engine-mac/Sources/KokonEngine/Bench.swift
+++ b/engine-mac/Sources/KokonEngine/Bench.swift
@@ -55,10 +55,6 @@ public enum Bench {
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])) }
- // Below 32 GB the models are read back into the file cache after each image (`Prefetch`): its gain on image 2.
- if chip.memoryGB < 30, Prefetch.enabled {
- runs.append(Run(name: "KOKON_PREFETCH=0", environment: ["KOKON_PREFETCH": "0"]))
- }
// 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])) }
@@ -148,7 +144,7 @@ public enum Bench {
}
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, \(Int(Bench.pause)) s after image 1 (below 32 GB the models are loaded again for "
- + "every image, read back into the file cache meanwhile unless KOKON_PREFETCH=0). Accuracy at 512² against the engine's fp32 GPU path"
+ + "every image). Accuracy at 512² against the engine's fp32 GPU path"
+ (quick ? "; --quick: one image per run." : ".")]
return lines.joined(separator: "\n")
}
@@ -204,7 +200,7 @@ public enum Bench {
} else {
var images: [Double] = [], steps: [Double] = [], vae = 0.0, parts: [[String: Double]] = []
for i in 0..<(quick ? 1 : 2) {
- // Image 2 after a pause, like someone looking at image 1 (the time `Prefetch` reads the models in).
+ // Image 2 after a pause, like someone looking at image 1.
if i > 0 { Thread.sleep(forTimeInterval: Bench.pause) }
_ = try pipeline.textToImage(prompt: Bench.prompt, width: 1024, height: 1024, seed: 42 + UInt64(i))
let t = pipeline.timings
diff --git a/engine-mac/Sources/KokonEngine/Prefetch.swift b/engine-mac/Sources/KokonEngine/Prefetch.swift
deleted file mode 100644
index 8a09347..0000000
--- a/engine-mac/Sources/KokonEngine/Prefetch.swift
+++ /dev/null
@@ -1,48 +0,0 @@
-import Foundation
-
-/// **Reads the model files back into macOS's file cache after an image**, in the background, while the user looks at
-/// it. Below 32 GB the models are not kept between images and the VAE decode's peak (8.6–8.9 GB) pushes their pages
-/// out: the next image read them from the SSD while the user waited. M2 Pro 16 GB, Benchmark button 2026-10-26,
-/// image 2 against image 1: text encoder +2.5–3.3 s, step 1 +0.5–2.1 s, VAE +0.3–0.7 s; steps 2–8 the same.
-///
-/// The pages are file cache (shared with the models' read-only mappings), not wired memory: macOS takes them back
-/// when another app needs them, and the worst case is a few GB read for nothing. `KOKON_PREFETCH=0` turns it off.
-public enum Prefetch {
- public static var enabled: Bool { ProcessInfo.processInfo.environment["KOKON_PREFETCH"] != "0" }
-
- /// Bumped by every `files` call: a newer prefetch stops an older one.
- private static let generation = Counter()
-
- /// Reads `paths` in order (the first one the next image needs first), on a background thread.
- public static func files(_ paths: [String]) {
- let mine = generation.increment()
- Thread.detachNewThread {
- Thread.current.qualityOfService = .utility
- let chunk = 16 << 20
- let buffer = UnsafeMutableRawPointer.allocate(byteCount: chunk, alignment: 16_384)
- defer { buffer.deallocate() }
- for path in paths {
- let fd = open(path, O_RDONLY)
- guard fd >= 0 else { continue }
- defer { close(fd) }
- var offset: off_t = 0
- while generation.value == mine {
- let n = pread(fd, buffer, chunk, offset)
- if n <= 0 { break }
- offset += off_t(n)
- }
- }
- }
- }
-
- /// Stops the prefetch running now.
- public static func cancel() { _ = generation.increment() }
-}
-
-/// A counter shared between threads.
-final class Counter: @unchecked Sendable {
- private var count = 0
- private let lock = NSLock()
- var value: Int { lock.lock(); defer { lock.unlock() }; return count }
- func increment() -> Int { lock.lock(); defer { lock.unlock() }; count += 1; return count }
-}
diff --git a/engine-mac/Sources/KokonEngine/QwenPipeline.swift b/engine-mac/Sources/KokonEngine/QwenPipeline.swift
index 0d4d2ed..8b9df54 100644
--- a/engine-mac/Sources/KokonEngine/QwenPipeline.swift
+++ b/engine-mac/Sources/KokonEngine/QwenPipeline.swift
@@ -295,11 +295,6 @@ public final class QwenPipeline {
timings["vae"] = since(t)
timings["total"] = since(started)
log(String(format: "VAE: %.2f s; total %.1f s", timings["vae"]!, timings["total"]!))
- // The server's next image: the models that were not kept go back into the file cache meanwhile (`Prefetch`).
- if keepModels, Prefetch.enabled {
- let dropped = [(encoderPath, keepEncoder), (ditPath, keepDiT), (vaePath, keepVAE)].filter { !$0.1 }.map(\.0)
- if !dropped.isEmpty { Prefetch.files(dropped) }
- }
return image
}
diff --git a/engine-mac/Tests/KokonEngineTests/PrefetchTests.swift b/engine-mac/Tests/KokonEngineTests/PrefetchTests.swift
deleted file mode 100644
index bb64cfe..0000000
--- a/engine-mac/Tests/KokonEngineTests/PrefetchTests.swift
+++ /dev/null
@@ -1,17 +0,0 @@
-import XCTest
-@testable import KokonEngine
-
-/// `Prefetch` reads files in the background and a newer call stops an older one; a missing file is skipped.
-final class PrefetchTests: XCTestCase {
- func testReadsAndStops() throws {
- let dir = FileManager.default.temporaryDirectory.appendingPathComponent("kokon-prefetch-\(UUID())")
- try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
- defer { try? FileManager.default.removeItem(at: dir) }
- let file = dir.appendingPathComponent("model.bin")
- try Data(count: 40 << 20).write(to: file)
- Prefetch.files([dir.appendingPathComponent("missing").path, file.path])
- Prefetch.files([file.path])
- Prefetch.cancel()
- Thread.sleep(forTimeInterval: 0.2) // the threads end on their own; nothing to wait for but no crash
- }
-}
diff --git a/src/components/Settings.tsx b/src/components/Settings.tsx
index b651e70..b517a2c 100644
--- a/src/components/Settings.tsx
+++ b/src/components/Settings.tsx
@@ -163,7 +163,7 @@ function MacBench({ blocked }: { blocked: string | null }) {
<div className="setting-card-text">
<strong>Benchmark this Mac</strong>
<span className="muted">
- Measures Kokon's Mac engine on this Mac: speed, memory and accuracy, with each chip-specific path on and off. It takes 10 to 15 minutes and
+ Measures Kokon's Mac engine on this Mac: speed, memory and accuracy, with each chip-specific path on and off. It takes about 10 minutes and
uses the whole Mac: close other apps and keep it plugged in. Images can't be made while it runs.
</span>
</div>