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: fp16 weights and activations in the products, BNNS on the AMX

Gabriele Lozuponeb7c9c372a885
diff --git a/engine-mac/README.md b/engine-mac/README.md
index f4a2888..3f0e1d1 100644
--- a/engine-mac/README.md
+++ b/engine-mac/README.md
@@ -29,6 +29,7 @@ swift test # no model needed
| `QwenSequence.swift` | the joint text/image sequence, block-causal segments and RoPE positions |
| `QwenDiT.swift`, `Kernels/dit.metal`, `Attention.swift`, `Arena.swift` | the DiT: modulation on the CPU, everything per token on the GPU |
| `Coexecution.swift`, `Kernels/ane.metal` | the AMX and the Neural Engine beside the GPU on the DiT's products; the timeline of each split operation |
+| `CPUProduct.swift` | the AMX's products: BNNS, fp32 or fp16 operands |
| `Balancer.swift` | the balancing loop: each evaluation's timeline sets the next one's rows and heads per unit |
| `Kernels/attention.metal` | fused block-causal attention |
| `AttentionSplit.swift`, `CPUAttention.swift` | the target's attention cut by heads: GPU, CPU (AMX + cores), optionally the Neural Engine |
@@ -170,6 +171,22 @@ fp16 operands in the flash kernel, **the default since 2026-10-25** (`KOKON_ATTE
the velocity within 6.0e-4 of fp64 at 256² (fp32 kernel 1.0e-5; bf16 tools ~1e-2); the two 1024² images differ by 0.25
levels on average, 0.18 % of values by more than 8. The accuracy figures above are the fp32 kernel's.
+**fp16 operands in the products, the default since 2026-10-25** (`KOKON_WEIGHTS=fp32` and `KOKON_ACTIVATIONS=fp32`
+for the checks): the weights are unpacked to fp16 (half the bytes written and read by every unit), the GPU casts
+the GPU's and the AMX's rows of each input to fp16 once (shared by q, k, v and by gate, proj), MPS multiplies fp16 ×
+fp16 into fp32 and the AMX runs BNNS instead of `cblas_sgemm` (alone, on its shares: fp32 1.3–1.9× faster, fp16
+inputs 2–2.7×). The three units share one limit when they run together (memory or power: BNNS in fp32 alone moved
+an 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.55
+s** (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).
+The 1024² image against the previous precision: 0.05 levels on average, at most 6. **1024² image: 69.8 s** (text
+encoder 2.0 s, step 1 8.4 s, steps 2–8 7.4–8.0 s, VAE 6.0 s).
+
+MFA's GEMM (libnnc, 48 × 48 blocks, 2 × 2 SIMD groups) was tried against MPS: its async copies are an AIR intrinsic
+that macOS 27's run-time compiler refuses (libnnc ships prebuilt metallibs for it), and without them it ran at
+3.6–4.0 TFLOP/s against MPS's 5.1–5.6 at 1472 × 4096 × 4096, so MPS stays.
+
**VAE decoder** (`check-vae`, against `tools/reference_vae.py`, diffusers fp32): within 1.1e-5; 1024² in 2.75 s. Its
graph builds and compiles in 0.3 s, but its first run at a size costs ~3.7 s more, GPU time (~1 s of CPU): it cannot
hide under the DiT, so the pipeline keeps its VAE between images and a long-lived engine pays it once per size.
diff --git a/engine-mac/Sources/KokonEngine/CPUProduct.swift b/engine-mac/Sources/KokonEngine/CPUProduct.swift
new file mode 100644
index 0000000..6b503cc
--- /dev/null
+++ b/engine-mac/Sources/KokonEngine/CPUProduct.swift
@@ -0,0 +1,35 @@
+import Accelerate
+
+/// **Products on the CPU's matrix unit (AMX)**, row-major, contiguous rows: `C[m, n] = α · A[m, k] · B`, B `[k, n]`
+/// or, `transposedB`, `[n, k]`; C fp32, A and B fp32 or fp16 (`halfA`, `halfB`).
+///
+/// BNNS rather than `cblas_sgemm`: on the DiT's AMX shares, both fp32 and exact to 4e-6, BNNS runs 1.3–1.9× faster
+/// (M2 Pro, macOS 27, 2026-10-25: 448 × 4096 × 4096 8.0 ms against 14.8 ms, 448 × 4096 × 12288 23.7 against ~40,
+/// 320 × 12288 × 4096 20.2 against 25.8). `BNNSMatMul` is deprecated since macOS 15 for BNNSGraph, which compiles
+/// a whole graph ahead; for one product with run-time operands this call is still the direct way.
+enum CPUProduct {
+ static func multiply(_ a: UnsafeRawPointer, _ b: UnsafeRawPointer, into c: UnsafeMutablePointer<Float>,
+ m: Int, k: Int, n: Int, alpha: Float = 1, transposedB: Bool = false, halfA: Bool = false, halfB: Bool = false,
+ threads: Int? = nil) -> Bool {
+ func matrix(_ p: UnsafeRawPointer, rows: Int, columns: Int, type: BNNSDataType = .float) -> BNNSNDArrayDescriptor {
+ var d = BNNSNDArrayDescriptor()
+ d.layout = BNNSDataLayoutRowMajorMatrix
+ d.size = (columns, rows, 0, 0, 0, 0, 0, 0)
+ d.data = UnsafeMutableRawPointer(mutating: p)
+ d.data_type = type
+ d.data_scale = 1
+ return d
+ }
+ var da = matrix(a, rows: m, columns: k, type: halfA ? .float16 : .float)
+ let typeB: BNNSDataType = halfB ? .float16 : .float
+ var db = transposedB ? matrix(b, rows: n, columns: k, type: typeB) : matrix(b, rows: k, columns: n, type: typeB)
+ var dc = matrix(c, rows: m, columns: n)
+ var parameters = BNNSFilterParameters()
+ parameters.n_threads = threads ?? 0
+ let size = BNNSMatMulWorkspaceSize(false, transposedB, alpha, &da, &db, &dc, &parameters)
+ guard size >= 0 else { return false }
+ let workspace = size > 0 ? UnsafeMutableRawPointer.allocate(byteCount: size, alignment: 64) : nil
+ defer { workspace?.deallocate() }
+ return BNNSMatMul(false, transposedB, alpha, &da, &db, &dc, workspace, &parameters) == 0
+ }
+}
diff --git a/engine-mac/Sources/KokonEngine/Coexecution.swift b/engine-mac/Sources/KokonEngine/Coexecution.swift
index 461ef4d..0e91f7d 100644
--- a/engine-mac/Sources/KokonEngine/Coexecution.swift
+++ b/engine-mac/Sources/KokonEngine/Coexecution.swift
@@ -6,7 +6,7 @@ import Metal
///
/// C[m, n] = A[m, k] · W[k, n] W already unpacked to fp32 [k, n] (the reserve) by the GPU
/// rows [0, g) GPU, MPS fp32
-/// rows [g, g + a) AMX, cblas_sgemm fp32 on the same reserve (unified memory)
+/// rows [g, g + a) AMX, BNNS fp32 on the same reserve (unified memory)
/// rows [g + a, m) Neural Engine, fp16 in tiles of 4 096 × 4 096 (`ane.metal` packs and unpacks)
///
/// GPU timeline per product p: unpack W → pack the Neural Engine's tiles → signal `ready` = p → its own rows →
@@ -54,6 +54,15 @@ 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
+ /// 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).
+ /// With fp16 weights, 1024² on the M2 Pro (`time-dit`, 2026-10-25): 7.46 s per evaluation against 8.0–8.1 (fp32 A)
+ /// and 8.54 with fp32 weights and `cblas_sgemm`; the AMX runs BNNS fp16 × fp16 at ~2.5 TFLOP/s alone against ~1.0
+ /// for `cblas_sgemm`. The velocity at 896² against diffusers: 7.2e-4 (fp32 A 5.7e-4, fp32 weights 5.1e-4; the
+ /// Neural Engine's rows are fp16 in every case).
+ let halfActivations = ProcessInfo.processInfo.environment["KOKON_ACTIVATIONS"] != "fp32"
+ private lazy var aHalf: MTLBuffer? = try? context.scratch(rows * QwenDiT.hidden * 2, label: "A fp16")
/// Seconds each worker spent computing (not waiting), and failures (a failure leaves rows unwritten).
var amxSeconds = 0.0, aneSeconds = 0.0
var failures: [String] = []
@@ -66,8 +75,10 @@ final class Coexecutor {
/// 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, ane: Bool = true, amx: Bool = true, aneAttention: Bool = false) throws {
+ init(context: MetalContext, rows: Int, ane: Bool = true, amx: Bool = true, aneAttention: Bool = false,
+ halfWeights: Bool = false) throws {
self.context = context
+ self.halfWeights = halfWeights
self.rows = rows
self.aneEnabled = ane
self.amxEnabled = amx
@@ -131,7 +142,8 @@ final class Coexecutor {
w: (buffer: MTLBuffer, offset: Int, pointer: UnsafeMutablePointer<Float>),
c: (buffer: MTLBuffer, offset: Int, pointer: UnsafeMutablePointer<Float>),
m: Int, k: Int, n: Int, commands: MTLCommandBuffer,
- ahead: ((MTLCommandBuffer) throws -> Void)? = nil, gpuRows: (Int) throws -> Void) throws {
+ castReady: Bool = false, ahead: ((MTLCommandBuffer) throws -> Void)? = nil,
+ gpuRows: (Int, MTLBuffer?) throws -> Void) throws {
let s = split(m: m, k: k, n: n)
counter += 1
let p = counter
@@ -184,18 +196,29 @@ final class Coexecutor {
}
}
}
+ let half = halfActivations ? aHalf : nil
+ // Every row but the Neural Engine's (the same for every product), so the next product on the same A
+ // (`castReady`: q, k, v; gate, proj) reuses the cast whatever its AMX share.
+ if let half, !castReady {
+ var count = UInt32((m - s.ane) * k)
+ try kernel("pack_half") { e in
+ e.setBuffer(a.buffer, offset: a.offset, index: 0); e.setBuffer(half, offset: 0, index: 1)
+ e.setBytes(&count, length: 4, index: 2)
+ e.dispatchThreads(MTLSize(width: Int(count), height: 1, depth: 1), threadsPerThreadgroup: MTLSize(width: 256, height: 1, depth: 1))
+ }
+ }
if s.amx > 0 || s.ane > 0 { commands.encodeSignalEvent(ready, value: p) }
// The next weight's own work while the AMX and the Neural Engine run this product.
try ahead?(commands)
if s.amx > 0 {
- nonisolated(unsafe) let (pa, pw, pc) = (a.pointer + s.gpu * k, w.pointer, c.pointer + s.gpu * n)
+ nonisolated(unsafe) let (pa, pw, pc) = (half.map { UnsafeRawPointer($0.contents() + s.gpu * k * 2) } ?? UnsafeRawPointer(a.pointer + s.gpu * k),
+ UnsafeRawPointer(w.pointer), c.pointer + s.gpu * n)
let rows = s.amx
amxWorker.submit { [self] in
defer { amxDone.signaledValue = p }
guard wait(ready, p, "AMX") else { return }
let t = DispatchTime.now().uptimeNanoseconds
- cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, Int32(rows), Int32(n), Int32(k), 1,
- pa, Int32(k), pw, Int32(n), 0, pc, Int32(n))
+ if !CPUProduct.multiply(pa, pw, into: pc, m: rows, k: k, n: n, halfA: half != nil, halfB: halfWeights) { fail("AMX: BNNS refused \(rows)×\(k)×\(n)") }
finished(p, \.amx, since: t)
}
}
@@ -209,7 +232,7 @@ final class Coexecutor {
finished(p, \.ane, since: t)
}
}
- try gpuRows(s.gpu)
+ try gpuRows(s.gpu, half)
gpuFinished(p, commands)
if s.amx > 0 { commands.encodeWaitForEvent(amxDone, value: p) }
if s.ane > 0 {
@@ -254,7 +277,7 @@ final class Coexecutor {
let columns = try context.scratch((2 * n + 16) * 4, label: "λ \(weight)")
columnScales[weight] = columns
var sh = Shape(k: UInt32(k), n: UInt32(n), k0: 0, kPart: 0, n0: 0, nPart: 0, row0: 0, rows: 0, kParts: 0)
- try kernel("ane_columns", commands) { e in
+ try kernel(halfWeights ? "ane_columns_h" : "ane_columns", commands) { e in
e.setBuffer(w.buffer, offset: w.offset, index: 0)
e.setBuffer(columns, offset: 0, index: 1); e.setBuffer(columns, offset: n * 4, index: 2)
e.setBytes(&sh, length: MemoryLayout<Shape>.stride, index: 3)
@@ -277,7 +300,7 @@ 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("ane_pack_weight", commands) { e in
+ try kernel(halfWeights ? "ane_pack_weight_h" : "ane_pack_weight", commands) { e in
e.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.metal
index 553af89..1d8bcec 100644
--- a/engine-mac/Sources/KokonEngine/Kernels/ane.metal
+++ b/engine-mac/Sources/KokonEngine/Kernels/ane.metal
@@ -30,7 +30,8 @@ struct AneShape {
// Per column of W [k, n]: λ_j and the lifted column's L1 norm. A threadgroup takes 64 columns, 16 row slices of
// each (coalesced rows), combined in threadgroup memory: one thread per column walking every row took ~8 ms per
// 4096 × 12288 weight (M2 Pro).
-kernel void ane_columns(device const float *w [[buffer(0)]], device float *lambda [[buffer(1)]],
+template <typename T>
+kernel void ane_columns(device const T *w [[buffer(0)]], device float *lambda [[buffer(1)]],
device float *norm [[buffer(2)]], constant AneShape &s [[buffer(3)]],
uint2 tg [[threadgroup_position_in_grid]], uint2 t [[thread_position_in_threadgroup]]) {
threadgroup float peaks[16][64], sums[16][64];
@@ -38,7 +39,7 @@ kernel void ane_columns(device const float *w [[buffer(0)]], device float *lambd
float peak = 0, sum = 0;
if (j < s.n) {
for (uint r = t.y; r < s.k; r += 16) {
- float v = fabs(w[(ulong)r * s.n + j]);
+ float v = fabs(float(w[(ulong)r * s.n + j]));
peak = max(peak, v);
sum += v;
}
@@ -54,6 +55,11 @@ kernel void ane_columns(device const float *w [[buffer(0)]], device float *lambd
}
}
+template [[host_name("ane_columns")]] kernel void ane_columns<float>(device const float *, device float *, device float *,
+ constant AneShape &, uint2, uint2);
+template [[host_name("ane_columns_h")]] kernel void ane_columns<half>(device const half *, device float *, device float *,
+ constant AneShape &, uint2, uint2);
+
// L = max_j norm[j], into state[0]. One threadgroup of 1 024.
kernel void ane_norm(device const float *norm [[buffer(0)]], device float *state [[buffer(1)]],
constant AneShape &s [[buffer(2)]], uint tid [[thread_index_in_threadgroup]]) {
@@ -70,15 +76,20 @@ kernel void ane_norm(device const float *norm [[buffer(0)]], device float *state
}
}
-// One weight tile, lifted, into its surface [kPart, nPart] fp16.
-kernel void ane_pack_weight(device const float *w [[buffer(0)]], device const float *lambda [[buffer(1)]],
+// One weight tile, lifted, into its surface [kPart, nPart] fp16. W fp32 or fp16 (`_h`).
+template <typename T>
+kernel void ane_pack_weight(device const T *w [[buffer(0)]], device const float *lambda [[buffer(1)]],
device half *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] = half(w[(ulong)(s.k0 + kk) * s.n + j] * lambda[j]);
+ tile[(ulong)kk * s.nPart + jj] = half(float(w[(ulong)(s.k0 + kk) * s.n + j]) * lambda[j]);
}
+template [[host_name("ane_pack_weight")]] kernel void ane_pack_weight<float>(device const float *, device const float *,
+ device half *, constant AneShape &, uint2);
+template [[host_name("ane_pack_weight_h")]] kernel void ane_pack_weight<half>(device const half *, device const float *,
+ device half *, constant AneShape &, uint2);
// σ_i of each Neural Engine row. One threadgroup of 256 per row.
kernel void ane_row_scales(device const float *a [[buffer(0)]], device const float *state [[buffer(1)]],
diff --git a/engine-mac/Sources/KokonEngine/QwenDiT.swift b/engine-mac/Sources/KokonEngine/QwenDiT.swift
index e1e59b5..63c0de5 100644
--- a/engine-mac/Sources/KokonEngine/QwenDiT.swift
+++ b/engine-mac/Sources/KokonEngine/QwenDiT.swift
@@ -48,6 +48,9 @@ public final class QwenDiT {
/// (`Coexecution.swift`, `AttentionSplit.swift`); nil: GPU alone. `KOKON_COEXEC=0` turns it off, `KOKON_ANE=0` /
/// `KOKON_AMX=0` one unit, `KOKON_ANE_ATTENTION=1` heads on the Neural Engine too, `KOKON_BALANCE=0` the balancing loop.
let coexecutor: Coexecutor?
+ /// **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"
private var attentions: [String: GraphAttention] = [:]
/// Seconds per phase of the last evaluation.
public private(set) var timings: [String: Double] = [:]
@@ -77,7 +80,7 @@ public final class QwenDiT {
if environment["KOKON_COEXEC"] != "0", sequence.count >= 1024 {
coexecutor = try Coexecutor(context: context, rows: QwenDiT.padded(sequence.count),
ane: environment["KOKON_ANE"] != "0", amx: environment["KOKON_AMX"] != "0",
- aneAttention: environment["KOKON_ANE_ATTENTION"] == "1")
+ aneAttention: environment["KOKON_ANE_ATTENTION"] == "1", halfWeights: halfWeights)
} else {
coexecutor = nil
}
@@ -173,6 +176,7 @@ public final class QwenDiT {
let d = QwenDiT.dim, n = sequence.count, p = sequence.prefix, s = sequence.target
let started = DispatchTime.now().uptimeNanoseconds
timings = [:]
+ castInput = nil
try prepareModulation([0, sigma])
arena.pointer(modulation).update(from: modulationCache[0]! + modulationCache[sigma]!, count: 10 * d)
timings["modulation"] = elapsed(since: started)
@@ -317,10 +321,12 @@ public final class QwenDiT {
return try file.tensor(QwenDiT.prefix + name)
}
+ /// The input the last split product cast to fp16 (slice offset, first row, k); forgotten by any kernel or attention.
+ private var castInput: (offset: Int, row: Int, k: Int)?
/// The weight unpacked (and packed for the Neural Engine) during the product before, and its reserve.
private var unpackedAhead: (name: String, reserve: Int)?
- /// `C[m, n] = A[m, k] · W` with W the file's Linear `[n, k]`, unpacked to `[k, n]` fp32 in a reserve first.
+ /// `C[m, n] = A[m, k] · W` with W the file's Linear `[n, k]`, unpacked to `[k, n]` (fp16, or fp32) in a reserve first.
/// `aRow`, `cRow`: first row of A and C in their slices. `next`: the weight of the product that follows, unpacked
/// into the other reserve and packed for the Neural Engine while the AMX and the Neural Engine run this one (the
/// GPU's ~1.8 ms per 4096 × 4096 weight otherwise ran alone between products).
@@ -338,14 +344,15 @@ public final class QwenDiT {
} else {
index = nextReserve
try gpu("dequant", commands) {
- try dequant.encode(tensor, of: file, into: arena.buffer, outOffset: reserves[index].offset, transposed: true, commands: $0)
+ try dequant.encode(tensor, of: file, into: arena.buffer, outOffset: reserves[index].offset, transposed: true,
+ output: halfWeights ? .f16 : .f32, commands: $0)
}
}
unpackedAhead = nil
nextReserve = (index + 1) % reserves.count
let reserve = reserves[index]
// The GPU's rows: all of them, or its share of a split product.
- func gpuRows(_ rows: Int) throws {
+ func gpuRows(_ rows: Int, _ half: MTLBuffer? = nil) throws {
let key = "\(rows)×\(kk)×\(nn)"
let product: MPSMatrixMultiplication
if let existing = products[key] { product = existing } else {
@@ -353,10 +360,12 @@ public final class QwenDiT {
resultRows: rows, resultColumns: nn, interiorColumns: kk, alpha: 1, beta: 0)
products[key] = product
}
- let left = MPSMatrix(buffer: arena.buffer, offset: a.offset + aRow * kk * 4,
- descriptor: MPSMatrixDescriptor(rows: rows, columns: kk, rowBytes: kk * 4, dataType: .float32))
+ let left = half.map { MPSMatrix(buffer: $0, descriptor: MPSMatrixDescriptor(rows: rows, columns: kk, rowBytes: kk * 2, dataType: .float16)) }
+ ?? MPSMatrix(buffer: arena.buffer, offset: a.offset + aRow * kk * 4,
+ descriptor: MPSMatrixDescriptor(rows: rows, columns: kk, rowBytes: kk * 4, dataType: .float32))
let right = MPSMatrix(buffer: arena.buffer, offset: reserve.offset,
- descriptor: MPSMatrixDescriptor(rows: kk, columns: nn, rowBytes: nn * 4, dataType: .float32))
+ descriptor: MPSMatrixDescriptor(rows: kk, columns: nn, rowBytes: nn * (halfWeights ? 2 : 4),
+ dataType: halfWeights ? .float16 : .float32))
let result = MPSMatrix(buffer: arena.buffer, offset: c.offset + cRow * nn * 4,
descriptor: MPSMatrixDescriptor(rows: rows, columns: nn, rowBytes: nn * 4, dataType: .float32))
try gpu(m < 512 ? "products (few rows)" : "products", commands) {
@@ -371,19 +380,23 @@ public final class QwenDiT {
if let next {
let t = try weight(next), other = nextReserve
ahead = { [self] commands in
- try dequant.encode(t, of: file, into: arena.buffer, outOffset: reserves[other].offset, transposed: true, commands: commands)
+ try dequant.encode(t, of: file, into: arena.buffer, outOffset: reserves[other].offset, transposed: true,
+ output: halfWeights ? .f16 : .f32, commands: commands)
try coexecutor.prepareWeight(next, w: operand(reserves[other], 0, t.rows), k: t.columns, n: t.rows, commands: commands)
unpackedAhead = (next, other)
}
}
+ let ready = castInput.map { $0 == (a.offset, aRow, kk) } ?? false
try coexecutor.encode(weight: name, a: operand(a, aRow, kk), w: operand(reserve, 0, nn), c: operand(c, cRow, nn),
- m: m, k: kk, n: nn, commands: commands, ahead: ahead, gpuRows: gpuRows)
+ m: m, k: kk, n: nn, commands: commands, castReady: ready, ahead: ahead, gpuRows: gpuRows)
+ castInput = c.offset == a.offset ? nil : (a.offset, aRow, kk)
} else {
try gpuRows(m)
}
}
func compute(_ name: String, commands: MTLCommandBuffer, _ body: (MTLComputeCommandEncoder) throws -> Void) throws {
+ castInput = nil
try gpu(name, commands) { commands in
let encoder = commands.makeComputeCommandEncoder()!
encoder.label = name
@@ -468,6 +481,7 @@ public final class QwenDiT {
/// 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`).
func attend(queries: Int, count: Int, keys: Int, causal: Bool, commands: MTLCommandBuffer) throws {
+ castInput = nil
let row = QwenDiT.dim * 4
if let coexecutor, !profiling, !graphAttention, !causal, coexecutor.attentionApplies(queries: count) {
func operand(_ slice: Arena.Slice, _ first: Int) -> Coexecutor.Operand {