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: brushed edits and extending an image (init image, mask, strength)

Gabriele Lozupone1320a5aaa0da
diff --git a/crates/qls-core/src/sdcpp.rs b/crates/qls-core/src/sdcpp.rs
index f53f081..0d04520 100644
--- a/crates/qls-core/src/sdcpp.rs
+++ b/crates/qls-core/src/sdcpp.rs
@@ -220,12 +220,14 @@ impl Capabilities {
self.engine == crate::config::MAC_ENGINE_EXE
}
/// What in `req` Kokon's Mac engine cannot do yet, in the user's words; None when it can, and always for
- /// sd-server. It edits with reference images when it has the vision projector (`ref_images` in its features), but
- /// has no init image or mask yet (brushed edits, extending an image).
+ /// sd-server. It edits with reference images when it has the vision projector (`ref_images` in its features), and
+ /// takes an init image and a mask (brushed edits, extending an image) from the build that advertises them.
pub fn mac_engine_unsupported(&self, req: &ImgGenRequest) -> Option<&'static str> {
if !self.is_mac_engine() {
None
- } else if req.init_image.is_some() || req.mask_image.is_some() {
+ } else if (req.init_image.is_some() && !self.img_feature("init_image"))
+ || (req.mask_image.is_some() && !self.img_feature("mask_image"))
+ {
Some("edits of a brushed area or extending images")
} else if !req.ref_images.is_empty() && !self.img_feature("ref_images") {
Some("edits")
@@ -916,11 +918,18 @@ mod tests {
assert_eq!(caps.mac_engine_unsupported(&edit), Some("edits"), "no vision projector");
let inpaint = ImgGenRequest { mask_image: Some("png".into()), ..t2i.clone() };
assert_eq!(caps.mac_engine_unsupported(&inpaint), Some("edits of a brushed area or extending images"));
- // Started with --llm_vision: edits with references run, a mask still does not.
+ // Started with --llm_vision: edits with references run; a mask only on a build that advertises it.
let vision: Capabilities = serde_json::from_str(r#"{"engine":"kokon-engine-mac","supported_modes":["img_gen"],
"features_by_mode":{"img_gen":{"ref_images":true}}}"#).unwrap();
assert_eq!(vision.mac_engine_unsupported(&edit), None);
assert!(vision.mac_engine_unsupported(&inpaint).is_some());
+ let masks: Capabilities = serde_json::from_str(r#"{"engine":"kokon-engine-mac","supported_modes":["img_gen"],
+ "features_by_mode":{"img_gen":{"ref_images":true,"init_image":true,"mask_image":true}}}"#).unwrap();
+ let brushed = ImgGenRequest { init_image: Some("png".into()), ref_images: vec!["png".into()], ..inpaint.clone() };
+ assert_eq!(masks.mac_engine_unsupported(&brushed), None);
+ let init_only: Capabilities = serde_json::from_str(r#"{"engine":"kokon-engine-mac","supported_modes":["img_gen"],
+ "features_by_mode":{"img_gen":{"ref_images":true,"init_image":true}}}"#).unwrap();
+ assert!(init_only.mac_engine_unsupported(&brushed).is_some(), "a mask the engine does not advertise");
let hires = ImgGenRequest { hires: Some(HiresParams { enabled: true, ..Default::default() }), ..t2i.clone() };
assert_eq!(caps.mac_engine_unsupported(&hires), Some("second passes"));
// sd-server: no engine field, nothing refused here.
diff --git a/engine-mac/README.md b/engine-mac/README.md
index 6caba5a..748bfea 100644
--- a/engine-mac/README.md
+++ b/engine-mac/README.md
@@ -260,9 +260,9 @@ Engine's programs, are not pipelines an archive holds. Only an M2 Pro has been m
`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, and edits with reference images when started with `--llm_vision` (qls-core passes
-the mmproj; below); an init image or a mask (brushed edits, extending an image), LoRAs and second passes are refused with
-400 (qls-core says so before submitting), upscaling falls back to Lanczos. Prompt+ works on every prompt (`text_gen`,
+`ProgressParser` reads. Text to image, edits with reference images when started with `--llm_vision` (qls-core passes
+the mmproj; below), and an init image with a mask (brushed edits, extending an image; below); LoRAs and second passes are
+refused with 400 (qls-core says so before submitting), upscaling falls back to Lanczos. Prompt+ works on every prompt (`text_gen`,
below), looking at the images of an edit with the vision tower. 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.
@@ -372,7 +372,29 @@ within 6.8e-4 (the fp16 cache), the greedy choice the same at 23 of 23.
.build/release/kokon-engine-mac generate <encoder.gguf> <dit.gguf> <vae> "make the cat a fox" --ref in.png --mmproj <mmproj.gguf>
```
-Not yet: an init image with a mask (brushed edits, extending an image: sd.cpp blends the masked latent each step).
+**Brushed edits and extending an image** (`init_image`, `mask_image`, `strength`; Kokon sends them with its references,
+both at the output's size): as Kokon's sd.cpp runs Qwen-Image 2.1 (pipeline/image.cpp, diffusion_engine.cpp). The init
+image goes through the VAE encoder as a reference does; `strength` cuts the schedule (`t_enc = int(8 · strength)`, at most
+7, from sigma index `7 − t_enc`: strength 1 runs all 8 steps, 0.6 runs 5); the start is `(1 − σ₀) · init + σ₀ · noise`
+(the noise itself at σ₀ = 1); the mask is read as stb_image reads it (8-bit gray as stored), each value / 255 rounded,
+then the largest of each 16 × 16 block (`NearestMax`), and outside it each step's x₀ prediction is the init, so the latent
+there stays the init's own noising and ends on the init.
+
+`reference_generate.py --init --mask --strength` writes it as diffusers' inpaint pipelines loop (`scale_noise` start, the
+init noised to the next σ blended in after each step: the same latent algebraically, written independently) with sd.cpp's
+schedule and mask rules. The street cat at 384 × 256 as init and reference, a feathered mask over the cat, "Turn the cat
+into a small red fox…" (M2 Pro, 2026-10-26):
+
+| | strength 1 (8 steps) | strength 0.6 (5 steps) |
+|---|---|---|
+| the reference's conditioning and latents, fp32 path | image 1.9e-6, 34 values off by 1 | 1.7e-6, 34 by 1 |
+| the engine's vision tower, text encoder, VAE encoder, fp32 path | 3.2e-6, 60 by 1 | 3.1e-6, 67 by 1 |
+| the same, default path | 2.1e-4, 1 384 by at most 2 | 1.6e-4, 1 181 by 1 |
+
+```bash
+~/kokon-bench/venv-oracle/bin/python -I tools/reference_generate.py <dit.gguf> <vae> ~/kokon-bench/ref/text/cat-edit <repo dir> ~/kokon-bench/ref/inpaint-cat-384 --size 384x256 --init cat-384x256.png --mask mask-cat-384x256.png --strength 1
+.build/release/kokon-engine-mac check-generate <encoder.gguf> <dit.gguf> <vae> ~/kokon-bench/ref/inpaint-cat-384 ~/kokon-bench/ref/text/cat-edit [<mmproj.gguf>]
+```
## Per-chip paths
diff --git a/engine-mac/Sources/KokonEngine/EngineServer.swift b/engine-mac/Sources/KokonEngine/EngineServer.swift
index 7a67c66..b474ead 100644
--- a/engine-mac/Sources/KokonEngine/EngineServer.swift
+++ b/engine-mac/Sources/KokonEngine/EngineServer.swift
@@ -9,9 +9,9 @@ import Foundation
/// POST /sdcpp/v1/jobs/{id}/cancel 200 {status: cancelled}: a running image stops within a DiT layer
/// POST /sdcpp/v1/text_gen Prompt+: the text encoder's LLM writes, streamed as Server-Sent Events
///
-/// Text to image and edits (`ref_images`, with the vision projector given as `--llm_vision`; Prompt+ then also looks at
-/// the images); requests with a mask, an
-/// init image, LoRAs or a second pass are refused with 400 and say so. Jobs and text generation run one at a time;
+/// Text to image, edits (`ref_images`, with the vision projector given as `--llm_vision`; Prompt+ then also looks at
+/// the images) and an init image with a mask (`init_image`, `mask_image`, `strength`: brushed edits, extending an
+/// image); requests with LoRAs or a second pass are refused with 400 and say so. Jobs and text generation run one at a time;
/// what stays loaded between them depends on the Mac (`QwenPipeline.keepModels`).
///
/// Progress goes to stdout as sd-server's log lines, the ones qls-core's `ProgressParser` reads (process.rs):
@@ -54,6 +54,7 @@ public final class EngineServer: @unchecked Sendable {
let sigmas: [Float]
/// An edit's condition images, decoded, at the size they are encoded at.
let references: [QwenPipeline.Reference]
+ let initImage: QwenPipeline.InitImage?
/// nil and the reason when the engine cannot do it (yet). `vision`: the engine has the vision tower (edits).
static func parse(_ body: Data, vision: Bool = true) -> (ImageRequest?, String?) {
@@ -61,9 +62,6 @@ public final class EngineServer: @unchecked Sendable {
return (nil, "the body is not a JSON object")
}
func array(_ key: String) -> [Any] { json[key] as? [Any] ?? [] }
- if json["init_image"] is String || json["mask_image"] is String {
- return (nil, "Kokon's Mac engine has no init image or mask yet (brushed edits, extending images)")
- }
let refs = array("ref_images")
if !refs.isEmpty && !vision {
return (nil, "Qwen Image 2.1 editing requires Qwen3-VL vision weights; start the engine with --llm_vision")
@@ -113,8 +111,35 @@ public final class EngineServer: @unchecked Sendable {
}
references.append(r)
}
+ // init_image, mask_image and strength (sd-server's default 0.75), at the output's size as Kokon sends them
+ // (`image_preprocess` mode=none).
+ func decoded(_ key: String) -> Data? {
+ (json[key] as? String).flatMap { Data(base64Encoded: String($0.split(separator: ",").last ?? ""), options: .ignoreUnknownCharacters) }
+ }
+ var initImage: QwenPipeline.InitImage?
+ if json["init_image"] is String || json["mask_image"] is String {
+ guard let data = decoded("init_image"), let image = try? QwenPipeline.decodeImage(data) else {
+ return (nil, json["init_image"] is String ? "init_image is not a base64 image" : "a mask_image needs an init_image")
+ }
+ guard image.width == width, image.height == height else {
+ return (nil, "init_image is \(image.width)×\(image.height); Kokon's Mac engine needs it at the output's \(width)×\(height)")
+ }
+ var mask: [UInt8]?
+ if json["mask_image"] is String {
+ guard let data = decoded("mask_image"), let m = try? QwenPipeline.decodeGray(data) else {
+ return (nil, "mask_image is not a base64 image")
+ }
+ guard m.width == width, m.height == height else {
+ return (nil, "mask_image is \(m.width)×\(m.height); Kokon's Mac engine needs it at the output's \(width)×\(height)")
+ }
+ mask = m.gray
+ }
+ let strength = (json["strength"] as? NSNumber)?.floatValue ?? 0.75
+ guard strength.isFinite, strength >= 0, strength <= 1 else { return (nil, "strength \(strength) out of [0, 1]") }
+ initImage = .init(image: .init(rgba: image.rgba, width: width, height: height), mask: mask, strength: strength)
+ }
return (ImageRequest(prompt: json["prompt"] as? String ?? "", width: width, height: height, seed: seed,
- batch: batch, sigmas: sigmas, references: references), nil)
+ batch: batch, sigmas: sigmas, references: references, initImage: initImage), nil)
}
}
@@ -181,7 +206,7 @@ public final class EngineServer: @unchecked Sendable {
func capabilities() -> [String: Any] {
let url = URL(fileURLWithPath: paths.diffusionModel)
- let feature: [String: Any] = ["ref_images": paths.vision != nil, "init_image": false, "mask_image": false, "lora": false,
+ let feature: [String: Any] = ["ref_images": paths.vision != nil, "init_image": true, "mask_image": true, "lora": false,
"hires": false, "custom_sigmas": true, "cancel_generating": true]
return [
"engine": "kokon-engine-mac",
@@ -435,7 +460,7 @@ public final class EngineServer: @unchecked Sendable {
log("[INFO ] engine-mac - decoding 1 latents")
}
}
- let image = try pipeline.generate(prompt: r.prompt, references: r.references, width: r.width, height: r.height,
+ let image = try pipeline.generate(prompt: r.prompt, references: r.references, initImage: r.initImage, width: r.width, height: r.height,
seed: UInt64(bitPattern: seed), sigmas: r.sigmas)
let png = try QwenPipeline.pngData(QwenPipeline.pixels(image, width: r.width, height: r.height), width: r.width, height: r.height)
images.append(png.base64EncodedString())
diff --git a/engine-mac/Sources/KokonEngine/QwenPipeline.swift b/engine-mac/Sources/KokonEngine/QwenPipeline.swift
index edef60b..8b9df54 100644
--- a/engine-mac/Sources/KokonEngine/QwenPipeline.swift
+++ b/engine-mac/Sources/KokonEngine/QwenPipeline.swift
@@ -97,6 +97,40 @@ public final class QwenPipeline {
sigmas: sigmas, step: step)
}
+ /// **An init image** (sd-server's `init_image`, `mask_image`, `strength`: brushed edits, extending an image, img2img),
+ /// as Kokon's sd.cpp runs it for Qwen-Image 2.1 (pipeline/image.cpp, diffusion_engine.cpp): the image through the VAE
+ /// encoder as the references; the schedule cut by `strength` (`steps(from:strength:)`); the start
+ /// `(1 − σ₀) · init + σ₀ · noise`; with a mask, each step's x₀ prediction replaced by the init outside it.
+ public struct InitImage {
+ /// At the output's size, interleaved 8-bit RGBA.
+ public let image: Reference
+ /// 8-bit gray at the output's size, white = repaint; nil: img2img alone.
+ public let mask: [UInt8]?
+ public let strength: Float
+ public init(image: Reference, mask: [UInt8]?, strength: Float) { (self.image, self.mask, self.strength) = (image, mask, strength) }
+ }
+
+ /// sd.cpp's img2img schedule: `t_enc = int(steps · strength)` (one less when that is every step), from sigma index
+ /// `steps − t_enc − 1` to the end, so a strength below 1 runs `t_enc + 1` steps.
+ public static func steps(from sigmas: [Float], strength: Float) -> [Float] {
+ let steps = sigmas.count - 1
+ guard strength < 1, steps > 0 else { return sigmas }
+ var encoded = Int(Float(steps) * strength)
+ if encoded >= steps { encoded = steps - 1 }
+ return Array(sigmas[(steps - max(0, encoded) - 1)...])
+ }
+
+ /// sd.cpp's latent mask: each value / 255 rounded (≥ 128 repaints), then the largest of each 16 × 16 block
+ /// (`NearestMax`); true where the token keeps the init image.
+ public static func keptTokens(mask: [UInt8], width: Int, height: Int) -> [Bool] {
+ let (h, w) = (height / 16, width / 16)
+ var keep = [Bool](repeating: true, count: h * w)
+ for y in 0..<(h * 16) {
+ for x in 0..<(w * 16) where mask[y * width + x] >= 128 { keep[(y / 16) * w + x / 16] = false }
+ }
+ return keep
+ }
+
/// **The vision tower's file** (mmproj, `--llm_vision`): edits need it.
public var visionPath: String?
@@ -105,16 +139,21 @@ public final class QwenPipeline {
/// the slots the encoder marks (`img_shapes`: the references, then the target). sd.cpp's `vlm_use_vae_input`: the
/// tower sees the image the VAE encodes. `conditioning`: the encoder's rows and which are image slots, instead of
/// encoding (the checks); `referenceLatents`: the references' packed tokens instead of the VAE encoder's.
- public func generate(prompt: String, references: [Reference] = [], width: Int, height: Int, seed: UInt64,
- noise: [Float]? = nil, conditioning given: (rows: [Float], slots: [Bool])? = nil,
- referenceLatents givenLatents: [Float]? = nil, sigmas: [Float] = QwenPipeline.turboSigmas,
- step: ((Int, [Float]) -> Void)? = nil) throws -> [Float] {
+ /// `initImage`: start from an image (`InitImage`); `initLatent`: its packed tokens instead of the VAE encoder's.
+ public func generate(prompt: String, references: [Reference] = [], initImage: InitImage? = nil, width: Int, height: Int,
+ seed: UInt64, noise: [Float]? = nil, conditioning given: (rows: [Float], slots: [Bool])? = nil,
+ referenceLatents givenLatents: [Float]? = nil, initLatent givenInit: [Float]? = nil,
+ sigmas: [Float] = QwenPipeline.turboSigmas, step: ((Int, [Float]) -> Void)? = nil) throws -> [Float] {
guard width % 32 == 0, height % 32 == 0, width >= 64, height >= 64 else {
throw QwenSequence.Failure.layout("\(width)×\(height): each side must be a multiple of 32, at least 64")
}
for r in references where r.width % 32 != 0 || r.height % 32 != 0 || r.rgba.count != 4 * r.width * r.height {
throw QwenSequence.Failure.layout("a reference of \(r.width)×\(r.height): sides must be multiples of 32")
}
+ if let initImage, initImage.image.width != width || initImage.image.height != height
+ || initImage.image.rgba.count != 4 * width * height || (initImage.mask.map { $0.count != width * height } ?? false) {
+ throw QwenSequence.Failure.layout("the init image and its mask must be \(width)×\(height)")
+ }
let started = DispatchTime.now().uptimeNanoseconds
timings = [:]
func since(_ t: UInt64) -> Double { Double(DispatchTime.now().uptimeNanoseconds - t) * 1e-9 }
@@ -162,22 +201,26 @@ public final class QwenPipeline {
log(String(format: "text encoder: %d tokens in %.2f s", rows, timings["encode"]!))
events?(.encoded(tokens: rows, seconds: timings["encode"]!))
- // 3. The references' latents (`_encode_vae_image`), packed and in order.
+ // 3. The references' latents (`_encode_vae_image`), packed and in order; the init image's the same way.
t = DispatchTime.now().uptimeNanoseconds
var referenceTokens: [Float] = givenLatents ?? []
- if givenLatents == nil, !references.isEmpty {
+ var initTokens = givenInit
+ let encodeReferences = givenLatents == nil && !references.isEmpty
+ if encodeReferences || (initImage != nil && givenInit == nil) {
if vae == nil { vae = try QwenVAE(path: vaePath, context: context) }
- for r in references {
+ func encoded(_ r: Reference) throws -> [Float] {
// VaeImageProcessor.preprocess: x / 255, then 2x − 1; planar RGBA.
let plane = r.width * r.height
var input = [Float](repeating: 0, count: 4 * plane)
for p in 0..<plane { for c in 0..<4 { input[c * plane + p] = Float(r.rgba[p * 4 + c]) / 255 * 2 - 1 } }
- let latent = try vae!.encode(input, height: r.height, width: r.width)
- referenceTokens += QwenPipeline.pack(latent, height: r.height / 16, width: r.width / 16)
+ return QwenPipeline.pack(try vae!.encode(input, height: r.height, width: r.width), height: r.height / 16, width: r.width / 16)
}
+ if encodeReferences { for r in references { referenceTokens += try encoded(r) } }
+ if let initImage, initTokens == nil { initTokens = try encoded(initImage.image) }
if !keepVAE { vae = nil }
timings["vae encode"] = since(t)
- log(String(format: "VAE encoder: %d reference(s) in %.2f s", references.count, timings["vae encode"]!))
+ log(String(format: "VAE encoder: %d image(s) in %.2f s", (encodeReferences ? references.count : 0) + (givenInit == nil && initImage != nil ? 1 : 0),
+ timings["vae encode"]!))
}
// 4. Noise, packed: token y·w + x holds the 64 channels of cell (y, x).
@@ -186,6 +229,13 @@ public final class QwenPipeline {
throw QwenSequence.Failure.layout("noise of \(start.count) values for a \(channels)×\(h)×\(w) latent")
}
var x = QwenPipeline.pack(start, height: h, width: w)
+ let schedule = initImage.map { QwenPipeline.steps(from: sigmas, strength: $0.strength) } ?? sigmas
+ // sd.cpp's `noise_scaling` for flow models; at σ₀ = 1 (strength 1) the noise itself.
+ if let initTokens {
+ guard initTokens.count == x.count else { throw QwenSequence.Failure.layout("an init latent of \(initTokens.count) values") }
+ for j in x.indices { x[j] = initTokens[j] * (1 - schedule[0]) + x[j] * schedule[0] }
+ }
+ let kept = initImage?.mask.map { QwenPipeline.keptTokens(mask: $0, width: width, height: height) }
// 5. The steps.
t = DispatchTime.now().uptimeNanoseconds
@@ -208,21 +258,28 @@ public final class QwenPipeline {
}
dit.cancelled = cancelled
defer { dit.cancelled = { false } }
- try dit.prepareModulation([0] + sigmas.dropLast())
+ try dit.prepareModulation([0] + schedule.dropLast())
timings["dit load"] = since(t)
let memory = dit.memoryBytes
log(String(format: "DiT: %d rows, prefix %d, prefix K/V cache %@, working memory %.2f GB%@", sequence.count, sequence.prefix,
dit.prefixCache.map { String(format: "%.2f GB (%@)", Double($0.length) / 1e9, dit.cacheFormat.rawValue) } ?? "off",
Double(memory.all) / 1e9, memory.target.map { String(format: " (target's %.2f GB)", Double($0) / 1e9) } ?? ""))
- for i in 0..<(sigmas.count - 1) {
+ for i in 0..<(schedule.count - 1) {
if cancelled() { throw QwenDiT.Cancelled() }
let stepStart = DispatchTime.now().uptimeNanoseconds
- let velocity = try dit.forward(encoder: conditioning, references: referenceTokens, target: x, sigma: sigmas[i])
- let dt = sigmas[i + 1] - sigmas[i]
- for j in x.indices { x[j] += dt * velocity[j] }
+ let sigma = schedule[i]
+ let velocity = try dit.forward(encoder: conditioning, references: referenceTokens, target: x, sigma: sigma)
+ let dt = schedule[i + 1] - sigma
+ if let kept, let initTokens {
+ // Outside the mask sd.cpp's x₀ prediction is the init, so the step is (x − init) / σ: x stays on
+ // the init's own noising, (1 − σ) · init + σ · noise, and ends on it.
+ for j in x.indices { x[j] += dt * (kept[j / channels] ? (x[j] - initTokens[j]) / sigma : velocity[j]) }
+ } else {
+ for j in x.indices { x[j] += dt * velocity[j] }
+ }
timings["step \(i + 1)"] = since(stepStart)
- log(String(format: "step %d/%d (σ %.4f): %.2f s", i + 1, sigmas.count - 1, sigmas[i], timings["step \(i + 1)"]!))
- events?(.step(i + 1, of: sigmas.count - 1, seconds: timings["step \(i + 1)"]!))
+ log(String(format: "step %d/%d (σ %.4f): %.2f s", i + 1, schedule.count - 1, sigma, timings["step \(i + 1)"]!))
+ events?(.step(i + 1, of: schedule.count - 1, seconds: timings["step \(i + 1)"]!))
step?(i, x)
}
shares = dit.coexecutor?.shares
@@ -359,6 +416,24 @@ public final class QwenPipeline {
return (out, w, h)
}
+ /// A mask file as 8-bit gray, as sd-server loads `mask_image` (stb_image with one channel): 8-bit gray read as
+ /// stored, anything else through `decodeImage` and stb's luminance `(77 r + 150 g + 29 b) >> 8`.
+ public static func decodeGray(_ data: Data) throws -> (gray: [UInt8], width: Int, height: Int) {
+ if let source = CGImageSourceCreateWithData(data as CFData, nil), let image = CGImageSourceCreateImageAtIndex(source, 0, nil),
+ image.colorSpace?.model == .monochrome, image.bitsPerComponent == 8, image.bitsPerPixel == 8,
+ let bytes = image.dataProvider?.data, let p = CFDataGetBytePtr(bytes) {
+ let (w, h) = (image.width, image.height)
+ var out = [UInt8](repeating: 0, count: w * h)
+ for y in 0..<h { for x in 0..<w { out[y * w + x] = p[y * image.bytesPerRow + x] } }
+ 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)
+ }
+ return (gray, rgba.width, rgba.height)
+ }
+
/// Interleaved 8-bit RGBA (straight alpha) encoded as a PNG.
public static func pngData(_ rgba: [UInt8], width: Int, height: Int) throws -> Data {
let data = Data(rgba) as CFData
diff --git a/engine-mac/Sources/KokonEngine/TextChecks.swift b/engine-mac/Sources/KokonEngine/TextChecks.swift
index ca7c6a0..178f5df 100644
--- a/engine-mac/Sources/KokonEngine/TextChecks.swift
+++ b/engine-mac/Sources/KokonEngine/TextChecks.swift
@@ -141,9 +141,21 @@ extension Checks {
let rows = try reference(text, "conditioning")
given = (rows, [Bool](repeating: false, count: rows.count / QwenDiT.dim))
}
- let image = try pipeline.generate(prompt: prompt, references: references, width: w * 16, height: h * 16, seed: 0,
- noise: try reference(directory, "noise"), conditioning: given,
- referenceLatents: latents) { i, latent in
+ // An init image and a mask (`reference_generate.py --init --mask --strength`).
+ var initImage: QwenPipeline.InitImage?, initLatent: [Float]?
+ if meta["init"] as? Bool == true {
+ let folder = URL(fileURLWithPath: directory)
+ let png = try QwenPipeline.decodeImage(Data(contentsOf: folder.appendingPathComponent("init.png")))
+ let mask = meta["mask"] as? Bool == true
+ ? try QwenPipeline.decodeGray(Data(contentsOf: folder.appendingPathComponent("mask.png"))).gray : nil
+ let strength = Float(meta["strength"] as? Double ?? 1)
+ initImage = .init(image: .init(rgba: png.rgba, width: png.width, height: png.height), mask: mask, strength: strength)
+ if mmproj == nil && !sizes.isEmpty { initLatent = try reference(directory, "init_latent") }
+ print("init image, \(mask == nil ? "no mask" : "mask"), strength \(strength)")
+ }
+ let image = try pipeline.generate(prompt: prompt, references: references, initImage: initImage, width: w * 16, height: h * 16,
+ seed: 0, noise: try reference(directory, "noise"), conditioning: given,
+ referenceLatents: latents, initLatent: initLatent) { i, latent in
latent.withUnsafeBufferPointer { report("latent\(i)", $0.baseAddress!, try! reference(directory, "latent\(i)")) }
}
image.withUnsafeBufferPointer { report("image", $0.baseAddress!, try! reference(directory, "image")) }
diff --git a/engine-mac/Tests/KokonEngineTests/QwenPipelineTests.swift b/engine-mac/Tests/KokonEngineTests/QwenPipelineTests.swift
index f0b6151..9feb60a 100644
--- a/engine-mac/Tests/KokonEngineTests/QwenPipelineTests.swift
+++ b/engine-mac/Tests/KokonEngineTests/QwenPipelineTests.swift
@@ -13,6 +13,24 @@ final class QwenPipelineTests: XCTestCase {
XCTAssertEqual(QwenPipeline.unpack(tokens, height: h, width: w), latent)
}
+ /// sd.cpp's img2img cut (pipeline/image.cpp): t_enc = int(8 · strength), at most 7, from sigma index 7 − t_enc.
+ func testStrengthCutsTheScheduleAsSdCpp() {
+ let sigmas = QwenPipeline.turboSigmas
+ XCTAssertEqual(QwenPipeline.steps(from: sigmas, strength: 1), sigmas)
+ XCTAssertEqual(QwenPipeline.steps(from: sigmas, strength: 0.99), sigmas) // t_enc 7: every step
+ XCTAssertEqual(QwenPipeline.steps(from: sigmas, strength: 0.5), Array(sigmas[3...])) // t_enc 4: 5 steps
+ XCTAssertEqual(QwenPipeline.steps(from: sigmas, strength: 0.125), Array(sigmas[6...]))
+ XCTAssertEqual(QwenPipeline.steps(from: sigmas, strength: 0), Array(sigmas[7...])) // one step at least
+ }
+
+ /// The latent mask: gray / 255 rounded (128 repaints, 127 does not), then the largest of each 16 × 16 block.
+ func testMaskIsRoundedThenTheLargestOfEachBlock() {
+ var mask = [UInt8](repeating: 127, count: 48 * 32) // 3 × 2 tokens
+ mask[5 * 48 + 20] = 128 // pixel (20, 5): token (1, 0)
+ mask[31 * 48 + 47] = 255 // the last pixel: token (2, 1)
+ XCTAssertEqual(QwenPipeline.keptTokens(mask: mask, width: 48, height: 32), [true, false, true, true, true, false])
+ }
+
func testNoiseIsSdCppsBitForBit() {
// Values of sd.cpp's PhiloxRNG built as Kokon's macOS engine (tools/philox_reference.cpp): the first four
// and the last of a 1024² latent's draw, then the first of the next draw.
diff --git a/engine-mac/Tests/KokonEngineTests/VisionTests.swift b/engine-mac/Tests/KokonEngineTests/VisionTests.swift
index 1bad88b..81486cc 100644
--- a/engine-mac/Tests/KokonEngineTests/VisionTests.swift
+++ b/engine-mac/Tests/KokonEngineTests/VisionTests.swift
@@ -1,3 +1,4 @@
+import ImageIO
import XCTest
@testable import KokonEngine
@@ -76,6 +77,39 @@ final class EditRequestTests: XCTestCase {
"ref_image_args": "resize_before_vae=false"])).1) // 336 % 32
XCTAssertNotNil(EngineServer.ImageRequest.parse(try body(["ref_images": ["not an image"]])).1)
}
+
+ /// 8-bit gray PNG, as qls-core sends masks (`gray_png_b64`).
+ func grayPNG(_ gray: [UInt8], _ width: Int, _ height: Int) throws -> String {
+ let data = NSMutableData()
+ let provider = CGDataProvider(data: Data(gray) as CFData)!
+ let image = CGImage(width: width, height: height, bitsPerComponent: 8, bitsPerPixel: 8, bytesPerRow: width,
+ space: CGColorSpaceCreateDeviceGray(), bitmapInfo: CGBitmapInfo(rawValue: 0), provider: provider,
+ decode: nil, shouldInterpolate: false, intent: .defaultIntent)!
+ let destination = CGImageDestinationCreateWithData(data, "public.png" as CFString, 1, nil)!
+ CGImageDestinationAddImage(destination, image, nil)
+ XCTAssert(CGImageDestinationFinalize(destination))
+ return (data as Data).base64EncodedString()
+ }
+
+ func testInitImageAndMaskAreReadAsSent() throws {
+ let gray = (0..<(512 * 384)).map { UInt8(truncatingIfNeeded: $0 * 13) }
+ let (r, reason) = EngineServer.ImageRequest.parse(try body(["init_image": try png(512, 384), "mask_image": try grayPNG(gray, 512, 384)]))
+ XCTAssertNil(reason)
+ XCTAssertEqual(r?.initImage?.mask, gray) // gray values as stored, no color conversion
+ XCTAssertEqual(r?.initImage?.strength, 0.75) // sd-server's default
+ XCTAssertEqual(r?.initImage?.image.rgba[4 * 5 + 1], UInt8(truncatingIfNeeded: (4 * 5 + 1) * 7))
+ let plain = EngineServer.ImageRequest.parse(try body(["init_image": try png(512, 384), "strength": 1])).0
+ XCTAssertNil(plain?.initImage?.mask)
+ XCTAssertEqual(plain?.initImage?.strength, 1)
+ XCTAssertNil(EngineServer.ImageRequest.parse(try body([:])).0?.initImage)
+ }
+
+ func testInitImageRefusals() throws {
+ XCTAssertNotNil(EngineServer.ImageRequest.parse(try body(["init_image": try png(256, 384)])).1) // not the output's size
+ XCTAssertNotNil(EngineServer.ImageRequest.parse(try body(["mask_image": try png(512, 384)])).1) // a mask alone
+ XCTAssertNotNil(EngineServer.ImageRequest.parse(try body(["init_image": try png(512, 384), "mask_image": try png(512, 256)])).1)
+ XCTAssertNotNil(EngineServer.ImageRequest.parse(try body(["init_image": try png(512, 384), "strength": 1.5])).1)
+ }
}
/// The text encoder's side of images, without a model: Qwen3-VL's 3D positions and the templates.
diff --git a/engine-mac/tools/reference_generate.py b/engine-mac/tools/reference_generate.py
index 205c9e6..5af46ab 100644
--- a/engine-mac/tools/reference_generate.py
+++ b/engine-mac/tools/reference_generate.py
@@ -15,7 +15,16 @@ to the VAE (RGBA, `VaeImageProcessor.preprocess` at its own size, which `resize_
text reference's `image_pad_mask` places their slots. Saved as `reference<i>`.
python -I engine-mac/tools/reference_generate.py <dit.gguf> <vae.safetensors> <text reference dir> <repo dir> <out>
- [--grid 16 | --size WxH] [--seed 1] [--dtype float64]
+ [--grid 16 | --size WxH] [--seed 1] [--dtype float64] [--init in.png [--mask mask.png] [--strength 1]]
+
+**An init image and a mask** (`--init`, `--mask`, `--strength`; brushed edits and extending an image, as Kokon's
+sd.cpp runs them for Qwen-Image 2.1, pipeline/image.cpp and diffusion_engine.cpp), written as diffusers' inpaint
+pipelines loop (QwenImageInpaintPipeline): the init image encoded as the references are; the schedule cut by sd.cpp's
+rule (`t_enc = int(steps · strength)`, one less at `steps`, start at sigma index `steps − t_enc − 1`: one step more
+than diffusers' `get_timesteps`); the start `scale_noise(init, σ₀, noise)`; after each step the latent outside the
+mask replaced by the init noised to the next σ (the clean init after the last). The mask as sd.cpp reads it: gray / 255
+rounded, then the largest value of each 16 × 16 block (`NearestMax`), 1 = repaint. sd.cpp blends the x₀ prediction
+with the clean init instead, the same latent algebraically. Saves `init.png`, `mask.png` and `init_latent`.
`--dtype float64`: the DiT and the latents in fp64 (the scheduler still rounds the latent to fp32 each step), the
VAE in fp32. Needed on unsloth's DiT, where torch's fp32 drifts to 7e-5 of fp64 in one evaluation.
@@ -51,6 +60,9 @@ def main():
parser.add_argument("--size", help="WxH of the image instead (multiples of 32)")
parser.add_argument("--seed", type=int, default=1)
parser.add_argument("--dtype", default="float32", choices=["float32", "float64"])
+ parser.add_argument("--init", help="init image (PNG at the output's size)")
+ parser.add_argument("--mask", help="mask (PNG at the output's size; white = repaint)")
+ parser.add_argument("--strength", type=float, default=1.0)
args = parser.parse_args()
dtype = getattr(torch, args.dtype)
if dtype == torch.float64:
@@ -85,10 +97,34 @@ def main():
refs.append((packed.to(dtype), rh // 16, rw // 16))
del encoder_vae
+ # The init image and the mask (sd.cpp's rules, above).
+ init, keep = None, None
+ if args.init:
+ encoder_vae = load_full_vae(args.vae)
+ processor = VaeImageProcessor(vae_scale_factor=16, vae_latent_channels=64)
+ mean = torch.tensor(encoder_vae.config.latents_mean).view(1, 64, 1, 1, 1)
+ std = torch.tensor(encoder_vae.config.latents_std).view(1, 64, 1, 1, 1)
+ image = Image.open(args.init).convert("RGBA")
+ assert image.size == (w * 16, h * 16), f"the init image must be {w * 16}x{h * 16}"
+ image.save(os.path.join(args.out, "init.png"))
+ latent = (encoder_vae.encode(processor.preprocess(image, width=w * 16, height=h * 16).unsqueeze(2)).latent_dist.mode() - mean) / std
+ init = latent[0, :, 0].reshape(64, -1).transpose(0, 1)[None]
+ save("init_latent", init[0])
+ init = init.to(dtype)
+ del encoder_vae
+ if args.mask:
+ gray = Image.open(args.mask).convert("L")
+ assert gray.size == (w * 16, h * 16), f"the mask must be {w * 16}x{h * 16}"
+ gray.save(os.path.join(args.out, "mask.png"))
+ pixels = torch.from_numpy(np.asarray(gray, dtype=np.float32) / 255)
+ blocks = torch.floor(pixels + 0.5).view(h, 16, w, 16).amax(dim=(1, 3)) # std::round, then NearestMax
+ keep = (1 - blocks).reshape(1, h * w, 1).to(dtype) # 1 = the init stays
+
# prepare_latents + _pack_latents
noise = torch.randn((1, 1, 64, h, w), generator=torch.Generator().manual_seed(args.seed), dtype=torch.float32)
save("noise", noise[0, 0])
- latents = noise.view(1, 64, h * w).transpose(1, 2).to(dtype)
+ noise = noise.view(1, 64, h * w).transpose(1, 2).to(dtype)
+ latents = noise
# retrieve_timesteps with the checkpoint's sigmas
index = json.load(open(os.path.join(args.repo, "model_index.json")))
@@ -98,14 +134,25 @@ def main():
scheduler.config.get("max_image_seq_len", 4096), scheduler.config.get("base_shift", 0.5),
scheduler.config.get("max_shift", 1.15))
scheduler.set_timesteps(sigmas=index["sample_sigmas"], mu=mu)
- scheduler.set_begin_index(0)
+ start = 0
+ if init is not None and args.strength < 1:
+ steps = len(scheduler.timesteps)
+ t_enc = int(steps * np.float32(args.strength))
+ start = steps - (t_enc - 1 if t_enc == steps else t_enc) - 1
+ scheduler.set_begin_index(start)
+ timesteps = scheduler.timesteps[start:]
+ if init is not None:
+ latents = scheduler.scale_noise(init, timesteps[:1], noise) # σ · noise + (1 − σ) · init
dit = ReferenceDiT(args.dit, dtype=dtype)
- for i, t in enumerate(scheduler.timesteps):
+ for i, t in enumerate(timesteps):
velocity = dit.forward(conditioning, latents, h, w, t.expand(1).to(dtype) / 1000, progress=False,
refs=refs, slots=slots)
save(f"velocity{i}", velocity[0])
latents = scheduler.step(velocity, t, latents, return_dict=False)[0]
+ if keep is not None:
+ proper = init if i == len(timesteps) - 1 else scheduler.scale_noise(init, timesteps[i + 1:i + 2], noise)
+ latents = keep * proper + (1 - keep) * latents
save(f"latent{i}", latents[0])
print(f"step {i + 1}: t {float(t) / 1000:.6f}", flush=True)
@@ -121,9 +168,9 @@ def main():
np.asarray(pil).tofile(os.path.join(args.out, "pixels.u8"))
meta = {"prompt": text_meta["prompt"], "grid": [h, w], "seed": args.seed, "mode": pil.mode,
- "sigmas": scheduler.sigmas.tolist(), "timesteps": (scheduler.timesteps / 1000).tolist(),
+ "sigmas": scheduler.sigmas[start:].tolist(), "timesteps": (timesteps / 1000).tolist(),
"dit": os.path.basename(args.dit), "dtype": args.dtype, "vae": os.path.basename(args.vae),
- "references": sizes}
+ "references": sizes, "init": init is not None, "mask": keep is not None, "strength": args.strength}
with open(os.path.join(args.out, "meta.json"), "w") as f:
json.dump(meta, f, indent=1)
print(f"image {pil.size} {pil.mode}")