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: read the models back into the file cache after each image (below 32 GB)

Gabriele Lozuponece9185fb0708
diff --git a/docs/STATUS.md b/docs/STATUS.md
index 6ac01c1..67964b0 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 min) and gives the report to paste in
+ bench from the app (10–15 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 a907b02..350954a 100644
--- a/engine-mac/README.md
+++ b/engine-mac/README.md
@@ -433,21 +433,21 @@ 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 min; the
+In Kokon: Settings → Performance, turn on Kokon's Mac engine and save, then **Benchmark this Mac → Run** (10–15 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 min; --quick: one image per run
+bash engine-mac/tools/bench.sh # 10–15 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
+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). Paste it in
+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
[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.
diff --git a/engine-mac/Sources/KokonEngine/Bench.swift b/engine-mac/Sources/KokonEngine/Bench.swift
index e04fd33..d6799c5 100644
--- a/engine-mac/Sources/KokonEngine/Bench.swift
+++ b/engine-mac/Sources/KokonEngine/Bench.swift
@@ -34,6 +34,9 @@ public enum Bench {
return paths
}
+ /// Seconds between image 1 and image 2.
+ static let pause = 10.0
+
/// 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"]
@@ -52,6 +55,10 @@ 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])) }
@@ -140,7 +147,8 @@ 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 (below 32 GB the app loads the models again for every image, so image 2 does too). Accuracy at 512² against the engine's fp32 GPU path"
+ + "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"
+ (quick ? "; --quick: one image per run." : ".")]
return lines.joined(separator: "\n")
}
@@ -196,6 +204,8 @@ 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).
+ 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
images.append(t["total"] ?? .nan)
diff --git a/engine-mac/Sources/KokonEngine/Prefetch.swift b/engine-mac/Sources/KokonEngine/Prefetch.swift
new file mode 100644
index 0000000..8a09347
--- /dev/null
+++ b/engine-mac/Sources/KokonEngine/Prefetch.swift
@@ -0,0 +1,48 @@
+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 8b9df54..0d4d2ed 100644
--- a/engine-mac/Sources/KokonEngine/QwenPipeline.swift
+++ b/engine-mac/Sources/KokonEngine/QwenPipeline.swift
@@ -295,6 +295,11 @@ 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
new file mode 100644
index 0000000..bb64cfe
--- /dev/null
+++ b/engine-mac/Tests/KokonEngineTests/PrefetchTests.swift
@@ -0,0 +1,17 @@
+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 b517a2c..b651e70 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 about 10 minutes and
+ 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
uses the whole Mac: close other apps and keep it plugged in. Images can't be made while it runs.
</span>
</div>