Skip to content

Gemma 4 26B-A4B inference in ~2 GB of RAM on any M-series MacBook

Add optional Gemma 4 image support (#144)

Andrey Mikhaylovfd3c0b8be8df
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 7686e5b1..3bf08b70 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -29,6 +29,8 @@ jobs:
run: swift build -c release
- name: Run serial tests
run: Scripts/test.sh
+ - name: Check for tracked symlinks
+ run: ruby Scripts/check_tracked_symlinks.rb
- name: Check Markdown links
run: ruby Scripts/check_markdown_links.rb
- name: Check the app version against the latest release
diff --git a/.gitignore b/.gitignore
index 6d12f045..ab451b7c 100644
--- a/.gitignore
+++ b/.gitignore
@@ -41,7 +41,7 @@ Model/
# Logs / scratch
*.log
benchmark-results/
-scratch/
+/scratch
tmp/
# Python
diff --git a/AGENTS.md b/AGENTS.md
index f09268d6..2a30e5f4 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -62,3 +62,24 @@ is the runtime KV format. The HUD shows generation rate, token count, and
decode-service memory; Last run also shows time to first token and I/O. Build
the app with its sibling `TurboFieldfareDecodeService`; it never loads a second
in-process model. See [README](README.md) and [Runtime controls](docs/RUNTIME_CONTROLS.md).
+
+## Images
+
+Image support is an optional `<name>.vision.gturbo` companion pack that sits
+beside the text model. Without it the text runtime behaves exactly as before.
+
+```bash
+swift run -c release TurboFieldfareRepack \
+ --vision-output scratch/gemma4.vision.gturbo \
+ --text-model scratch/gemma4.gturbo
+```
+
+The model-free suites cover preprocessing, the tower kernels, the companion
+format, the installer transaction, prompt rendering, and the server ingress.
+Cases that need a real installed pack skip themselves when
+`scratch/gemma4.gturbo` and its companion are missing, so a checkout without a
+model still runs green.
+
+Keep the image path fail-closed. If the pack is missing or invalid, say image
+support is unavailable. Never accept an image and then answer as though it had
+not been sent.
diff --git a/Package.swift b/Package.swift
index 6b8be2b5..127f8138 100644
--- a/Package.swift
+++ b/Package.swift
@@ -127,7 +127,8 @@ let package = Package(
"TurboFieldfareCLICore",
.product(name: "Hub", package: "swift-transformers"),
],
- path: "Tests/TurboFieldfare/Core"
+ path: "Tests/TurboFieldfare/Core",
+ resources: [.copy("Runtime/Vision/Fixtures/images")]
),
.testTarget(
name: "TurboFieldfareRepackTests",
diff --git a/README.md b/README.md
index 41261e18..d26fac32 100644
--- a/README.md
+++ b/README.md
@@ -67,7 +67,7 @@ your prompt, and press **Generate**.
| Model | Gemma 4 26B-A4B IT, 26B total parameters, about 3.88B active per token |
| Weights | MLX affine 4-bit, group 64; 8-bit router; 4-bit shared and routed experts |
| Memory | ~2 GB of weights and 4K KV cache |
-| Storage | About 14.3 GB for the installed text-only model |
+| Storage | About 14.3 GB for the text model, plus about 1.1 GB for the optional image pack |
| Hardware | Apple Silicon Mac; 8 GB of RAM |
| Platform | macOS 26, Metal 4, Swift 6.2 |
| M2 measured decode | [5.1-6.3 tok/s](docs/BENCHMARKS.md#m2-measured-decode) on an 8 GB M2 MacBook Air |
@@ -117,11 +117,21 @@ Generation defaults to temperature `0.2`, Top-K `64`, and Top-P `0.95`. Set
temperature to `0` for deterministic greedy output. The model can still repeat
itself or give incorrect answers, so check important results.
-TurboFieldfare is text-only. The app and CLI support user and model messages
-plus optional system guidance; they do not expose or execute tools. The
-loopback server accepts function-tool declarations and returns
-model-produced tool calls for the client to authorize and execute. Images,
-audio, and video are not supported.
+The app and CLI support user and model messages plus optional system guidance;
+they do not expose or execute tools. The loopback server accepts function-tool
+declarations and returns model-produced tool calls for the client to authorize
+and execute. Audio and video are not supported.
+
+### Images
+
+Images are supported through a vision tower, which installs as a companion
+pack beside the text model. Install it once and the app, CLI, and server all
+accept images. Without it they tell you image support is unavailable, and the
+text runtime is untouched. The image tower requires an M2 or newer Apple
+Silicon Mac; text-only inference remains available on M1.
+
+[System design](docs/SYSTEM_DESIGN.md#images) covers how the tower runs and
+what it costs on an 8 GB machine.
### Mac app
@@ -206,6 +216,40 @@ swift run -c release TurboFieldfareRepack \
--input-gturbo scratch/gemma4.gturbo
```
+#### Install image support
+
+The companion pack installs beside the text model:
+
+```bash
+swift run -c release TurboFieldfareRepack \
+ --vision-output scratch/gemma4.vision.gturbo \
+ --text-model scratch/gemma4.gturbo
+```
+
+The pack adds about 1.1 GB. Verify it with `--verify-vision-install`, remove an
+installed one with `--remove-vision-install`, and drop a cancelled download with
+`--discard-partial --vision-output <dir>`. A cancelled transfer can also be
+continued with `--resume`. The Mac app installs the same pack from its
+**Image Support** section.
+
+#### Send an image
+
+```bash
+swift run -c release TurboFieldfareCLI \
+ --model scratch/gemma4.gturbo \
+ --chat-prompt "What is in this picture?" \
+ --image photo.jpg
+```
+
+`--image` is repeatable and requires `--chat-prompt`; it cannot be combined
+with `--prompt` or `--messages-file`. Without the companion pack the run stops
+and says image support is unavailable.
+
+A multi-turn conversation carries its images inside the messages file instead,
+as `image_file` parts in any user message; `--image` covers the single-turn
+case only. Either route needs at least 16 expert-cache slots, because an image
+prompt always prefills chunked.
+
#### Instruction chat
Put chat messages in a JSON array and pass it with `--messages-file`:
@@ -302,7 +346,7 @@ correctness invariants.
TurboFieldfare currently includes:
- Remote streaming repack into the `.gturbo` model format
-- Instruction-tuned Gemma 4 26B-A4B with verified text-only chat formatting
+- Instruction-tuned Gemma 4 26B-A4B with verified chat formatting
- 4-bit MLX affine embedding, attention, shared-expert, and routed-expert
weights, with an 8-bit router
- Custom Metal kernels for quantized GEMV, attention, MoE, normalization,
@@ -315,9 +359,14 @@ TurboFieldfare currently includes:
- A Swift library, streaming installer, command-line interface, loopback
OpenAI-compatible server, and native SwiftUI/AppKit Mac app with a one-shot
local decode service
-
-Current scope is text-only inference from the pinned Gemma 4 26B-A4B
-instruction checkpoint on Apple Silicon Macs with at least 8 GB of RAM.
+- Optional image input from a separately installed companion pack: the vision
+ tower runs on bounded scratch, image rows attend in both directions inside
+ the sliding-window layers, and routed experts are released while the tower
+ runs
+
+Current scope is text input from the pinned Gemma 4 26B-A4B instruction
+checkpoint on Apple Silicon Macs with at least 8 GB of RAM, plus image input
+on M2 or newer Macs. Audio and video are out of scope.
### Future work
diff --git a/Scripts/check_app_version.rb b/Scripts/check_app_version.rb
index 4194cf70..bd9dd32b 100755
--- a/Scripts/check_app_version.rb
+++ b/Scripts/check_app_version.rb
@@ -51,8 +51,11 @@ def published_versions
releases = JSON.parse(response.body)
return [] unless releases.is_a?(Array)
+ # Prereleases are rejected with drafts: an rc tag becoming "latest" pushes
+ # the real latest release into the floor slot, and the check then silently
+ # accepts a version two releases behind.
releases
- .reject { |release| release["draft"] }
+ .reject { |release| release["draft"] || release["prerelease"] }
.map { |release| release["tag_name"].to_s.delete_prefix("v") }
.reject(&:empty?)
.sort { |left, right| compare(right, left) }
diff --git a/Scripts/check_tracked_symlinks.rb b/Scripts/check_tracked_symlinks.rb
new file mode 100755
index 00000000..a92f4128
--- /dev/null
+++ b/Scripts/check_tracked_symlinks.rb
@@ -0,0 +1,60 @@
+#!/usr/bin/env ruby
+
+# Fails when the repository tracks a symlink.
+#
+# This exists because a tracked symlink named after an ignored directory is a
+# data-loss trap, and git gives no warning when it springs. `scratch` was once
+# committed as a symlink to its own absolute path. Checking out, merging, or
+# pulling that tree replaces the real `scratch/` directory - the converted
+# `.gturbo` models and the download cache, tens of gigabytes - with a one-line
+# symlink, exit code 0, no prompt. Recovery is a full remote repack.
+#
+# A directory-only ignore pattern cannot prevent the recurrence: `scratch/`
+# matches the directory but not a symlink of the same name, so `git add -A`
+# stages it. The anchored `/scratch` in .gitignore closes that specific hole;
+# this check closes the general one, for any path.
+#
+# The repository has no legitimate tracked symlinks. If one is ever genuinely
+# needed, add it to ALLOWED below with the reason, so the exemption is a
+# deliberate edit rather than a silent pass.
+
+ROOT = File.expand_path("..", __dir__)
+
+ALLOWED = {}.freeze
+
+SYMLINK_MODE = "120000".freeze
+
+entries = `git -C #{ROOT} ls-files -s -z`
+abort "could not read the git index" unless $?.success?
+
+offenders = entries.split("\0").map do |entry|
+ mode, rest = entry.split(" ", 2)
+ next nil unless mode == SYMLINK_MODE
+
+ path = rest.split("\t", 2).last
+ next nil if ALLOWED.key?(path)
+
+ target = `git -C #{ROOT} show :#{path}`.strip
+ [path, target]
+end.compact
+
+if offenders.empty?
+ puts "no tracked symlinks"
+ exit 0
+end
+
+listing = offenders.map { |path, target| " #{path} -> #{target}" }.join("\n")
+abort <<~MESSAGE
+ tracked symlink(s) found:
+
+ #{listing}
+
+ A tracked symlink whose name collides with a real local directory is deleted
+ without warning on checkout, merge, or pull. Untrack it with
+
+ git rm --cached <path>
+
+ and make sure .gitignore matches the name itself, not just its children:
+ an anchored `/name` covers the directory, its contents, and a symlink of the
+ same name, while `name/` covers only the directory.
+MESSAGE
diff --git a/Sources/TurboFieldfare/Infrastructure/Metal/MetalContext.swift b/Sources/TurboFieldfare/Infrastructure/Metal/MetalContext.swift
index 2151b89e..1eea8155 100644
--- a/Sources/TurboFieldfare/Infrastructure/Metal/MetalContext.swift
+++ b/Sources/TurboFieldfare/Infrastructure/Metal/MetalContext.swift
@@ -82,6 +82,7 @@ public final class MetalContext: @unchecked Sendable {
"utility",
"fused",
"prefill",
+ "vision",
]
/// Bundle locations for runtime shader modules.
@@ -97,6 +98,9 @@ public final class MetalContext: @unchecked Sendable {
"rope": "Metal/Primitives",
"tensorops": "Metal/TensorCore",
"utility": "Metal/Primitives",
+ "vision": "Metal/Vision",
+ "vision_register_gemm": "Metal/Vision",
+ "vision_resize": "Metal/Vision",
]
private static func shaderURL(module: String) -> URL? {
@@ -124,21 +128,50 @@ public final class MetalContext: @unchecked Sendable {
}
}
- /// Compile a shader module separately from the shared runtime library.
- public static func moduleLibrary(device: MTLDevice, module: String) throws -> MTLLibrary {
+ /// Compile one shader module into its own library, leaving the shared
+ /// runtime library untouched.
+ ///
+ /// Cached per device, module, math mode and source variant: libraries are
+ /// immutable, and
+ /// one `VisionRuntime` init otherwise compiles the identical tensorops
+ /// source three times (linear, attention, projector) on every load.
+ public static func privateLibrary(device: MTLDevice, module: String,
+ mathMode: MTLMathMode? = nil,
+ includeVisionTensorOps: Bool = false) throws
+ -> MTLLibrary {
+ let key = "\(ObjectIdentifier(device).hashValue)#\(module)"
+ + "#\(mathMode?.rawValue ?? -1)#\(includeVisionTensorOps)"
+ privateLibraryLock.lock()
+ defer { privateLibraryLock.unlock() }
+ if let cached = privateLibraryCache[key] {
+ return cached
+ }
guard let url = shaderURL(module: module) else {
throw MetalError.missingShaderResource(module)
}
let src = try String(contentsOf: url, encoding: .utf8)
let opts = MTLCompileOptions()
opts.languageVersion = .version4_0
+ if let mathMode {
+ opts.mathMode = mathMode
+ }
+ if includeVisionTensorOps {
+ opts.preprocessorMacros = [
+ "TURBO_FIELDFARE_VISION_TENSOROPS": NSNumber(value: true)
+ ]
+ }
do {
- return try device.makeLibrary(source: src, options: opts)
+ let library = try device.makeLibrary(source: src, options: opts)
+ privateLibraryCache[key] = library
+ return library
} catch {
throw MetalError.libraryCompileFailed("\(error)")
}
}
+ private static let privateLibraryLock = NSLock()
+ private static nonisolated(unsafe) var privateLibraryCache: [String: MTLLibrary] = [:]
+
public func pipeline(_ name: String) throws -> MTLComputePipelineState {
try pipeline(name, constants: [])
}
diff --git a/Sources/TurboFieldfare/Infrastructure/ModelIO/GTurboModelDirectory.swift b/Sources/TurboFieldfare/Infrastructure/ModelIO/GTurboModelDirectory.swift
index 7984fcee..663d177b 100644
--- a/Sources/TurboFieldfare/Infrastructure/ModelIO/GTurboModelDirectory.swift
+++ b/Sources/TurboFieldfare/Infrastructure/ModelIO/GTurboModelDirectory.swift
@@ -108,4 +108,42 @@ package final class GTurboModelDirectory {
}
return ModelError.posixFailed(call: "openat(\(relativePath))", errno: errno)
}
+
+ package func basenames() throws -> Set<String> {
+ let duplicate = fcntl(rootFD, F_DUPFD_CLOEXEC, 0)
+ guard duplicate >= 0 else {
+ throw ModelError.posixFailed(call: "fcntl(F_DUPFD_CLOEXEC, model root)", errno: errno)
+ }
+ guard let directory = fdopendir(duplicate) else {
+ let savedErrno = errno
+ close(duplicate)
+ throw ModelError.posixFailed(call: "fdopendir(model root)", errno: savedErrno)
+ }
+ defer { closedir(directory) }
+ var names = Set<String>()
+ // The duplicate shares its offset with the retained descriptor, and the
+ // previous enumeration consumed it, so without this a second call
+ // returns nothing and a valid directory reads as having no entries.
+ rewinddir(directory)
+ // Cleared immediately before each `readdir`, not once before the loop:
+ // POSIX only promises `errno` is meaningful after a failure, and both
+ // `rewinddir` and the allocation inside the loop may set it on success.
+ // A stray value made an intact directory throw, which the vision pack
+ // reader turns into "image support is unavailable".
+ errno = 0
+ while let entry = readdir(directory) {
+ let name = withUnsafePointer(to: &entry.pointee.d_name) {
+ $0.withMemoryRebound(to: CChar.self, capacity: Int(MAXNAMLEN) + 1) {
+ String(cString: $0)
+ }
+ }
+ if name != "." && name != ".." { names.insert(name) }
+ errno = 0
+ }
+ guard errno == 0 else {
+ throw ModelError.posixFailed(call: "readdir(model root)", errno: errno)
+ }
+ return names
+ }
+
}
diff --git a/Sources/TurboFieldfare/Infrastructure/ModelIO/ResidentBuffer.swift b/Sources/TurboFieldfare/Infrastructure/ModelIO/ResidentBuffer.swift
index cc3c7308..1a7a47e2 100644
--- a/Sources/TurboFieldfare/Infrastructure/ModelIO/ResidentBuffer.swift
+++ b/Sources/TurboFieldfare/Infrastructure/ModelIO/ResidentBuffer.swift
@@ -7,6 +7,8 @@ import Metal
/// inside `buffer`.
final class ResidentBuffer {
let buffer: MTLBuffer
+ let residentSize: UInt64
+ let mappedLength: Int
/// `mmap` the page-aligned window covering `[fileOffset, fileOffset + residentSize)`
/// inside the file at `fileURL`. The wrapped `MTLBuffer` starts at the
@@ -73,5 +75,7 @@ final class ResidentBuffer {
}
self.buffer = buf
+ self.residentSize = residentSize
+ self.mappedLength = mappedLen
}
}
diff --git a/Sources/TurboFieldfare/Infrastructure/Streaming/PreadExpertStreamer.swift b/Sources/TurboFieldfare/Infrastructure/Streaming/PreadExpertStreamer.swift
index 45ef0998..cdd2ee6a 100644
--- a/Sources/TurboFieldfare/Infrastructure/Streaming/PreadExpertStreamer.swift
+++ b/Sources/TurboFieldfare/Infrastructure/Streaming/PreadExpertStreamer.swift
@@ -60,6 +60,7 @@ public final class PreadExpertStreamer: @unchecked Sendable {
public let layout: StreamLayout
public let slotCount: Int
+ private let slotAllocationSize: Int
public let cachePolicy: ExpertCachePolicy
private let fd: Int32
@@ -127,6 +128,7 @@ public final class PreadExpertStreamer: @unchecked Sendable {
}
let allocationSize = ((Int(layout.expertStride) + pageSize - 1) / pageSize) * pageSize
+ self.slotAllocationSize = allocationSize
var pointers: [UnsafeMutableRawPointer] = []
var buffers: [MTLBuffer] = []
pointers.reserveCapacity(slotCount)
@@ -411,4 +413,11 @@ public final class PreadExpertStreamer: @unchecked Sendable {
filled += readCount
}
}
+
+ /// Model-derived CPU-side scratch owned by this streamer: its aligned
+ /// slot allocation. Diagnostic metadata for residency reporting, not an
+ /// ownership or lifetime API.
+ public var diagnosticSlotScratchBytes: UInt64 {
+ UInt64(slotCount) * UInt64(slotAllocationSize)
+ }
}
diff --git a/Sources/TurboFieldfare/Kernels/Attention/PrefillAttention.swift b/Sources/TurboFieldfare/Kernels/Attention/PrefillAttention.swift
index 3afa3bf2..0f0f4d7d 100644
--- a/Sources/TurboFieldfare/Kernels/Attention/PrefillAttention.swift
+++ b/Sources/TurboFieldfare/Kernels/Attention/PrefillAttention.swift
@@ -1,6 +1,11 @@
import Foundation
import Metal
+enum PrefillAttentionLayerKind: Sendable, Equatable {
+ case full
+ case slidingWindow
+}
+
struct PrefillAttentionParams: Sendable, Equatable {
var startPosition: UInt32
var queryCount: UInt32
@@ -13,6 +18,8 @@ struct PrefillAttentionParams: Sendable, Equatable {
var qTokenStrideElements: UInt32
var oTokenStrideElements: UInt32
var scale: Float
+ var bidirectionalBlockStart: UInt32
+ var bidirectionalBlockEnd: UInt32
init(startPosition: UInt32,
queryCount: UInt32,
@@ -24,7 +31,9 @@ struct PrefillAttentionParams: Sendable, Equatable {
kvTokenStrideElements: UInt32,
qTokenStrideElements: UInt32,
oTokenStrideElements: UInt32,
- scale: Float) {
+ scale: Float,
+ bidirectionalBlockStart: UInt32 = 0,
+ bidirectionalBlockEnd: UInt32 = 0) {
self.startPosition = startPosition
self.queryCount = queryCount
self.headDim = headDim
@@ -36,6 +45,8 @@ struct PrefillAttentionParams: Sendable, Equatable {
self.qTokenStrideElements = qTokenStrideElements
self.oTokenStrideElements = oTokenStrideElements
self.scale = scale
+ self.bidirectionalBlockStart = bidirectionalBlockStart
+ self.bidirectionalBlockEnd = bidirectionalBlockEnd
}
}
@@ -43,11 +54,13 @@ struct PrefillAttentionParams: Sendable, Equatable {
final class PrefillAttention {
private let context: MetalContext
private let psoCausalTiled: MTLComputePipelineState
+ private let psoParamsSmoke: MTLComputePipelineState
private let psoFullTensorOps2DValidityV2: MTLComputePipelineState?
init(context: MetalContext) throws {
self.context = context
self.psoCausalTiled = try context.pipeline("attention_prefill_causal_tiled")
+ self.psoParamsSmoke = try context.pipeline("prefill_attention_params_smoke")
self.psoFullTensorOps2DValidityV2 = context.device.supportsFamily(.apple10)
? try? context.pipeline("attention_prefill_full_tensorops_2d_validity_v2")
: nil
@@ -60,8 +73,17 @@ final class PrefillAttention {
out: MTLBuffer, outOffset: Int = 0,
params: PrefillAttentionParams,
kvRingCapacity: UInt32 = 0,
+ layerKind: PrefillAttentionLayerKind = .full,
path: RuntimePrefillAttentionPath = .causalTiled) {
- validate(params)
+ var effectiveParams = params
+ // Only sliding-window layers make an image block bidirectional;
+ // full-attention layers stay causal. Zeroed here as well as at the
+ // call site so a caller cannot widen visibility by mistake.
+ if layerKind == .full {
+ effectiveParams.bidirectionalBlockStart = 0
+ effectiveParams.bidirectionalBlockEnd = 0
+ }
+ validate(effectiveParams)
let requestsTensorOps = path == .fullTensorOps2DPreferred
|| path == .fullTensorOps2DValidityV2
@@ -70,10 +92,10 @@ final class PrefillAttention {
// shape for sliding attention must add a full-visibility check here.
let tensorOpsShape = requestsTensorOps
&& kvRingCapacity == 0
- && params.headDim == 512
- && params.numQHeads == 16
- && params.numKVHeads == 2
- && params.scale == 1.0
+ && effectiveParams.headDim == 512
+ && effectiveParams.numQHeads == 16
+ && effectiveParams.numKVHeads == 2
+ && effectiveParams.scale == 1.0
let tensorOpsPipeline = tensorOpsShape ? psoFullTensorOps2DValidityV2 : nil
let useTensorOps = tensorOpsPipeline != nil
let pipeline: MTLComputePipelineState
@@ -87,7 +109,7 @@ final class PrefillAttention {
// fixtures must use 512/16/2 to prove that TensorOps ran.
pipeline = causalTiledPipeline(kvRingCapacity: kvRingCapacity)
}
- let headDim = Int(params.headDim)
+ let headDim = Int(effectiveParams.headDim)
let threadWidth = max(1, pipeline.threadExecutionWidth)
let threadCount = useTensorOps
? 128
@@ -101,14 +123,14 @@ final class PrefillAttention {
enc.setBuffer(k, offset: kOffset, index: 1)
enc.setBuffer(v, offset: vOffset, index: 2)
enc.setBuffer(out, offset: outOffset, index: 3)
- var p = params
+ var p = effectiveParams
enc.setBytes(&p, length: MemoryLayout<PrefillAttentionParams>.stride, index: 4)
let groups = useTensorOps
- ? MTLSize(width: Int(params.queryCount),
- height: Int(params.numQHeads) / 8,
+ ? MTLSize(width: Int(effectiveParams.queryCount),
+ height: Int(effectiveParams.numQHeads) / 8,
depth: 1)
- : MTLSize(width: Int(params.queryCount),
- height: Int(params.numQHeads),
+ : MTLSize(width: Int(effectiveParams.queryCount),
+ height: Int(effectiveParams.numQHeads),
depth: 1)
enc.dispatchThreadgroups(
groups,
@@ -132,6 +154,10 @@ final class PrefillAttention {
"KV token stride is too small")
precondition(params.startPosition + params.queryCount <= params.kvValidCount,
"kvValidCount must include all in-flight query rows")
+ precondition(params.bidirectionalBlockStart <= params.bidirectionalBlockEnd,
+ "bidirectional block range is invalid")
+ precondition(params.bidirectionalBlockEnd <= params.kvValidCount,
+ "bidirectional block exceeds valid KV rows")
}
@@ -139,6 +165,23 @@ final class PrefillAttention {
((value + multiple - 1) / multiple) * multiple
}
+
+ /// Reads every field back through the MSL struct. `PrefillAttentionParams`
+ /// is mirrored by hand in `prefill.metal`, and a field added on one side
+ /// only shifts every later field silently.
+ func encodeParamsSmoke(commandBuffer: MTLCommandBuffer,
+ params: PrefillAttentionParams,
+ out: MTLBuffer) {
+ guard let enc = commandBuffer.makeComputeCommandEncoder() else { return }
+ enc.setComputePipelineState(psoParamsSmoke)
+ var p = params
+ enc.setBytes(&p, length: MemoryLayout<PrefillAttentionParams>.stride, index: 0)
+ enc.setBuffer(out, offset: 0, index: 1)
+ enc.dispatchThreads(MTLSize(width: 13, height: 1, depth: 1),
+ threadsPerThreadgroup: MTLSize(width: 13, height: 1, depth: 1))
+ enc.endEncoding()
+ }
+
private func causalTiledPipeline(kvRingCapacity: UInt32) -> MTLComputePipelineState {
guard kvRingCapacity > 0 else { return psoCausalTiled }
do {
diff --git a/Sources/TurboFieldfare/Kernels/TensorCore/MPPPrefillInt4QMM.swift b/Sources/TurboFieldfare/Kernels/TensorCore/MPPPrefillInt4QMM.swift
index 56380155..9da5b21d 100644
--- a/Sources/TurboFieldfare/Kernels/TensorCore/MPPPrefillInt4QMM.swift
+++ b/Sources/TurboFieldfare/Kernels/TensorCore/MPPPrefillInt4QMM.swift
@@ -1,37 +1,123 @@
import Foundation
import Metal
-final class MPPPrefillInt4QMM {
- enum Path: String, Sendable {
+public final class MPPPrefillInt4QMM {
+ public enum Variant: String, Sendable {
+ case control
+ case apple10V1 = "apple10-v1"
+ case apple10BF16 = "apple10-bf16"
+ }
+
+ public enum Path: String, Sendable {
case affineThreadgroupF16 = "affine-threadgroup-f16"
- case unavailable
+ case affineThreadgroupF16Apple10V1 = "affine-threadgroup-f16-apple10-v1"
+ case affineThreadgroupBF16Apple10 = "affine-threadgroup-bf16-apple10"
+ case fallback
+ }
+
+ public struct PathMetadata: Sendable, Equatable {
+ public let path: Path
+ public let tileM: Int
+ public let tileN: Int
+ public let tileK: Int
+ public let modelDerivedCPUHeapScratchBytes: Int
+ public let expandedWeightBufferBytes: Int
+ public let threadgroupBytes: Int
+ public let cooperativeValueBytesEstimate: Int
+ public let simultaneousWeightTiles: Int
+ public let weightBufferOffsetAlignment: Int
+ public let weightBufferOffsetRemainder128: Int
+ public let fallbackCount: Int
}
- static let tileM = 64
- static let tileN = 32
- static let tileK = Quantization.groupSize
+ public static let tileM = 64
+ public static let tileN = 32
+ public static let tileK = Quantization.groupSize
+ public static let threadgroupBytes = tileN * tileK * MemoryLayout<Float16>.stride
+ public static let cooperativeValueBytesEstimate = 2 * tileM * tileN * MemoryLayout<Float>.stride
- private var pipeline: MTLComputePipelineState?
+ private let context: MetalContext
+ private var controlPSO: MTLComputePipelineState?
+ private var apple10PSO: MTLComputePipelineState?
+ private var apple10BF16PSO: MTLComputePipelineState?
+ private let variant: Variant
+ public let unavailableReason: String?
- init(context: MetalContext) {
+ public init(context: MetalContext, variant: Variant = .control) {
+ self.context = context
+ self.variant = variant
+ var controlPSO: MTLComputePipelineState?
+ var apple10PSO: MTLComputePipelineState?
+ var apple10BF16PSO: MTLComputePipelineState?
+ var unavailableReason: String?
+ let apple10FunctionName: String? = switch variant {
+ case .control:
+ nil
+ case .apple10V1:
+ "mpp_prefill_affine_threadgroup_f16_apple10_v1"
+ case .apple10BF16:
+ "mpp_prefill_affine_threadgroup_bf16_apple10_v1"
+ }
do {
- let library = try Self.compileTensorOpsLibrary(device: context.device)
- guard let function = library.makeFunction(
+ if let apple10FunctionName {
+ guard context.device.supportsFamily(.apple10) else {
+ throw NSError(
+ domain: "MPPPrefillInt4QMM",
+ code: 2,
+ userInfo: [NSLocalizedDescriptionKey:
+ "\(apple10FunctionName) needs an Apple10 GPU family device"])
+ }
+ }
+ let library = try MetalContext.privateLibrary(device: context.device, module: "tensorops")
+ guard let controlFunction = library.makeFunction(
name: "mpp_prefill_affine_threadgroup_f16") else {
- throw MetalError.missingFunction("mpp_prefill_affine_threadgroup_f16")
+ throw NSError(
+ domain: "MPPPrefillInt4QMM",
+ code: 1,
+ userInfo: [NSLocalizedDescriptionKey:
+ "mpp_prefill_affine_threadgroup_f16 symbol unavailable"])
+ }
+ controlPSO = try context.device.makeComputePipelineState(
+ function: controlFunction)
+ if let apple10FunctionName {
+ // Name the function this variant actually needs, and say when
+ // the device is the reason. The BF16 (vision projector) variant
+ // used to report the f16 symbol as missing, blaming a symbol
+ // that is present and hiding the real cause.
+ guard let apple10Function = library.makeFunction(
+ name: apple10FunctionName) else {
+ throw NSError(
+ domain: "MPPPrefillInt4QMM",
+ code: 2,
+ userInfo: [NSLocalizedDescriptionKey:
+ "\(apple10FunctionName) symbol unavailable"])
+ }
+ if variant == .apple10BF16 {
+ apple10BF16PSO = try context.device.makeComputePipelineState(
+ function: apple10Function)
+ } else {
+ apple10PSO = try context.device.makeComputePipelineState(
+ function: apple10Function)
+ }
}
- self.pipeline = try context.device.makeComputePipelineState(function: function)
} catch {
- self.pipeline = nil
+ unavailableReason = String(describing: error)
}
+ self.controlPSO = controlPSO
+ self.apple10PSO = apple10PSO
+ self.apple10BF16PSO = apple10BF16PSO
+ self.unavailableReason = unavailableReason
}
- var isAvailable: Bool {
- pipeline != nil
+ public var isAvailable: Bool {
+ controlPSO != nil && (
+ variant == .control
+ || variant == .apple10V1 && apple10PSO != nil
+ || variant == .apple10BF16 && apple10BF16PSO != nil)
}
@discardableResult
- func encode(commandBuffer: MTLCommandBuffer,
+ public func encode(commandBuffer: MTLCommandBuffer,
weights: MTLBuffer, weightsOffset: Int = 0,
scales: MTLBuffer, scalesOffset: Int = 0,
biases: MTLBuffer, biasesOffset: Int = 0,
@@ -39,22 +125,38 @@ final class MPPPrefillInt4QMM {
y: MTLBuffer, yOffset: Int = 0,
m: Int,
n: Int,
- k: Int) -> Path {
- guard m > 0,
- n > 0,
- k > 0,
- k.isMultiple(of: Self.tileK),
+ k: Int) -> PathMetadata {
+ let supportedShape = m > 0 && n > 0 && k > 0
+ && k.isMultiple(of: Self.tileK)
+ let useBF16 = variant == .apple10BF16
+ // The BF16 variant is the vision projector and has no control kernel, so
+ // a short output previously selected no pipeline at all and fell back
+ // without projecting — a 3x3 patch grid pools to a single row. The
+ // Apple10 kernels bound-check every store against M and the dispatch
+ // rounds up to a whole tile, so a partial tile is correct; the F16 path
+ // keeps its 64-row floor because the control kernel serves it better.
+ let useApple10 = variant != .control
+ && context.device.supportsFamily(.apple10)
+ && (useBF16 || m >= 64)
+ && k.isMultiple(of: 128)
+ && (useBF16 ? apple10BF16PSO != nil : apple10PSO != nil)
+ let selectedPSO = useApple10
+ ? (useBF16 ? apple10BF16PSO : apple10PSO)
+ : useBF16 ? nil : controlPSO
+ guard supportedShape,
weightsOffset >= 0,
scalesOffset.isMultiple(of: MemoryLayout<UInt16>.stride),
biasesOffset.isMultiple(of: MemoryLayout<UInt16>.stride),
xOffset.isMultiple(of: MemoryLayout<Float16>.stride),
yOffset.isMultiple(of: MemoryLayout<Float16>.stride),
- let pipeline,
+ let pso = selectedPSO,
let encoder = commandBuffer.makeComputeCommandEncoder() else {
- return .unavailable
+ return metadata(path: .fallback,
+ weightsOffset: weightsOffset,
+ fallbackCount: 1)
}
- encoder.setComputePipelineState(pipeline)
+ encoder.setComputePipelineState(pso)
encoder.setBuffer(weights, offset: weightsOffset, index: 0)
encoder.setBuffer(scales, offset: scalesOffset, index: 1)
encoder.setBuffer(biases, offset: biasesOffset, index: 2)
@@ -67,17 +169,40 @@ final class MPPPrefillInt4QMM {
encoder.setBytes(&nValue, length: MemoryLayout<UInt32>.size, index: 6)
encoder.setBytes(&kValue, length: MemoryLayout<UInt32>.size, index: 7)
encoder.dispatchThreadgroups(
- MTLSize(width: (n + Self.tileN - 1) / Self.tileN,
+ MTLSize(width: (n + (useApple10 ? 64 : Self.tileN) - 1)
+ / (useApple10 ? 64 : Self.tileN),
height: (m + Self.tileM - 1) / Self.tileM,
depth: 1),
- threadsPerThreadgroup: MTLSize(width: pipeline.threadExecutionWidth * 4,
+ threadsPerThreadgroup: MTLSize(width: pso.threadExecutionWidth * 4,
height: 1,
depth: 1))
encoder.endEncoding()
- return .affineThreadgroupF16
+ return metadata(path: useBF16 && useApple10
+ ? .affineThreadgroupBF16Apple10
+ : useApple10
+ ? .affineThreadgroupF16Apple10V1
+ : .affineThreadgroupF16,
+ weightsOffset: weightsOffset,
+ fallbackCount: variant != .control && !useApple10 ? 1 : 0)
}
- private static func compileTensorOpsLibrary(device: MTLDevice) throws -> MTLLibrary {
- try MetalContext.moduleLibrary(device: device, module: "tensorops")
+ private func metadata(path: Path,
+ weightsOffset: Int,
+ fallbackCount: Int) -> PathMetadata {
+ let apple10 = path == .affineThreadgroupF16Apple10V1
+ || path == .affineThreadgroupBF16Apple10
+ return PathMetadata(
+ path: path,
+ tileM: Self.tileM,
+ tileN: apple10 ? 64 : Self.tileN,
+ tileK: apple10 ? 128 : Self.tileK,
+ modelDerivedCPUHeapScratchBytes: 0,
+ expandedWeightBufferBytes: 0,
+ threadgroupBytes: apple10 ? 16_384 : Self.threadgroupBytes,
+ cooperativeValueBytesEstimate: apple10 ? 32_768 : Self.cooperativeValueBytesEstimate,
+ simultaneousWeightTiles: 1,
+ weightBufferOffsetAlignment: 1,
+ weightBufferOffsetRemainder128: weightsOffset % 128,
+ fallbackCount: fallbackCount)
}
}
diff --git a/Sources/TurboFieldfare/Kernels/Vision/VisionAttention.swift b/Sources/TurboFieldfare/Kernels/Vision/VisionAttention.swift
new file mode 100644
index 00000000..c7926a80
--- /dev/null
+++ b/Sources/TurboFieldfare/Kernels/Vision/VisionAttention.swift
@@ -0,0 +1,496 @@
+import Foundation
+import Metal
+
+public final class VisionAttention {
+ public enum Variant: String, Sendable {
+ case native72
+ case native72Q16
+ case mppTensorOps72
+ case mlxPadded80
+ case mlxSteel80
+ }
+
+ public static let headDimension = 72
+ public static let paddedHeadDimension = 80
+ private let pipeline: MTLComputePipelineState
+ private let mlxPipeline: MTLComputePipelineState?
+ private let padPipeline: MTLComputePipelineState?
+ private let unpadPipeline: MTLComputePipelineState?
+ private let mlxQ: MTLBuffer?
+ private let mlxK: MTLBuffer?
+ private let mlxV: MTLBuffer?
+ private let mlxOutput: MTLBuffer?
+ private let mppPadded: Bool
+ private let queryTile: Int
+ public let variant: Variant
+
+ /// True when the projections write the padded head-major layout directly and
+ /// attention writes unpadded output, so no pad or unpad dispatch runs.
+ ///
+ /// Decided once, here: the constructor is told via `allowFusedPaddedLayout`
+ /// whether the linear path can write the padded head-major store. The
+ /// runtime used to AND this flag with that capability at encode time, which
+ /// gave the decision two owners — a legal flag combination then cleared and
+ /// blit-filled fused buffers no kernel read while the requested MPP kernel
+ /// silently fell back to the native one.
+ public let usesFusedPaddedLayout: Bool
+
+ /// Softmax phase mode for the MPP kernel. `.parallel` spreads max, exp and
+ /// sum across all 128 threads and is not bit-identical; `.parallelExp` keeps
+ /// the tile sum sequential per query and is bit-identical to `.serial`.
+ public enum SoftmaxPhase: UInt32, Sendable {
+ case serial = 0
+ case parallel = 1
+ case parallelExp = 2
+ }
+
+ public let softmaxPhase: SoftmaxPhase
+ public var usesParallelSoftmax: Bool { softmaxPhase == .parallel }
+
+ /// Destination buffers for the QKV projections under the fused layout.
+ public var fusedQ: MTLBuffer? { usesFusedPaddedLayout ? mlxQ : nil }
+ public var fusedK: MTLBuffer? { usesFusedPaddedLayout ? mlxK : nil }
+ public var fusedV: MTLBuffer? { usesFusedPaddedLayout ? mlxV : nil }
+
+ public var additionalScratchBytes: Int {
+ [mlxQ, mlxK, mlxV, mlxOutput]
+ .compactMap(\.self)
+ .reduce(0) { $0 + $1.length }
+ }
+
+ /// Zeroes the padded lanes the projections never write. Called once per image;
+ /// nothing writes lanes 72 to 79 afterwards, so they stay zero across layers.
+ public func encodeClearPadding(commandBuffer: MTLCommandBuffer) {
+ guard usesFusedPaddedLayout,
+ let blit = commandBuffer.makeBlitCommandEncoder() else { return }
+ for buffer in [mlxQ, mlxK, mlxV].compactMap(\.self) {
+ blit.fill(buffer: buffer, range: 0..<buffer.length, value: 0)
+ }
+ blit.endEncoding()
+ }
+
+ /// Query rows per threadgroup in the *native* kernel, which is not always
+ /// the tile the accelerated path dispatches with. Dispatching the MPP
+ /// variant's 16 against a kernel built for 8 left the upper half of every
+ /// attention output unwritten — silently, because the fallback only runs
+ /// when the caller cannot supply the padded layout.
+ private let nativeQueryTile: Int
+
+ public init(context: MetalContext,
+ environment: [String: String] = ProcessInfo.processInfo.environment,
+ allowFusedPaddedLayout: Bool = true) throws {
+ if let path = environment["TURBO_FIELDFARE_VISION_MLX_METALLIB"] {
+ variant = .mlxSteel80
+ queryTile = 32
+ pipeline = try context.pipeline("vision_attention_online_72")
+ nativeQueryTile = 8
+ padPipeline = try context.pipeline("vision_pad_heads_72_to_80")
+ unpadPipeline = try context.pipeline("vision_unpad_heads_80_to_72")
+ let library = try context.device.makeLibrary(URL: URL(fileURLWithPath: path))
+ let constants = MTLFunctionConstantValues()
+ var disabled = false
+ for index in [200, 201, 300, 301, 302] {
+ constants.setConstantValue(
+ &disabled, type: .bool, index: index)
+ }
+ let function = try library.makeFunction(
+ name: "steel_attention_bfloat16_bq32_bk32_bd80_wm4_wn1_maskbfloat16",
+ constantValues: constants)
+ mlxPipeline = try context.device.makeComputePipelineState(function: function)
+ let paddedBytes = 2_520 * 16 * 80 * MemoryLayout<UInt16>.stride
+ mlxQ = try Self.makePrivateBuffer(device: context.device, bytes: paddedBytes)
+ mlxK = try Self.makePrivateBuffer(device: context.device, bytes: paddedBytes)
+ mlxV = try Self.makePrivateBuffer(device: context.device, bytes: paddedBytes)
+ mlxOutput = try Self.makePrivateBuffer(device: context.device, bytes: paddedBytes)
+ mppPadded = false
+ usesFusedPaddedLayout = false
+ softmaxPhase = .serial
+ } else if environment["TURBO_FIELDFARE_VISION_ATTENTION_PAD80"] == "1" {
+ variant = .mlxPadded80
+ queryTile = 8
+ pipeline = try context.pipeline("vision_attention_online_80")
+ nativeQueryTile = 8
+ mlxPipeline = nil
+ padPipeline = nil
+ unpadPipeline = nil
+ mlxQ = nil
+ mlxK = nil
+ mlxV = nil
+ mlxOutput = nil
+ mppPadded = false
+ usesFusedPaddedLayout = false
+ softmaxPhase = .serial
+ } else if environment["TURBO_FIELDFARE_VISION_ATTENTION_MPP"] == "1" {
+ variant = .mppTensorOps72
+ queryTile = 16
+ let library = try MetalContext.privateLibrary(
+ device: context.device, module: "tensorops",
+ includeVisionTensorOps: true)
+ let pv80 = environment[
+ "TURBO_FIELDFARE_VISION_ATTENTION_PV80"] == "1"
+ guard let function = library.makeFunction(
+ name: pv80
+ ? "mpp_vision_attention_bf16_pv80"
+ : "mpp_vision_attention_bf16") else {
+ throw MetalError.missingFunction("mpp_vision_attention_bf16")
+ }
+ pipeline = try context.pipeline("vision_attention_online_72")
+ nativeQueryTile = 8
+ mlxPipeline = try context.device.makeComputePipelineState(function: function)
+ // When the linear path cannot write the padded head-major store the
+ // MPP kernel still runs, through the pad/unpad roundtrip, instead
+ // of silently degrading to the native kernel while `variant`
+ // reported otherwise.
+ let fused = allowFusedPaddedLayout
+ && environment["TURBO_FIELDFARE_VISION_PAD_ROUNDTRIP"] != "1"
+ usesFusedPaddedLayout = fused
+ padPipeline = fused
+ ? nil : try context.pipeline("vision_pad_heads_72_to_80")
+ unpadPipeline = fused
+ ? nil : try context.pipeline("vision_unpad_heads_80_to_72")
+ // The fused layout is addressed by padded GEMM rows, not patch rows.
+ let maximumRows = fused
+ ? Self.paddedRowCount(VisionConfig().maximumPatches)
+ : VisionConfig().maximumPatches
+ let paddedBytes = maximumRows * 16 * Self.paddedHeadDimension
+ * MemoryLayout<UInt16>.stride
+ mlxQ = try Self.makePrivateBuffer(device: context.device, bytes: paddedBytes)
+ mlxK = try Self.makePrivateBuffer(device: context.device, bytes: paddedBytes)
+ mlxV = try Self.makePrivateBuffer(device: context.device, bytes: paddedBytes)
+ mlxOutput = fused
+ ? nil
+ : try Self.makePrivateBuffer(device: context.device, bytes: paddedBytes)
+ mppPadded = true
+ // parallelExp is the default: bit-identical to the serial phase and
+ // measurably faster. SERIAL_SOFTMAX=1 is the rollback.
+ if environment["TURBO_FIELDFARE_VISION_ATTENTION_PARALLEL_SOFTMAX"] == "1" {
+ softmaxPhase = .parallel
+ } else if environment[
+ "TURBO_FIELDFARE_VISION_ATTENTION_SERIAL_SOFTMAX"] == "1" {
+ softmaxPhase = .serial
+ } else {
+ softmaxPhase = .parallelExp
+ }
+ } else if environment["TURBO_FIELDFARE_VISION_ATTENTION_Q8"] == "1" {
+ variant = .native72
+ queryTile = 8
+ pipeline = try context.pipeline("vision_attention_online_72")
+ nativeQueryTile = 8
+ mlxPipeline = nil
+ padPipeline = nil
+ unpadPipeline = nil
+ mlxQ = nil
+ mlxK = nil
+ mlxV = nil
+ mlxOutput = nil
+ mppPadded = false
+ usesFusedPaddedLayout = false
+ softmaxPhase = .serial
+ } else {
+ variant = .native72Q16
+ queryTile = 16
+ pipeline = try context.pipeline("vision_attention_online_72_q16")
+ nativeQueryTile = 16
+ mlxPipeline = nil
+ padPipeline = nil
+ unpadPipeline = nil
+ mlxQ = nil
+ mlxK = nil
+ mlxV = nil
+ mlxOutput = nil
+ mppPadded = false
+ usesFusedPaddedLayout = false
+ softmaxPhase = .serial
+ }
+ }
+
+ package static func paddedRowCount(_ rows: Int) -> Int {
+ ((rows + 63) / 64) * 64
+ }
+
+ /// Phases of the padded attention path. Non-padded variants report `.core` only.
+ public enum Phase: String, Sendable {
+ case pad
+ case core
+ case unpad
+ }
+
+ public func encode(commandBuffer: MTLCommandBuffer,
+ q: MTLBuffer, k: MTLBuffer, v: MTLBuffer,
+ output: MTLBuffer,
+ sequenceLength: Int, numHeads: Int = 16,
+ inputRowStride: Int = 0) {
+ encodePhased(q: q, k: k, v: v, output: output,
+ sequenceLength: sequenceLength, numHeads: numHeads,
+ inputRowStride: inputRowStride) { _, body in
+ body(commandBuffer)
+ }
+ }
+
+ /// Encodes attention one phase at a time, letting the caller choose the command
+ /// buffer per phase. `encode` routes every phase to a single buffer; the stage
+ /// profiler gives each phase its own buffer to attribute pad/core/unpad time.
+ /// Under the fused layout only `.core` runs.
+ public func encodePhased(
+ q: MTLBuffer, k: MTLBuffer, v: MTLBuffer, output: MTLBuffer,
+ sequenceLength: Int, numHeads: Int = 16,
+ inputRowStride: Int = 0,
+ run: (Phase, (MTLCommandBuffer) -> Void) -> Void
+ ) {
+ precondition(sequenceLength > 0 && numHeads > 0)
+ // The stride is the caller's confirmation that Q/K/V really are in the
+ // padded head-major store this object committed to at construction
+ // (via `allowFusedPaddedLayout`, which carries the linear path's
+ // capability). Taking this branch on `usesFusedPaddedLayout` alone
+ // would read a row-major call as 80-stride head-major — a precondition
+ // failure, and silent garbage under -Ounchecked — so stride 0 still
+ // routes to the native kernel as a last-resort fallback.
+ if usesFusedPaddedLayout, inputRowStride > 0, let mlxPipeline {
+ precondition(
+ inputRowStride >= sequenceLength,
+ "the fused layout reads head-major padded Q/K/V and needs their row stride")
+ run(.core) { commandBuffer in
+ encodeMPPTensorOps(
+ commandBuffer: commandBuffer,
+ sequenceLength: sequenceLength, numHeads: numHeads,
+ pipeline: mlxPipeline,
+ paddedQ: q, paddedK: k, paddedV: v,
+ paddedOutput: output,
+ inputRowStride: inputRowStride,
+ unpaddedOutputHeadDim: Self.headDimension)
+ }
+ return
+ }
+ if let mlxPipeline, let padPipeline, let unpadPipeline,
+ let mlxQ, let mlxK, let mlxV, let mlxOutput {
+ run(.pad) { commandBuffer in
+ encodePad(commandBuffer: commandBuffer, q: q, k: k, v: v,
+ sequenceLength: sequenceLength, numHeads: numHeads,
+ padPipeline: padPipeline,
+ paddedQ: mlxQ, paddedK: mlxK, paddedV: mlxV)
+ }
+ run(.core) { commandBuffer in
+ if mppPadded {
+ encodeMPPTensorOps(
+ commandBuffer: commandBuffer,
+ sequenceLength: sequenceLength, numHeads: numHeads,
+ pipeline: mlxPipeline,
+ paddedQ: mlxQ, paddedK: mlxK, paddedV: mlxV,
+ paddedOutput: mlxOutput,
+ inputRowStride: 0, unpaddedOutputHeadDim: 0)
+ } else {
+ encodeMLXSteel(
+ commandBuffer: commandBuffer,
+ sequenceLength: sequenceLength, numHeads: numHeads,
+ pipeline: mlxPipeline,
+ paddedQ: mlxQ, paddedK: mlxK, paddedV: mlxV,
+ paddedOutput: mlxOutput)
+ }
+ }
+ run(.unpad) { commandBuffer in
+ encodeUnpad(commandBuffer: commandBuffer, output: output,
+ sequenceLength: sequenceLength, numHeads: numHeads,
+ unpadPipeline: unpadPipeline, paddedOutput: mlxOutput)
+ }
+ return
+ }
+ run(.core) { commandBuffer in
+ encodeNative(commandBuffer: commandBuffer, q: q, k: k, v: v,
+ output: output,
+ sequenceLength: sequenceLength, numHeads: numHeads)
+ }
+ }
+
+ private func encodeNative(commandBuffer: MTLCommandBuffer,
+ q: MTLBuffer, k: MTLBuffer, v: MTLBuffer,
+ output: MTLBuffer,
+ sequenceLength: Int, numHeads: Int) {
+ guard let encoder = commandBuffer.makeComputeCommandEncoder() else { return }
+ encoder.setComputePipelineState(pipeline)
+ encoder.setBuffer(q, offset: 0, index: 0)
+ encoder.setBuffer(k, offset: 0, index: 1)
+ encoder.setBuffer(v, offset: 0, index: 2)
+ encoder.setBuffer(output, offset: 0, index: 3)
+ var length = UInt32(sequenceLength)
+ var heads = UInt32(numHeads)
+ encoder.setBytes(&length, length: MemoryLayout<UInt32>.size, index: 4)
+ encoder.setBytes(&heads, length: MemoryLayout<UInt32>.size, index: 5)
+ encoder.dispatchThreadgroups(
+ MTLSize(width: (sequenceLength + nativeQueryTile - 1) / nativeQueryTile,
+ height: numHeads, depth: 1),
+ threadsPerThreadgroup: MTLSize(width: 128, height: 1, depth: 1))
+ encoder.endEncoding()
+ }
+
+ private func encodePad(
+ commandBuffer: MTLCommandBuffer,
+ q: MTLBuffer, k: MTLBuffer, v: MTLBuffer,
+ sequenceLength: Int, numHeads: Int,
+ padPipeline: MTLComputePipelineState,
+ paddedQ: MTLBuffer, paddedK: MTLBuffer, paddedV: MTLBuffer
+ ) {
+ guard let pad = commandBuffer.makeComputeCommandEncoder() else { return }
+ pad.setComputePipelineState(padPipeline)
+ pad.setBuffer(q, offset: 0, index: 0)
+ pad.setBuffer(k, offset: 0, index: 1)
+ pad.setBuffer(v, offset: 0, index: 2)
+ pad.setBuffer(paddedQ, offset: 0, index: 3)
+ pad.setBuffer(paddedK, offset: 0, index: 4)
+ pad.setBuffer(paddedV, offset: 0, index: 5)
+ var rows = UInt32(sequenceLength), heads = UInt32(numHeads)
+ pad.setBytes(&rows, length: 4, index: 6)
+ pad.setBytes(&heads, length: 4, index: 7)
+ pad.dispatchThreads(
+ MTLSize(width: sequenceLength * numHeads * 80, height: 1, depth: 1),
+ threadsPerThreadgroup: MTLSize(width: 256, height: 1, depth: 1))
+ pad.endEncoding()
+ }
+
+ private func encodeUnpad(
+ commandBuffer: MTLCommandBuffer,
+ output: MTLBuffer,
+ sequenceLength: Int, numHeads: Int,
+ unpadPipeline: MTLComputePipelineState,
+ paddedOutput: MTLBuffer
+ ) {
+ guard let unpad = commandBuffer.makeComputeCommandEncoder() else { return }
+ var rows = UInt32(sequenceLength), heads = UInt32(numHeads)
+ unpad.setComputePipelineState(unpadPipeline)
+ unpad.setBuffer(paddedOutput, offset: 0, index: 0)
+ unpad.setBuffer(output, offset: 0, index: 1)
+ unpad.setBytes(&rows, length: 4, index: 2)
+ unpad.setBytes(&heads, length: 4, index: 3)
+ unpad.dispatchThreads(
+ MTLSize(width: sequenceLength * numHeads * 72, height: 1, depth: 1),
+ threadsPerThreadgroup: MTLSize(width: 256, height: 1, depth: 1))
+ unpad.endEncoding()
+ }
+
+ private func encodeMLXSteel(
+ commandBuffer: MTLCommandBuffer,
+ sequenceLength: Int, numHeads: Int,
+ pipeline: MTLComputePipelineState,
+ paddedQ: MTLBuffer, paddedK: MTLBuffer, paddedV: MTLBuffer,
+ paddedOutput: MTLBuffer
+ ) {
+ var parameters = MLXAttentionParameters(
+ sequenceLength: sequenceLength, heads: numHeads)
+ guard let encoder = commandBuffer.makeComputeCommandEncoder() else { return }
+ encoder.setComputePipelineState(pipeline)
+ encoder.setBuffer(paddedQ, offset: 0, index: 0)
+ encoder.setBuffer(paddedK, offset: 0, index: 1)
+ encoder.setBuffer(paddedV, offset: 0, index: 2)
+ encoder.setBuffer(paddedOutput, offset: 0, index: 3)
+ encoder.setBytes(&parameters,
+ length: MemoryLayout<MLXAttentionParameters>.stride,
+ index: 4)
+ encoder.dispatchThreadgroups(
+ MTLSize(width: (sequenceLength + 31) / 32,
+ height: numHeads, depth: 1),
+ threadsPerThreadgroup: MTLSize(width: 128, height: 1, depth: 1))
+ encoder.endEncoding()
+ }
+
+ private func encodeMPPTensorOps(
+ commandBuffer: MTLCommandBuffer,
+ sequenceLength: Int, numHeads: Int,
+ pipeline: MTLComputePipelineState,
+ paddedQ: MTLBuffer, paddedK: MTLBuffer, paddedV: MTLBuffer,
+ paddedOutput: MTLBuffer,
+ inputRowStride: Int,
+ unpaddedOutputHeadDim: Int
+ ) {
+ guard let encoder = commandBuffer.makeComputeCommandEncoder() else { return }
+ var rows = UInt32(sequenceLength), heads = UInt32(numHeads)
+ var layout = VisionAttentionLayout(
+ inputRowStride: UInt32(inputRowStride),
+ unpaddedOutputHeadDim: UInt32(unpaddedOutputHeadDim),
+ parallelSoftmax: softmaxPhase.rawValue)
+ encoder.setComputePipelineState(pipeline)
+ encoder.setBuffer(paddedQ, offset: 0, index: 0)
+ encoder.setBuffer(paddedK, offset: 0, index: 1)
+ encoder.setBuffer(paddedV, offset: 0, index: 2)
+ encoder.setBuffer(paddedOutput, offset: 0, index: 3)
+ encoder.setBytes(&rows, length: 4, index: 4)
+ encoder.setBytes(&heads, length: 4, index: 5)
+ encoder.setBytes(&layout,
+ length: MemoryLayout<VisionAttentionLayout>.stride,
+ index: 6)
+ encoder.dispatchThreadgroups(
+ MTLSize(width: (sequenceLength + 15) / 16,
+ height: numHeads, depth: 1),
+ threadsPerThreadgroup: MTLSize(width: 128, height: 1, depth: 1))
+ encoder.endEncoding()
+ }
+
+ private static func makePrivateBuffer(device: MTLDevice, bytes: Int) throws -> MTLBuffer {
+ guard let buffer = device.makeBuffer(length: bytes, options: .storageModePrivate) else {
+ throw MetalError.noDevice
+ }
+ return buffer
+ }
+
+}
+
+private struct VisionAttentionLayout {
+ var inputRowStride: UInt32
+ var unpaddedOutputHeadDim: UInt32
+ var parallelSoftmax: UInt32
+}
+
+private struct MLXAttentionParameters {
+ var batch: Int32 = 1
+ var heads: Int32
+ var dimension: Int32
+ var queryLength: Int32
+ var keyLength: Int32
+ var gqaFactor: Int32 = 1
+ var scale: Float = 1
+ var queryBlocks: Int32
+ var keyBlocks: Int32
+ var alignedQueryBlocks: Int32
+ var alignedKeyBlocks: Int32
+ var queryRemainder: Int32
+ var keyRemainder: Int32
+ var queryOffset: Int32 = 0
+ var queryStrideBatch: Int64
+ var queryStrideHead: Int64
+ var queryStrideSequence: Int64
+ var keyStrideBatch: Int64
+ var keyStrideHead: Int64
+ var keyStrideSequence: Int64
+ var valueStrideBatch: Int64
+ var valueStrideHead: Int64
+ var valueStrideSequence: Int64
+ var outputStrideBatch: Int64
+ var outputStrideHead: Int64
+ var outputStrideSequence: Int64
+
+ init(sequenceLength: Int, heads: Int) {
+ self.heads = Int32(heads)
+ self.dimension = 80
+ queryLength = Int32(sequenceLength)
+ keyLength = Int32(sequenceLength)
+ queryBlocks = Int32((sequenceLength + 31) / 32)
+ keyBlocks = queryBlocks
+ alignedQueryBlocks = Int32(sequenceLength / 32)
+ alignedKeyBlocks = alignedQueryBlocks
+ queryRemainder = Int32(sequenceLength % 32)
+ keyRemainder = queryRemainder
+ let batchStride = Int64(heads * sequenceLength * 80)
+ let headStride = Int64(sequenceLength * 80)
+ let sequenceStride: Int64 = 80
+ queryStrideBatch = batchStride
+ queryStrideHead = headStride
+ queryStrideSequence = sequenceStride
+ keyStrideBatch = batchStride
+ keyStrideHead = headStride
+ keyStrideSequence = sequenceStride
+ valueStrideBatch = batchStride
+ valueStrideHead = headStride
+ valueStrideSequence = sequenceStride
+ outputStrideBatch = batchStride
+ outputStrideHead = headStride
+ outputStrideSequence = sequenceStride
+ }
+}
diff --git a/Sources/TurboFieldfare/Kernels/Vision/VisionLinearBF16.swift b/Sources/TurboFieldfare/Kernels/Vision/VisionLinearBF16.swift
new file mode 100644
index 00000000..f53f37d7
--- /dev/null
+++ b/Sources/TurboFieldfare/Kernels/Vision/VisionLinearBF16.swift
@@ -0,0 +1,281 @@
+import Metal
+
+public final class VisionLinearBF16 {
+ private enum PathMode {
+ case disabled, all, attention, mlp
+
+ func applies(n: Int, k: Int) -> Bool {
+ switch self {
+ case .disabled: false
+ case .all: true
+ case .attention: n == 1_152 && k <= 1_152
+ case .mlp: n == 4_304 || k == 4_304
+ }
+ }
+ }
+
+ public struct Metadata: Sendable, Equatable {
+ public let tileM: Int
+ public let tileN: Int
+ public let tileK: Int
+ public let modelDerivedCPUHeapScratchBytes = 0
+ public let expandedWeightBufferBytes = 0
+
+ fileprivate init(tileM: Int, tileN: Int, tileK: Int) {
+ self.tileM = tileM
+ self.tileN = tileN
+ self.tileK = tileK
+ }
+ }
+
+ /// Head-major padded store for the QKV projections. `rowStride` is the
+ /// per-head row count of the destination; lanes in `[headDim, paddedHeadDim)`
+ /// are left untouched and must already be zero.
+ public struct PaddedHeadStore: Sendable, Equatable {
+ public let rowStride: Int
+ public let headDim: Int
+ public let paddedHeadDim: Int
+
+ public init(rowStride: Int, headDim: Int, paddedHeadDim: Int) {
+ self.rowStride = rowStride
+ self.headDim = headDim
+ self.paddedHeadDim = paddedHeadDim
+ }
+ }
+
+ private let pipeline: MTLComputePipelineState?
+ private let mlxPipelines: [Int: MTLComputePipelineState]
+ private let registerPipeline: MTLComputePipelineState?
+ private let registerGeGLUPipeline: MTLComputePipelineState?
+ private let registerMode: PathMode
+
+ /// The fused MLP epilogue exists only on the register path.
+ public func supportsFusedGeGLU(n: Int, k: Int) -> Bool {
+ registerGeGLUPipeline != nil && registerMode.applies(n: n, k: k)
+ }
+
+ /// Only the register GEMM implements the padded head-major store, so the
+ /// fused attention layout stays off whenever another linear path is selected.
+ public func supportsPaddedHeadStore(n: Int, k: Int) -> Bool {
+ registerPipeline != nil && registerMode.applies(n: n, k: k)
+ }
+
+ public init(context: MetalContext,
+ environment: [String: String] = ProcessInfo.processInfo.environment) throws {
+ let registerAttention = environment[
+ "TURBO_FIELDFARE_VISION_REGISTER_ATTENTION"] == "1"
+ let registerMLP = environment["TURBO_FIELDFARE_VISION_REGISTER_MLP"] == "1"
+ let mode: PathMode
+ if environment["TURBO_FIELDFARE_VISION_REGISTER_GEMM"] == "1"
+ || (registerAttention && registerMLP) {
+ mode = .all
+ } else if registerAttention {
+ mode = .attention
+ } else if registerMLP {
+ mode = .mlp
+ } else {
+ mode = .disabled
+ }
+ registerMode = mode
+ if mode != .disabled {
+ let library = try MetalContext.privateLibrary(
+ device: context.device, module: "vision_register_gemm")
+ guard let function = library.makeFunction(name: "tff_vision_register_gemm"),
+ let geglu = library.makeFunction(
+ name: "tff_vision_register_gemm_geglu") else {
+ throw MetalError.missingFunction("tff_vision_register_gemm")
+ }
+ registerPipeline = try context.device.makeComputePipelineState(function: function)
+ registerGeGLUPipeline = try context.device.makeComputePipelineState(
+ function: geglu)
+ } else {
+ registerPipeline = nil
+ registerGeGLUPipeline = nil
+ }
+ var loadedMLXPipelines: [Int: MTLComputePipelineState] = [:]
+ if let path = environment["TURBO_FIELDFARE_VISION_MLX_GEMM_METALLIB"] {
+ let mlxLibrary = try context.device.makeLibrary(URL: URL(fileURLWithPath: path))
+ for alignN in [false, true] {
+ for alignK in [false, true] {
+ let constants = MTLFunctionConstantValues()
+ var disabled = false
+ var enabled = true
+ constants.setConstantValue(&disabled, type: .bool, index: 10)
+ constants.setConstantValue(&disabled, type: .bool, index: 100)
+ constants.setConstantValue(&disabled, type: .bool, index: 110)
+ constants.setConstantValue(&enabled, type: .bool, index: 200)
+ var n = alignN, k = alignK
+ constants.setConstantValue(&n, type: .bool, index: 201)
+ constants.setConstantValue(&k, type: .bool, index: 202)
+ let function = try mlxLibrary.makeFunction(
+ name: "steel_gemm_fused_nax_nt_bfloat16_bfloat16_"
+ + "bm64_bn128_bk256_wm2_wn4",
+ constantValues: constants)
+ loadedMLXPipelines[
+ (alignN ? 2 : 0) | (alignK ? 1 : 0)
+ ] = try context.device.makeComputePipelineState(function: function)
+ }
+ }
+ }
+ mlxPipelines = loadedMLXPipelines
+ if mode == .all || !loadedMLXPipelines.isEmpty {
+ pipeline = nil
+ } else {
+ let library = try MetalContext.privateLibrary(
+ device: context.device, module: "tensorops",
+ includeVisionTensorOps: true)
+ guard let function = library.makeFunction(name: "mpp_vision_linear_bf16") else {
+ throw MetalError.missingFunction("mpp_vision_linear_bf16")
+ }
+ pipeline = try context.device.makeComputePipelineState(function: function)
+ }
+ }
+
+ @discardableResult
+ public func encode(commandBuffer: MTLCommandBuffer,
+ input: MTLBuffer, inputOffset: Int = 0,
+ weights: MTLBuffer, weightsOffset: Int = 0,
+ output: MTLBuffer, outputOffset: Int = 0,
+ m: Int, n: Int, k: Int,
+ paddedHeadStore: PaddedHeadStore? = nil,
+ fusesGeGLU: Bool = false) -> Metadata {
+ precondition(m > 0 && n > 0 && k > 0)
+ precondition(!(fusesGeGLU && paddedHeadStore != nil))
+ if let selected = fusesGeGLU ? registerGeGLUPipeline : registerPipeline,
+ registerMode.applies(n: n, k: k) {
+ encodeRegisterGEMM(
+ commandBuffer: commandBuffer,
+ input: input, inputOffset: inputOffset,
+ weights: weights, weightsOffset: weightsOffset,
+ output: output, outputOffset: outputOffset,
+ m: m, n: n, k: k,
+ paddedHeadStore: paddedHeadStore,
+ pipeline: selected)
+ return Metadata(tileM: 64, tileN: 128, tileK: 16)
+ }
+ precondition(!fusesGeGLU, "fused GeGLU requires the register GEMM path")
+ precondition(paddedHeadStore == nil,
+ "padded head store requires the register GEMM path")
+ if !mlxPipelines.isEmpty {
+ encodeExternalMLXGEMM(
+ commandBuffer: commandBuffer,
+ input: input, inputOffset: inputOffset,
+ weights: weights, weightsOffset: weightsOffset,
+ output: output, outputOffset: outputOffset,
+ m: m, n: n, k: k)
+ return Metadata(tileM: 64, tileN: 128, tileK: 256)
+ }
+ guard let pipeline else {
+ preconditionFailure("no vision linear path is available for this shape")
+ }
+ guard let encoder = commandBuffer.makeComputeCommandEncoder() else {
+ return Metadata(tileM: 64, tileN: 32, tileK: 64)
+ }
+ encoder.setComputePipelineState(pipeline)
+ encoder.setBuffer(input, offset: inputOffset, index: 0)
+ encoder.setBuffer(weights, offset: weightsOffset, index: 1)
+ encoder.setBuffer(output, offset: outputOffset, index: 2)
+ var rows = UInt32(m), columns = UInt32(n), inner = UInt32(k)
+ encoder.setBytes(&rows, length: 4, index: 3)
+ encoder.setBytes(&columns, length: 4, index: 4)
+ encoder.setBytes(&inner, length: 4, index: 5)
+ encoder.dispatchThreadgroups(
+ MTLSize(width: (n + 31) / 32, height: (m + 63) / 64, depth: 1),
+ threadsPerThreadgroup: MTLSize(
+ width: pipeline.threadExecutionWidth * 4, height: 1, depth: 1))
+ encoder.endEncoding()
+ return Metadata(tileM: 64, tileN: 32, tileK: 64)
+ }
+
+ private func encodeRegisterGEMM(
+ commandBuffer: MTLCommandBuffer,
+ input: MTLBuffer, inputOffset: Int,
+ weights: MTLBuffer, weightsOffset: Int,
+ output: MTLBuffer, outputOffset: Int,
+ m: Int, n: Int, k: Int,
+ paddedHeadStore: PaddedHeadStore?,
+ pipeline: MTLComputePipelineState
+ ) {
+ guard let encoder = commandBuffer.makeComputeCommandEncoder() else { return }
+ encoder.setBuffer(input, offset: inputOffset, index: 0)
+ encoder.setBuffer(weights, offset: weightsOffset, index: 1)
+ encoder.setBuffer(output, offset: outputOffset, index: 2)
+ var rows = UInt32(m), columns = UInt32(n), inner = UInt32(k)
+ encoder.setBytes(&rows, length: 4, index: 3)
+ encoder.setBytes(&columns, length: 4, index: 4)
+ encoder.setBytes(&inner, length: 4, index: 5)
+ var store = VisionGEMMPaddedStore(
+ rowStride: UInt32(paddedHeadStore?.rowStride ?? 0),
+ headDim: UInt32(paddedHeadStore?.headDim ?? 0),
+ paddedHeadDim: UInt32(paddedHeadStore?.paddedHeadDim ?? 0))
+ encoder.setBytes(&store,
+ length: MemoryLayout<VisionGEMMPaddedStore>.stride,
+ index: 6)
+ encoder.setComputePipelineState(pipeline)
+ encoder.dispatchThreadgroups(
+ MTLSize(width: (n + 127) / 128, height: (m + 63) / 64, depth: 1),
+ threadsPerThreadgroup: MTLSize(width: 256, height: 1, depth: 1))
+ encoder.endEncoding()
+ }
+
+ private func encodeExternalMLXGEMM(
+ commandBuffer: MTLCommandBuffer,
+ input: MTLBuffer, inputOffset: Int,
+ weights: MTLBuffer, weightsOffset: Int,
+ output: MTLBuffer, outputOffset: Int,
+ m: Int, n: Int, k: Int
+ ) {
+ let key = (n.isMultiple(of: 128) ? 2 : 0) | (k.isMultiple(of: 256) ? 1 : 0)
+ guard let pipeline = mlxPipelines[key],
+ let encoder = commandBuffer.makeComputeCommandEncoder() else { return }
+ let tilesN = (n + 127) / 128
+ let tilesM = (m + 63) / 64
+ var parameters = MLXGEMMParameters(
+ m: m, n: n, k: k, tilesN: tilesN, tilesM: tilesM)
+ encoder.setComputePipelineState(pipeline)
+ encoder.setBuffer(input, offset: inputOffset, index: 0)
+ encoder.setBuffer(weights, offset: weightsOffset, index: 1)
+ encoder.setBuffer(output, offset: outputOffset, index: 3)
+ encoder.setBytes(&parameters, length: MemoryLayout<MLXGEMMParameters>.stride, index: 4)
+ encoder.dispatchThreadgroups(
+ MTLSize(width: tilesN * 4, height: (tilesM + 3) / 4, depth: 1),
+ threadsPerThreadgroup: MTLSize(width: 32, height: 4, depth: 2))
+ encoder.endEncoding()
+ }
+}
+
+private struct VisionGEMMPaddedStore {
+ var rowStride: UInt32
+ var headDim: UInt32
+ var paddedHeadDim: UInt32
+}
+
+private struct MLXGEMMParameters {
+ var m: Int32
+ var n: Int32
+ var k: Int32
+ var lda: Int32
+ var ldb: Int32
+ var ldd: Int32
+ var tilesN: Int32
+ var tilesM: Int32
+ var batchStrideA: Int64 = 0
+ var batchStrideB: Int64 = 0
+ var batchStrideD: Int64
+ var swizzleLog: Int32 = 2
+ var alignedKIterations: Int32
+ var batchDimensions: Int32 = 1
+
+ init(m: Int, n: Int, k: Int, tilesN: Int, tilesM: Int) {
+ self.m = Int32(m)
+ self.n = Int32(n)
+ self.k = Int32(k)
+ lda = Int32(k)
+ ldb = Int32(k)
+ ldd = Int32(n)
+ self.tilesN = Int32(tilesN)
+ self.tilesM = Int32(tilesM)
+ batchStrideD = Int64(m * n)
+ alignedKIterations = Int32(k / 256)
+ }
+}
diff --git a/Sources/TurboFieldfare/Kernels/Vision/VisionPrimitives.swift b/Sources/TurboFieldfare/Kernels/Vision/VisionPrimitives.swift
new file mode 100644
index 00000000..2e8ec2a7
--- /dev/null
+++ b/Sources/TurboFieldfare/Kernels/Vision/VisionPrimitives.swift
@@ -0,0 +1,179 @@
+import Metal
+
+package final class VisionPrimitives {
+ private let normalize: MTLComputePipelineState
+ private let addPosition: MTLComputePipelineState
+ private let rmsnorm: MTLComputePipelineState
+ private let postnormResidual: MTLComputePipelineState
+ private let qkvNormRoPE: MTLComputePipelineState
+ private let qkvNormRoPEPadded: MTLComputePipelineState
+ private let geglu: MTLComputePipelineState
+ private let pool: MTLComputePipelineState
+ private let bfloatToHalf: MTLComputePipelineState
+
+ package init(context: MetalContext,
+ environment: [String: String] = ProcessInfo.processInfo.environment) throws {
+ normalize = try context.pipeline("vision_normalize_patches")
+ addPosition = try context.pipeline("vision_add_position")
+ if environment["TURBO_FIELDFARE_VISION_SAFE_RMS"] == "1" {
+ let library = try MetalContext.privateLibrary(
+ device: context.device, module: "vision", mathMode: .safe)
+ guard let rmsFunction = library.makeFunction(name: "vision_rmsnorm_rows"),
+ let residualFunction = library.makeFunction(
+ name: "vision_postnorm_residual") else {
+ throw MetalError.missingFunction("vision safe RMSNorm")
+ }
+ rmsnorm = try context.device.makeComputePipelineState(function: rmsFunction)
+ postnormResidual = try context.device.makeComputePipelineState(
+ function: residualFunction)
+ } else {
+ rmsnorm = try context.pipeline("vision_rmsnorm_rows")
+ postnormResidual = try context.pipeline("vision_postnorm_residual")
+ }
+ qkvNormRoPE = try context.pipeline("vision_qkv_norm_rope")
+ qkvNormRoPEPadded = try context.pipeline("vision_qkv_norm_rope_padded")
+ geglu = try context.pipeline("vision_geglu")
+ pool = try context.pipeline("vision_pool_standardize_norm")
+ bfloatToHalf = try context.pipeline("vision_bfloat_to_half")
+ }
+
+ package func encodeNormalize(commandBuffer: MTLCommandBuffer,
+ input: MTLBuffer, output: MTLBuffer,
+ rows: Int, paddedRows: Int) {
+ guard let encoder = commandBuffer.makeComputeCommandEncoder() else { return }
+ encoder.setComputePipelineState(normalize)
+ encoder.setBuffer(input, offset: 0, index: 0)
+ encoder.setBuffer(output, offset: 0, index: 1)
+ var real = UInt32(rows), padded = UInt32(paddedRows)
+ encoder.setBytes(&real, length: 4, index: 2)
+ encoder.setBytes(&padded, length: 4, index: 3)
+ dispatch1D(encoder, count: paddedRows * 768, pipeline: normalize)
+ }
+
+ package func encodeAddPosition(commandBuffer: MTLCommandBuffer,
+ hidden: MTLBuffer,
+ table: MTLBuffer, tableOffset: Int,
+ positions: MTLBuffer, rows: Int) {
+ guard let encoder = commandBuffer.makeComputeCommandEncoder() else { return }
+ encoder.setComputePipelineState(addPosition)
+ encoder.setBuffer(hidden, offset: 0, index: 0)
+ encoder.setBuffer(table, offset: tableOffset, index: 1)
+ encoder.setBuffer(positions, offset: 0, index: 2)
+ var count = UInt32(rows)
+ encoder.setBytes(&count, length: 4, index: 3)
+ dispatch1D(encoder, count: rows * 1_152, pipeline: addPosition)
+ }
+
+ package func encodeRMSNorm(commandBuffer: MTLCommandBuffer,
+ input: MTLBuffer, output: MTLBuffer,
+ weightBuffer: MTLBuffer, weightOffset: Int,
+ rows: Int, width: Int = 1_152) {
+ guard let encoder = commandBuffer.makeComputeCommandEncoder() else { return }
+ encoder.setComputePipelineState(rmsnorm)
+ encoder.setBuffer(input, offset: 0, index: 0)
+ encoder.setBuffer(weightBuffer, offset: weightOffset, index: 1)
+ encoder.setBuffer(output, offset: 0, index: 2)
+ var rowCount = UInt32(rows), dimension = UInt32(width)
+ encoder.setBytes(&rowCount, length: 4, index: 3)
+ encoder.setBytes(&dimension, length: 4, index: 4)
+ encoder.dispatchThreadgroups(MTLSize(width: rows, height: 1, depth: 1),
+ threadsPerThreadgroup: MTLSize(width: 288, height: 1, depth: 1))
+ encoder.endEncoding()
+ }
+
+ package func encodePostnormResidual(commandBuffer: MTLCommandBuffer,
+ residual: MTLBuffer, branch: MTLBuffer,
+ weightBuffer: MTLBuffer, weightOffset: Int,
+ output: MTLBuffer, rows: Int) {
+ guard let encoder = commandBuffer.makeComputeCommandEncoder() else { return }
+ encoder.setComputePipelineState(postnormResidual)
+ encoder.setBuffer(residual, offset: 0, index: 0)
+ encoder.setBuffer(branch, offset: 0, index: 1)
+ encoder.setBuffer(weightBuffer, offset: weightOffset, index: 2)
+ encoder.setBuffer(output, offset: 0, index: 3)
+ var rowCount = UInt32(rows), width: UInt32 = 1_152
+ encoder.setBytes(&rowCount, length: 4, index: 4)
+ encoder.setBytes(&width, length: 4, index: 5)
+ encoder.dispatchThreadgroups(MTLSize(width: rows, height: 1, depth: 1),
+ threadsPerThreadgroup: MTLSize(width: 288, height: 1, depth: 1))
+ encoder.endEncoding()
+ }
+
+ package func encodeQKV(commandBuffer: MTLCommandBuffer,
+ q: MTLBuffer, k: MTLBuffer, v: MTLBuffer,
+ weights: MTLBuffer, qWeightOffset: Int, kWeightOffset: Int,
+ positions: MTLBuffer, rows: Int, heads: Int,
+ paddedRowStride: Int = 0) {
+ guard let encoder = commandBuffer.makeComputeCommandEncoder() else { return }
+ let padded = paddedRowStride != 0
+ let pipeline = padded ? qkvNormRoPEPadded : qkvNormRoPE
+ encoder.setComputePipelineState(pipeline)
+ encoder.setBuffer(q, offset: 0, index: 0)
+ encoder.setBuffer(k, offset: 0, index: 1)
+ encoder.setBuffer(v, offset: 0, index: 2)
+ encoder.setBuffer(weights, offset: qWeightOffset, index: 3)
+ encoder.setBuffer(weights, offset: kWeightOffset, index: 4)
+ encoder.setBuffer(positions, offset: 0, index: 5)
+ var rowCount = UInt32(rows), headCount = UInt32(heads)
+ encoder.setBytes(&rowCount, length: 4, index: 6)
+ encoder.setBytes(&headCount, length: 4, index: 7)
+ if padded {
+ var stride = UInt32(paddedRowStride)
+ encoder.setBytes(&stride, length: 4, index: 8)
+ }
+ dispatch1D(encoder, count: rows * heads, pipeline: pipeline)
+ }
+
+ package func encodeGeGLU(commandBuffer: MTLCommandBuffer,
+ gate: MTLBuffer, up: MTLBuffer, count: Int) {
+ guard let encoder = commandBuffer.makeComputeCommandEncoder() else { return }
+ encoder.setComputePipelineState(geglu)
+ encoder.setBuffer(gate, offset: 0, index: 0)
+ encoder.setBuffer(up, offset: 0, index: 1)
+ var value = UInt32(count)
+ encoder.setBytes(&value, length: 4, index: 2)
+ dispatch1D(encoder, count: count, pipeline: geglu)
+ }
+
+ package func encodePool(commandBuffer: MTLCommandBuffer,
+ input: MTLBuffer,
+ weights: MTLBuffer,
+ stdBiasOffset: Int, stdScaleOffset: Int,
+ output: MTLBuffer,
+ patchWidth: Int, patchHeight: Int) {
+ let rows = (patchWidth / 3) * (patchHeight / 3)
+ guard let encoder = commandBuffer.makeComputeCommandEncoder() else { return }
+ encoder.setComputePipelineState(pool)
+ encoder.setBuffer(input, offset: 0, index: 0)
+ encoder.setBuffer(weights, offset: stdBiasOffset, index: 1)
+ encoder.setBuffer(weights, offset: stdScaleOffset, index: 2)
+ encoder.setBuffer(output, offset: 0, index: 3)
+ var width = UInt32(patchWidth), height = UInt32(patchHeight)
+ encoder.setBytes(&width, length: 4, index: 4)
+ encoder.setBytes(&height, length: 4, index: 5)
+ encoder.dispatchThreadgroups(MTLSize(width: rows, height: 1, depth: 1),
+ threadsPerThreadgroup: MTLSize(width: 256, height: 1, depth: 1))
+ encoder.endEncoding()
+ }
+
+ package func encodeBFloatToHalf(commandBuffer: MTLCommandBuffer,
+ input: MTLBuffer, output: MTLBuffer,
+ count: Int) {
+ guard let encoder = commandBuffer.makeComputeCommandEncoder() else { return }
+ encoder.setComputePipelineState(bfloatToHalf)
+ encoder.setBuffer(input, offset: 0, index: 0)
+ encoder.setBuffer(output, offset: 0, index: 1)
+ var value = UInt32(count)
+ encoder.setBytes(&value, length: 4, index: 2)
+ dispatch1D(encoder, count: count, pipeline: bfloatToHalf)
+ }
+
+ private func dispatch1D(_ encoder: MTLComputeCommandEncoder,
+ count: Int, pipeline: MTLComputePipelineState) {
+ let width = min(pipeline.maxTotalThreadsPerThreadgroup, 256)
+ encoder.dispatchThreads(MTLSize(width: count, height: 1, depth: 1),
+ threadsPerThreadgroup: MTLSize(width: width, height: 1, depth: 1))
+ encoder.endEncoding()
+ }
+
+}
diff --git a/Sources/TurboFieldfare/Kernels/Vision/VisionResize.swift b/Sources/TurboFieldfare/Kernels/Vision/VisionResize.swift
new file mode 100644
index 00000000..8601a390
--- /dev/null
+++ b/Sources/TurboFieldfare/Kernels/Vision/VisionResize.swift
@@ -0,0 +1,230 @@
+import Foundation
+import Metal
+
+/// GPU separable bicubic resize, byte-identical to `TorchBicubicResize`.
+///
+/// The image front-end is the one place where a wrong filter changes what the
+/// model reads: measured on a UI screenshot, letting ImageIO do the reduction
+/// instead of this filter changed the transcription, dropping whole lines of
+/// text. Doing the reduction ourselves on the CPU fixes that but costs 0.1 to
+/// 0.2 s per image, which is most of the encode budget.
+///
+/// So the same arithmetic runs here. The weights come from
+/// `TorchBicubicResize.weightTable`, so the two paths cannot drift, and the
+/// tests assert byte equality rather than a tolerance.
+public final class VisionResize {
+ private struct Params {
+ var sourceWidth: UInt32
+ var sourceHeight: UInt32
+ var destinationWidth: UInt32
+ var destinationHeight: UInt32
+ var sourceRowBytes: UInt32
+ var destinationRowBytes: UInt32
+ var tapStride: UInt32
+ var precision: Int32
+ }
+
+ private let context: MetalContext
+ private let horizontal: MTLComputePipelineState
+ private let vertical: MTLComputePipelineState
+
+ public init(context: MetalContext) throws {
+ self.context = context
+ let library = try MetalContext.privateLibrary(
+ device: context.device, module: "vision_resize")
+ guard let horizontalFunction = library.makeFunction(name: "vision_resize_horizontal"),
+ let verticalFunction = library.makeFunction(name: "vision_resize_vertical") else {
+ throw MetalError.missingFunction("vision resize")
+ }
+ horizontal = try context.device.makeComputePipelineState(function: horizontalFunction)
+ vertical = try context.device.makeComputePipelineState(function: verticalFunction)
+ }
+
+ /// Bytes this resize will hold in GPU-visible buffers, so the caller can
+ /// report a peak that includes them.
+ public func scratchBytes(
+ sourceWidth: Int, sourceHeight: Int,
+ destinationWidth: Int, destinationHeight: Int
+ ) -> Int {
+ guard sourceWidth != destinationWidth || sourceHeight != destinationHeight else {
+ return 0
+ }
+ let intermediate = sourceHeight * destinationWidth * 4
+ let output = destinationHeight * destinationWidth * 4
+ return intermediate + output
+ }
+
+ /// Resizes RGBA8 pixels. `destination` must hold
+ /// `destinationHeight * destinationRowBytes` bytes.
+ public func resize(
+ source: UnsafeRawPointer,
+ sourceWidth: Int,
+ sourceHeight: Int,
+ sourceRowBytes: Int,
+ destination: UnsafeMutableRawPointer,
+ destinationWidth: Int,
+ destinationHeight: Int,
+ destinationRowBytes: Int
+ ) throws {
+ guard sourceWidth > 0, sourceHeight > 0,
+ destinationWidth > 0, destinationHeight > 0 else { return }
+ if sourceWidth == destinationWidth && sourceHeight == destinationHeight {
+ for row in 0..<sourceHeight {
+ memcpy(destination.advanced(by: row * destinationRowBytes),
+ source.advanced(by: row * sourceRowBytes),
+ sourceWidth * 4)
+ }
+ return
+ }
+
+ let device = context.device
+ guard let sourceBuffer = device.makeBuffer(
+ bytes: source, length: sourceHeight * sourceRowBytes,
+ options: .storageModeShared) else {
+ throw MetalError.noDevice
+ }
+ try resize(sourceBuffer: sourceBuffer,
+ sourceWidth: sourceWidth, sourceHeight: sourceHeight,
+ sourceRowBytes: sourceRowBytes,
+ destination: destination,
+ destinationWidth: destinationWidth,
+ destinationHeight: destinationHeight,
+ destinationRowBytes: destinationRowBytes)
+ }
+
+ /// The same resize, reading pixels the caller already put in GPU-visible
+ /// memory.
+ ///
+ /// A native-resolution decode is the largest transient in the whole image
+ /// path — 192 MB for a 48 MP source — and copying it into a buffer doubled
+ /// that. Callers that can decode straight into an `MTLBuffer` should.
+ public func resize(
+ sourceBuffer: MTLBuffer,
+ sourceWidth: Int,
+ sourceHeight: Int,
+ sourceRowBytes: Int,
+ destination: UnsafeMutableRawPointer,
+ destinationWidth: Int,
+ destinationHeight: Int,
+ destinationRowBytes: Int
+ ) throws {
+ let device = context.device
+ let source = UnsafeRawPointer(sourceBuffer.contents())
+
+ // Horizontal first, into an intermediate that keeps every source row:
+ // the vertical pass then reads columns of the already-narrowed image,
+ // which is the cheaper order whenever the width shrinks.
+ let intermediateRowBytes = destinationWidth * 4
+ guard let intermediate = device.makeBuffer(
+ length: max(1, sourceHeight * intermediateRowBytes),
+ options: .storageModeShared),
+ let output = device.makeBuffer(
+ length: max(1, destinationHeight * destinationRowBytes),
+ options: .storageModeShared),
+ let commandBuffer = context.queue.makeCommandBuffer() else {
+ throw MetalError.noDevice
+ }
+
+ if sourceWidth != destinationWidth {
+ try encode(commandBuffer: commandBuffer,
+ pipeline: horizontal,
+ table: TorchBicubicResize.weightTable(
+ input: sourceWidth, output: destinationWidth),
+ source: sourceBuffer,
+ destination: intermediate,
+ params: Params(
+ sourceWidth: UInt32(sourceWidth),
+ sourceHeight: UInt32(sourceHeight),
+ destinationWidth: UInt32(destinationWidth),
+ destinationHeight: UInt32(sourceHeight),
+ sourceRowBytes: UInt32(sourceRowBytes),
+ destinationRowBytes: UInt32(intermediateRowBytes),
+ tapStride: 0, precision: 0),
+ gridWidth: destinationWidth,
+ gridHeight: sourceHeight)
+ } else {
+ for row in 0..<sourceHeight {
+ memcpy(intermediate.contents().advanced(by: row * intermediateRowBytes),
+ source.advanced(by: row * sourceRowBytes),
+ sourceWidth * 4)
+ }
+ }
+
+ if sourceHeight != destinationHeight {
+ try encode(commandBuffer: commandBuffer,
+ pipeline: vertical,
+ table: TorchBicubicResize.weightTable(
+ input: sourceHeight, output: destinationHeight),
+ source: intermediate,
+ destination: output,
+ params: Params(
+ sourceWidth: UInt32(destinationWidth),
+ sourceHeight: UInt32(sourceHeight),
+ destinationWidth: UInt32(destinationWidth),
+ destinationHeight: UInt32(destinationHeight),
+ sourceRowBytes: UInt32(intermediateRowBytes),
+ destinationRowBytes: UInt32(destinationRowBytes),
+ tapStride: 0, precision: 0),
+ gridWidth: destinationWidth * 4,
+ gridHeight: destinationHeight)
+ }
+
+ commandBuffer.commit()
+ commandBuffer.waitUntilCompleted()
+ try checkCommandBufferError(commandBuffer.error)
+
+ let finished = sourceHeight == destinationHeight ? intermediate : output
+ let rowBytes = sourceHeight == destinationHeight
+ ? intermediateRowBytes : destinationRowBytes
+ for row in 0..<destinationHeight {
+ memcpy(destination.advanced(by: row * destinationRowBytes),
+ finished.contents().advanced(by: row * rowBytes),
+ destinationWidth * 4)
+ }
+ }
+
+ private func encode(
+ commandBuffer: MTLCommandBuffer,
+ pipeline: MTLComputePipelineState,
+ table: TorchBicubicResize.WeightTable,
+ source: MTLBuffer,
+ destination: MTLBuffer,
+ params: Params,
+ gridWidth: Int,
+ gridHeight: Int
+ ) throws {
+ guard let encoder = commandBuffer.makeComputeCommandEncoder() else {
+ throw MetalError.noQueue
+ }
+ var params = params
+ params.tapStride = UInt32(table.tapStride)
+ params.precision = Int32(table.precision)
+
+ encoder.setComputePipelineState(pipeline)
+ encoder.setBuffer(source, offset: 0, index: 0)
+ encoder.setBuffer(destination, offset: 0, index: 1)
+ // Buffers, not `setBytes`: that path is capped at 4 KB and a 4x
+ // reduction of a 4,000-pixel axis needs about 32 KB of taps, which
+ // aborted the process rather than failing a call.
+ guard let starts = context.device.makeBuffer(
+ bytes: table.starts,
+ length: table.starts.count * MemoryLayout<Int32>.stride,
+ options: .storageModeShared),
+ let weights = context.device.makeBuffer(
+ bytes: table.weights,
+ length: table.weights.count * MemoryLayout<Int16>.stride,
+ options: .storageModeShared) else {
+ throw MetalError.noDevice
+ }
+ encoder.setBuffer(starts, offset: 0, index: 2)
+ encoder.setBuffer(weights, offset: 0, index: 3)
+ encoder.setBytes(&params, length: MemoryLayout<Params>.stride, index: 4)
+
+ let width = min(pipeline.threadExecutionWidth, gridWidth)
+ let height = max(1, min(pipeline.maxTotalThreadsPerThreadgroup / width, gridHeight))
+ encoder.dispatchThreads(
+ MTLSize(width: gridWidth, height: gridHeight, depth: 1),
+ threadsPerThreadgroup: MTLSize(width: width, height: height, depth: 1))
+ encoder.endEncoding()
+ }
+}
diff --git a/Sources/TurboFieldfare/Metal/Prefill/prefill.metal b/Sources/TurboFieldfare/Metal/Prefill/prefill.metal
index 94fd146b..f5d21a9d 100644
--- a/Sources/TurboFieldfare/Metal/Prefill/prefill.metal
+++ b/Sources/TurboFieldfare/Metal/Prefill/prefill.metal
@@ -785,8 +785,22 @@ struct PrefillAttentionParams {
uint qTokenStrideElements;
uint oTokenStrideElements;
float scale;
+ uint bidirectionalBlockStart;
+ uint bidirectionalBlockEnd;
};
+static inline uint prefill_attention_last_exclusive(
+ constant PrefillAttentionParams& p,
+ uint abs_q
+) {
+ const bool in_bidirectional_block =
+ abs_q >= p.bidirectionalBlockStart &&
+ abs_q < p.bidirectionalBlockEnd;
+ return min(
+ p.kvValidCount,
+ in_bidirectional_block ? p.bidirectionalBlockEnd : abs_q + 1u);
+}
+
static inline uint prefill_kv_slot(uint logical) {
return (is_function_constant_defined(FC_PREFILL_KV_RING_CAP) &&
FC_PREFILL_KV_RING_CAP != 0u)
@@ -794,6 +808,29 @@ static inline uint prefill_kv_slot(uint logical) {
: logical;
}
+kernel void prefill_attention_params_smoke(
+ constant PrefillAttentionParams& p [[buffer(0)]],
+ device uint* out [[buffer(1)]],
+ uint id [[thread_position_in_grid]]
+) {
+ if (id >= 13u) return;
+ switch (id) {
+ case 0u: out[id] = p.startPosition; break;
+ case 1u: out[id] = p.queryCount; break;
+ case 2u: out[id] = p.headDim; break;
+ case 3u: out[id] = p.numQHeads; break;
+ case 4u: out[id] = p.numKVHeads; break;
+ case 5u: out[id] = p.kvValidCount; break;
+ case 6u: out[id] = p.slidingWindow; break;
+ case 7u: out[id] = p.kvTokenStrideElements; break;
+ case 8u: out[id] = p.qTokenStrideElements; break;
+ case 9u: out[id] = p.oTokenStrideElements; break;
+ case 10u: out[id] = as_type<uint>(p.scale); break;
+ case 11u: out[id] = p.bidirectionalBlockStart; break;
+ default: out[id] = p.bidirectionalBlockEnd; break;
+ }
+}
+
static inline float prefill_attention_tg_sum(
float value,
uint lane,
@@ -860,7 +897,7 @@ kernel void attention_prefill_causal_tiled(
if (p.slidingWindow != 0u && abs_q + 1u > p.slidingWindow) {
first = abs_q + 1u - p.slidingWindow;
}
- const uint last_exclusive = min(p.kvValidCount, abs_q + 1u);
+ const uint last_exclusive = prefill_attention_last_exclusive(p, abs_q);
device const half* q_row = Q + t * p.qTokenStrideElements + qh * p.headDim;
float row_max = -INFINITY;
diff --git a/Sources/TurboFieldfare/Metal/TensorCore/tensorops.metal b/Sources/TurboFieldfare/Metal/TensorCore/tensorops.metal
index aea257a1..5236c70c 100644
--- a/Sources/TurboFieldfare/Metal/TensorCore/tensorops.metal
+++ b/Sources/TurboFieldfare/Metal/TensorCore/tensorops.metal
@@ -6,6 +6,7 @@ using namespace metal;
using namespace mpp::tensor_ops;
constant constexpr uint kW4A8GroupSize = 64;
+
constant constexpr int kMPPAffineTileM = 64;
constant constexpr int kMPPAffineTileN = 32;
constant constexpr int kMPPAffineTileK = 64;
@@ -90,6 +91,9 @@ kernel void mpp_prefill_affine_threadgroup_f16(
for (int element = 0; element < accumulator.get_capacity(); ++element) {
accumulator[element] += groupProduct[element];
}
+ // TensorOps does not make threadgroup-memory lifetime visible across
+ // SIMD groups; keep the next group from overwriting B while another
+ // SIMD group can still be consuming the current tile.
threadgroup_barrier(mem_flags::mem_threadgroup);
}
@@ -104,4 +108,624 @@ kernel void mpp_prefill_affine_threadgroup_f16(
}
}
+#if defined(TURBO_FIELDFARE_VISION_TENSOROPS)
+
+kernel void mpp_vision_linear_bf16(
+ device bfloat* activations [[buffer(0)]],
+ device const bfloat* weights [[buffer(1)]],
+ device bfloat* output [[buffer(2)]],
+ constant uint& M [[buffer(3)]],
+ constant uint& N [[buffer(4)]],
+ constant uint& K [[buffer(5)]],
+ uint3 tgid [[threadgroup_position_in_grid]],
+ uint3 lid3 [[thread_position_in_threadgroup]],
+ uint3 threads3 [[threads_per_threadgroup]]) {
+ constexpr int tileM = 64;
+ constexpr int tileN = 32;
+ constexpr int tileK = 64;
+ constexpr auto descriptor = matmul2d_descriptor(
+ tileM, tileN, tileK, false, true, false);
+ matmul2d<descriptor, execution_simdgroups<4>> operation;
+
+ using device_bfloat_tensor = tensor<device bfloat, dextents<int32_t, 2>, tensor_inline>;
+ using threadgroup_bfloat_tensor = tensor<threadgroup bfloat, dextents<int32_t, 2>, tensor_inline>;
+ threadgroup bfloat weightTile[tileN * tileK];
+ threadgroup_bfloat_tensor tileB(
+ weightTile,
+ dextents<int32_t, 2>(tileK, tileN),
+ array<int32_t, 2>({1, tileK}));
+ // Extent is the K that remains, not a fixed tile: MPP clips loads to the
+ // declared extents, and that clipping is the only bound. `down_proj` passes
+ // K = 4304, which is 67 tiles plus 16, so a hardcoded 64 let the tail group
+ // read past each row — currently landing inside an unexplained 64-element
+ // pad in VisionScratch rather than crashing.
+ device_bfloat_tensor firstA(
+ activations,
+ dextents<int32_t, 2>(min(int32_t(tileK), int32_t(K)), M),
+ array<int32_t, 2>({1, int32_t(K)}));
+ auto firstTileA = firstA.slice(0, int32_t(tgid.y) * tileM);
+ auto accumulator = operation.get_destination_cooperative_tensor<
+ decltype(firstTileA), decltype(tileB), float>();
+ auto groupProduct = operation.get_destination_cooperative_tensor<
+ decltype(firstTileA), decltype(tileB), float>();
+ for (int element = 0; element < accumulator.get_capacity(); ++element) {
+ accumulator[element] = 0.0f;
+ }
+
+ const uint lid = lid3.x;
+ const uint threads = threads3.x;
+ for (uint group = 0; group < (K + tileK - 1u) / tileK; ++group) {
+ for (int element = 0; element < groupProduct.get_capacity(); ++element) {
+ groupProduct[element] = 0.0f;
+ }
+ for (uint linear = lid; linear < uint(tileN * tileK); linear += threads) {
+ const uint localN = linear / uint(tileK);
+ const uint localK = linear % uint(tileK);
+ const uint globalN = tgid.x * uint(tileN) + localN;
+ const uint globalK = group * uint(tileK) + localK;
+ weightTile[linear] = globalN < N && globalK < K
+ ? weights[globalN * K + globalK] : bfloat(0.0f);
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ device_bfloat_tensor groupA(
+ activations + group * uint(tileK),
+ dextents<int32_t, 2>(
+ min(int32_t(tileK), int32_t(K) - int32_t(group) * int32_t(tileK)), M),
+ array<int32_t, 2>({1, int32_t(K)}));
+ auto tileA = groupA.slice(0, int32_t(tgid.y) * tileM);
+ operation.run(tileA, tileB, groupProduct);
+ for (int element = 0; element < accumulator.get_capacity(); ++element) {
+ accumulator[element] += groupProduct[element];
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ }
+
+ for (int element = 0; element < accumulator.get_capacity(); ++element) {
+ if (!accumulator.is_valid_element(element)) continue;
+ const auto position = accumulator.get_multidimensional_index(element);
+ const uint globalN = tgid.x * uint(tileN) + uint(position[0]);
+ const uint globalM = tgid.y * uint(tileM) + uint(position[1]);
+ if (globalM < M && globalN < N) {
+ output[globalM * N + globalN] = bfloat(accumulator[element]);
+ }
+ }
+}
+
+#endif
+
+constant constexpr int kMPPAffineApple10TileM = 64;
+constant constexpr int kMPPAffineApple10TileN = 64;
+constant constexpr int kMPPAffineApple10TileK = 128;
+
+kernel void mpp_prefill_affine_threadgroup_f16_apple10_v1(
+ device const uint8_t* packedWeights [[buffer(0)]],
+ device const bfloat* scales [[buffer(1)]],
+ device const bfloat* biases [[buffer(2)]],
+ device half* activations [[buffer(3)]],
+ device half* output [[buffer(4)]],
+ constant uint& M [[buffer(5)]],
+ constant uint& N [[buffer(6)]],
+ constant uint& K [[buffer(7)]],
+ uint3 tgid [[threadgroup_position_in_grid]],
+ uint3 lid3 [[thread_position_in_threadgroup]],
+ uint3 threads3 [[threads_per_threadgroup]]) {
+ constexpr auto descriptor = matmul2d_descriptor(
+ kMPPAffineApple10TileM, kMPPAffineApple10TileN,
+ kMPPAffineApple10TileK, false, true, false);
+ matmul2d<descriptor, execution_simdgroups<4>> operation;
+
+ using device_half_tensor = tensor<device half, dextents<int32_t, 2>, tensor_inline>;
+ using threadgroup_half_tensor = tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>;
+
+ threadgroup half weightTile[
+ kMPPAffineApple10TileN * kMPPAffineApple10TileK];
+ threadgroup_half_tensor tileB(
+ weightTile,
+ dextents<int32_t, 2>(kMPPAffineApple10TileK, kMPPAffineApple10TileN),
+ array<int32_t, 2>({1, kMPPAffineApple10TileK}));
+ device_half_tensor firstA(
+ activations,
+ dextents<int32_t, 2>(kMPPAffineApple10TileK, M),
+ array<int32_t, 2>({1, int32_t(K)}));
+ auto firstTileA = firstA.slice(
+ 0, int32_t(tgid.y) * kMPPAffineApple10TileM);
+ auto accumulator = operation.get_destination_cooperative_tensor<
+ decltype(firstTileA), decltype(tileB), float>();
+ auto groupProduct = operation.get_destination_cooperative_tensor<
+ decltype(firstTileA), decltype(tileB), float>();
+ for (int element = 0; element < accumulator.get_capacity(); ++element) {
+ accumulator[element] = 0.0f;
+ }
+
+ const uint rowBytes = K / 2u;
+ const uint groupsPerRow = K / kW4A8GroupSize;
+ const uint lid = lid3.x;
+ const uint threads = threads3.x;
+ for (uint tileKStart = 0; tileKStart < K;
+ tileKStart += uint(kMPPAffineApple10TileK)) {
+ for (int element = 0; element < groupProduct.get_capacity(); ++element) {
+ groupProduct[element] = 0.0f;
+ }
+ for (uint linear = lid;
+ linear < uint(kMPPAffineApple10TileN * kMPPAffineApple10TileK);
+ linear += threads) {
+ const uint localN = linear / uint(kMPPAffineApple10TileK);
+ const uint localK = linear % uint(kMPPAffineApple10TileK);
+ const uint globalN = tgid.x * uint(kMPPAffineApple10TileN) + localN;
+ if (globalN < N) {
+ const uint globalK = tileKStart + localK;
+ const uint8_t packed = packedWeights[
+ globalN * rowBytes + (globalK >> 1)];
+ const uint q = (globalK & 1u) == 0u
+ ? uint(packed & 0x0fu)
+ : uint(packed >> 4);
+ const uint affineGroup = globalK / uint(kW4A8GroupSize);
+ const float scale = float(scales[
+ globalN * groupsPerRow + affineGroup]);
+ const float bias = float(biases[
+ globalN * groupsPerRow + affineGroup]);
+ weightTile[linear] = half(fma(float(q), scale, bias));
+ } else {
+ weightTile[linear] = half(0.0f);
+ }
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ device_half_tensor groupA(
+ activations + tileKStart,
+ dextents<int32_t, 2>(kMPPAffineApple10TileK, M),
+ array<int32_t, 2>({1, int32_t(K)}));
+ auto tileA = groupA.slice(
+ 0, int32_t(tgid.y) * kMPPAffineApple10TileM);
+ operation.run(tileA, tileB, groupProduct);
+ for (int element = 0; element < accumulator.get_capacity(); ++element) {
+ accumulator[element] += groupProduct[element];
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ }
+
+ for (int element = 0; element < accumulator.get_capacity(); ++element) {
+ if (!accumulator.is_valid_element(element)) continue;
+ const auto position = accumulator.get_multidimensional_index(element);
+ const uint globalN = tgid.x * uint(kMPPAffineApple10TileN)
+ + uint(position[0]);
+ const uint globalM = tgid.y * uint(kMPPAffineApple10TileM)
+ + uint(position[1]);
+ if (globalM < M && globalN < N) {
+ output[globalM * N + globalN] = half(accumulator[element]);
+ }
+ }
+}
+
+kernel void mpp_prefill_affine_threadgroup_bf16_apple10_v1(
+ device const uint8_t* packedWeights [[buffer(0)]],
+ device const bfloat* scales [[buffer(1)]],
+ device const bfloat* biases [[buffer(2)]],
+ device bfloat* activations [[buffer(3)]],
+ device half* output [[buffer(4)]],
+ constant uint& M [[buffer(5)]],
+ constant uint& N [[buffer(6)]],
+ constant uint& K [[buffer(7)]],
+ uint3 tgid [[threadgroup_position_in_grid]],
+ uint3 lid3 [[thread_position_in_threadgroup]],
+ uint3 threads3 [[threads_per_threadgroup]]) {
+ constexpr auto descriptor = matmul2d_descriptor(
+ kMPPAffineApple10TileM, kMPPAffineApple10TileN,
+ kMPPAffineApple10TileK, false, true, false);
+ matmul2d<descriptor, execution_simdgroups<4>> operation;
+
+ using device_bfloat_tensor =
+ tensor<device bfloat, dextents<int32_t, 2>, tensor_inline>;
+ using threadgroup_bfloat_tensor =
+ tensor<threadgroup bfloat, dextents<int32_t, 2>, tensor_inline>;
+
+ threadgroup bfloat weightTile[
+ kMPPAffineApple10TileN * kMPPAffineApple10TileK];
+ threadgroup_bfloat_tensor tileB(
+ weightTile,
+ dextents<int32_t, 2>(kMPPAffineApple10TileK, kMPPAffineApple10TileN),
+ array<int32_t, 2>({1, kMPPAffineApple10TileK}));
+ device_bfloat_tensor firstA(
+ activations,
+ dextents<int32_t, 2>(kMPPAffineApple10TileK, M),
+ array<int32_t, 2>({1, int32_t(K)}));
+ auto firstTileA = firstA.slice(
+ 0, int32_t(tgid.y) * kMPPAffineApple10TileM);
+ auto accumulator = operation.get_destination_cooperative_tensor<
+ decltype(firstTileA), decltype(tileB), float>();
+ auto groupProduct = operation.get_destination_cooperative_tensor<
+ decltype(firstTileA), decltype(tileB), float>();
+ for (int element = 0; element < accumulator.get_capacity(); ++element) {
+ accumulator[element] = 0.0f;
+ }
+
+ const uint rowBytes = K / 2u;
+ const uint groupsPerRow = K / kW4A8GroupSize;
+ const uint lid = lid3.x;
+ const uint threads = threads3.x;
+ for (uint tileKStart = 0; tileKStart < K;
+ tileKStart += uint(kMPPAffineApple10TileK)) {
+ for (int element = 0; element < groupProduct.get_capacity(); ++element) {
+ groupProduct[element] = 0.0f;
+ }
+ for (uint linear = lid;
+ linear < uint(kMPPAffineApple10TileN * kMPPAffineApple10TileK);
+ linear += threads) {
+ const uint localN = linear / uint(kMPPAffineApple10TileK);
+ const uint localK = linear % uint(kMPPAffineApple10TileK);
+ const uint globalN = tgid.x * uint(kMPPAffineApple10TileN) + localN;
+ if (globalN < N) {
+ const uint globalK = tileKStart + localK;
+ const uint8_t packed = packedWeights[
+ globalN * rowBytes + (globalK >> 1)];
+ const uint q = (globalK & 1u) == 0u
+ ? uint(packed & 0x0fu)
+ : uint(packed >> 4);
+ const uint affineGroup = globalK / uint(kW4A8GroupSize);
+ const float scale = float(scales[
+ globalN * groupsPerRow + affineGroup]);
+ const float bias = float(biases[
+ globalN * groupsPerRow + affineGroup]);
+ weightTile[linear] = bfloat(fma(float(q), scale, bias));
+ } else {
+ weightTile[linear] = bfloat(0.0f);
+ }
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ device_bfloat_tensor groupA(
+ activations + tileKStart,
+ dextents<int32_t, 2>(kMPPAffineApple10TileK, M),
+ array<int32_t, 2>({1, int32_t(K)}));
+ auto tileA = groupA.slice(
+ 0, int32_t(tgid.y) * kMPPAffineApple10TileM);
+ operation.run(tileA, tileB, groupProduct);
+ for (int element = 0; element < accumulator.get_capacity(); ++element) {
+ accumulator[element] += groupProduct[element];
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ }
+
+ for (int element = 0; element < accumulator.get_capacity(); ++element) {
+ if (!accumulator.is_valid_element(element)) continue;
+ const auto position = accumulator.get_multidimensional_index(element);
+ const uint globalN = tgid.x * uint(kMPPAffineApple10TileN)
+ + uint(position[0]);
+ const uint globalM = tgid.y * uint(kMPPAffineApple10TileM)
+ + uint(position[1]);
+ if (globalM < M && globalN < N) {
+ output[globalM * N + globalN] = half(accumulator[element]);
+ }
+ }
+}
+
+#if defined(TURBO_FIELDFARE_VISION_TENSOROPS)
+
+constant constexpr int kVisionAttentionQueries = 16;
+constant constexpr int kVisionAttentionKeys = 64;
+constant constexpr int kVisionAttentionHeadDim = 80;
+// The QK contraction needs a K that is a multiple of 16, so it keeps 80. The PV
+// matmul carries the head dimension as N, which only needs a multiple of 8, so
+// it contracts over the 72 real lanes; lanes 72 to 79 hold zero V and their
+// outputs were discarded anyway.
+constant constexpr int kVisionAttentionRealHeadDim = 72;
+
+/// `inputRowStride` is the per-head row count of the padded Q/K/V buffers, which
+/// may exceed `sequenceLength` when the projections write every padded GEMM row.
+/// `unpaddedOutputHeadDim` of 0 keeps the padded head-major output store; a
+/// nonzero value stores row-major `(row * numHeads + head) * headDim + lane`
+/// directly, which removes the separate unpad dispatch.
+struct VisionAttentionLayout {
+ uint inputRowStride;
+ uint unpaddedOutputHeadDim;
+ /// Softmax phase: 0 runs the original 16-thread serial phase; 1 spreads
+ /// max, exp and sum across all 128 threads, which makes the tile sum a tree
+ /// reduction and is therefore not bit-identical; 2 spreads max and exp but
+ /// keeps the tile sum sequential per query, which is bit-identical to 0.
+ uint parallelSoftmax;
+};
+
+/// `PVOutputDim` is how many head lanes the PV matmul produces. Threadgroup
+/// memory is passed in because MSL forbids declaring it in a non-kernel function.
+template <int PVOutputDim>
+inline void mpp_vision_attention_bf16_impl(
+ device bfloat* Q, device bfloat* K, device bfloat* V, device bfloat* O,
+ constant uint& sequenceLength,
+ constant uint& numHeads,
+ constant VisionAttentionLayout& layout,
+ uint3 tg, uint lid, ushort simdLane, ushort simdIndex,
+ threadgroup float* scoreTile,
+ threadgroup float* weightTile,
+ threadgroup float* rowMax,
+ threadgroup float* rowSum,
+ threadgroup float* oldScale,
+ threadgroup float* nextMaxTile) {
+ constexpr auto qkDescriptor = matmul2d_descriptor(
+ kVisionAttentionQueries,
+ kVisionAttentionKeys,
+ kVisionAttentionHeadDim,
+ false, true, false);
+ constexpr auto pvDescriptor = matmul2d_descriptor(
+ kVisionAttentionQueries,
+ PVOutputDim,
+ kVisionAttentionKeys,
+ false, false, false);
+ matmul2d<qkDescriptor, execution_simdgroups<4>> qkOperation;
+ matmul2d<pvDescriptor, execution_simdgroups<4>> pvOperation;
+
+ using device_bfloat_tensor =
+ tensor<device bfloat, dextents<int32_t, 2>, tensor_inline>;
+ using threadgroup_float_tensor =
+ tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>;
+
+ const uint queryStart = tg.x * uint(kVisionAttentionQueries);
+ const uint head = tg.y;
+ if (queryStart >= sequenceLength || head >= numHeads) return;
+ const uint rowStride = uint(kVisionAttentionHeadDim);
+ const uint validQueries = min(
+ uint(kVisionAttentionQueries), sequenceLength - queryStart);
+
+ const uint inputRows = layout.inputRowStride == 0u
+ ? sequenceLength : layout.inputRowStride;
+ const uint headBase = head * inputRows * uint(kVisionAttentionHeadDim);
+ device_bfloat_tensor queryTensor(
+ Q + headBase,
+ dextents<int32_t, 2>(kVisionAttentionHeadDim, int32_t(sequenceLength)),
+ array<int32_t, 2>({1, int32_t(rowStride)}));
+ device_bfloat_tensor keyTensor(
+ K + headBase,
+ dextents<int32_t, 2>(kVisionAttentionHeadDim, int32_t(sequenceLength)),
+ array<int32_t, 2>({1, int32_t(rowStride)}));
+ device_bfloat_tensor valueTensor(
+ V + headBase,
+ dextents<int32_t, 2>(PVOutputDim, int32_t(sequenceLength)),
+ array<int32_t, 2>({1, int32_t(rowStride)}));
+ threadgroup_float_tensor weights(
+ weightTile,
+ dextents<int32_t, 2>(
+ kVisionAttentionKeys, kVisionAttentionQueries),
+ array<int32_t, 2>({1, kVisionAttentionKeys}));
+
+ auto querySlice = queryTensor.slice(0, int32_t(queryStart));
+ auto firstValueSlice = valueTensor.slice(0, 0);
+ auto outputAccumulator =
+ pvOperation.template get_destination_cooperative_tensor<
+ decltype(weights), decltype(firstValueSlice), float>();
+ for (int element = 0;
+ element < outputAccumulator.get_capacity();
+ ++element) {
+ if (outputAccumulator.is_valid_element(element)) {
+ outputAccumulator[element] = 0.0f;
+ }
+ }
+ if (lid < uint(kVisionAttentionQueries)) {
+ rowMax[lid] = -INFINITY;
+ rowSum[lid] = 0.0f;
+ oldScale[lid] = 0.0f;
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ for (uint keyStart = 0; keyStart < sequenceLength;
+ keyStart += uint(kVisionAttentionKeys)) {
+ auto keySlice = keyTensor.slice(0, int32_t(keyStart));
+ auto scores = qkOperation.template get_destination_cooperative_tensor<
+ decltype(querySlice), decltype(keySlice), float>();
+ for (int element = 0; element < scores.get_capacity(); ++element) {
+ if (scores.is_valid_element(element)) scores[element] = 0.0f;
+ }
+ qkOperation.run(querySlice, keySlice, scores);
+ for (int element = 0; element < scores.get_capacity(); ++element) {
+ if (!scores.is_valid_element(element)) continue;
+ const auto position = scores.get_multidimensional_index(element);
+ scoreTile[
+ uint(position[1]) * uint(kVisionAttentionKeys)
+ + uint(position[0])] = scores[element];
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ const uint visible = min(
+ uint(kVisionAttentionKeys), sequenceLength - keyStart);
+ if (layout.parallelSoftmax != 0u) {
+ // Eight lanes per query, eight consecutive keys each. The lane groups
+ // sit inside one simdgroup, so an XOR butterfly over masks 1, 2 and 4
+ // reduces within a group without touching its neighbours.
+ constexpr uint keysPerLane =
+ uint(kVisionAttentionKeys) / 8u;
+ const uint lane = uint(simdLane);
+ const uint query = uint(simdIndex) * 4u + lane / 8u;
+ const uint keyBase = (lane % 8u) * keysPerLane;
+ const uint row = query * uint(kVisionAttentionKeys);
+
+ float tileMax = -INFINITY;
+ if (query < validQueries) {
+ for (uint offset = 0; offset < keysPerLane; ++offset) {
+ const uint key = keyBase + offset;
+ if (key < visible) tileMax = max(tileMax, scoreTile[row + key]);
+ }
+ }
+ for (uint mask = 1u; mask < 8u; mask <<= 1) {
+ tileMax = max(tileMax, simd_shuffle_xor(tileMax, ushort(mask)));
+ }
+ const float previousMax = rowMax[query];
+ const float previousSum = rowSum[query];
+ const float nextMax = max(previousMax, tileMax);
+ const float scale = previousSum > 0.0f
+ ? fast::exp(previousMax - nextMax)
+ : 0.0f;
+ // Mode 2 hands the running max to the serial summation threads, which
+ // own different queries than the lanes that computed it.
+ if (layout.parallelSoftmax == 2u && lane % 8u == 0u) {
+ nextMaxTile[query] = nextMax;
+ }
+ float tileSum = 0.0f;
+ for (uint offset = 0; offset < keysPerLane; ++offset) {
+ const uint key = keyBase + offset;
+ const float weight = query < validQueries && key < visible
+ ? fast::exp(scoreTile[row + key] - nextMax)
+ : 0.0f;
+ weightTile[row + key] = weight;
+ tileSum += weight;
+ }
+ if (layout.parallelSoftmax == 1u) {
+ for (uint mask = 1u; mask < 8u; mask <<= 1) {
+ tileSum += simd_shuffle_xor(tileSum, ushort(mask));
+ }
+ simdgroup_barrier(mem_flags::mem_threadgroup);
+ if (lane % 8u == 0u) {
+ oldScale[query] = scale;
+ rowSum[query] = previousSum * scale + tileSum;
+ rowMax[query] = nextMax;
+ }
+ } else {
+ // Mode 2: the weights are already written, so re-sum them in the
+ // original key order. Identical addends in identical order keep
+ // this bit-identical to the serial phase.
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ if (lid < uint(kVisionAttentionQueries)) {
+ const uint serialRow = lid * uint(kVisionAttentionKeys);
+ float serialSum = 0.0f;
+ for (uint key = 0; key < uint(kVisionAttentionKeys); ++key) {
+ serialSum += weightTile[serialRow + key];
+ }
+ oldScale[lid] = rowSum[lid] > 0.0f
+ ? fast::exp(rowMax[lid] - nextMaxTile[lid])
+ : 0.0f;
+ rowSum[lid] = rowSum[lid] * oldScale[lid] + serialSum;
+ rowMax[lid] = nextMaxTile[lid];
+ }
+ }
+ } else if (lid < uint(kVisionAttentionQueries)) {
+ const uint query = lid;
+ float tileMax = -INFINITY;
+ if (query < validQueries) {
+ for (uint key = 0; key < visible; ++key) {
+ tileMax = max(
+ tileMax,
+ scoreTile[query * uint(kVisionAttentionKeys) + key]);
+ }
+ }
+ const float nextMax = max(rowMax[query], tileMax);
+ const float scale = rowSum[query] > 0.0f
+ ? fast::exp(rowMax[query] - nextMax)
+ : 0.0f;
+ float tileSum = 0.0f;
+ for (uint key = 0; key < uint(kVisionAttentionKeys); ++key) {
+ const float weight = query < validQueries && key < visible
+ ? fast::exp(
+ scoreTile[query * uint(kVisionAttentionKeys) + key]
+ - nextMax)
+ : 0.0f;
+ weightTile[query * uint(kVisionAttentionKeys) + key] = weight;
+ tileSum += weight;
+ }
+ oldScale[query] = scale;
+ rowSum[query] = rowSum[query] * scale + tileSum;
+ rowMax[query] = nextMax;
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ auto valueSlice = valueTensor.slice(0, int32_t(keyStart));
+ auto outputProduct = pvOperation.template get_destination_cooperative_tensor<
+ decltype(weights), decltype(valueSlice), float>();
+ for (int element = 0;
+ element < outputProduct.get_capacity();
+ ++element) {
+ if (outputProduct.is_valid_element(element)) {
+ outputProduct[element] = 0.0f;
+ }
+ }
+ pvOperation.run(weights, valueSlice, outputProduct);
+ for (int element = 0;
+ element < outputAccumulator.get_capacity();
+ ++element) {
+ if (!outputAccumulator.is_valid_element(element)
+ || !outputProduct.is_valid_element(element)) continue;
+ const auto position =
+ outputAccumulator.get_multidimensional_index(element);
+ const uint query = uint(position[1]);
+ outputAccumulator[element] = fma(
+ 1.0f,
+ outputProduct[element],
+ outputAccumulator[element] * oldScale[query]);
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ }
+
+ for (int element = 0;
+ element < outputAccumulator.get_capacity();
+ ++element) {
+ if (!outputAccumulator.is_valid_element(element)) continue;
+ const auto position =
+ outputAccumulator.get_multidimensional_index(element);
+ const uint dimension = uint(position[0]);
+ const uint query = uint(position[1]);
+ if (query >= validQueries) continue;
+ const uint outputHeadDim = layout.unpaddedOutputHeadDim;
+ if (outputHeadDim == 0u) {
+ if (dimension < uint(kVisionAttentionHeadDim)) {
+ O[(head * sequenceLength + queryStart + query) * rowStride
+ + dimension] =
+ bfloat(outputAccumulator[element] / rowSum[query]);
+ }
+ } else if (dimension < outputHeadDim) {
+ O[(queryStart + query) * numHeads * outputHeadDim
+ + head * outputHeadDim + dimension] =
+ bfloat(outputAccumulator[element] / rowSum[query]);
+ }
+ }
+}
+
+kernel void mpp_vision_attention_bf16(
+ device bfloat* Q [[buffer(0)]],
+ device bfloat* K [[buffer(1)]],
+ device bfloat* V [[buffer(2)]],
+ device bfloat* O [[buffer(3)]],
+ constant uint& sequenceLength [[buffer(4)]],
+ constant uint& numHeads [[buffer(5)]],
+ constant VisionAttentionLayout& layout [[buffer(6)]],
+ uint3 tg [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ ushort simdLane [[thread_index_in_simdgroup]],
+ ushort simdIndex [[simdgroup_index_in_threadgroup]]) {
+ threadgroup float scoreTile[
+ kVisionAttentionQueries * kVisionAttentionKeys];
+ threadgroup float weightTile[
+ kVisionAttentionQueries * kVisionAttentionKeys];
+ threadgroup float rowMax[kVisionAttentionQueries];
+ threadgroup float rowSum[kVisionAttentionQueries];
+ threadgroup float oldScale[kVisionAttentionQueries];
+ threadgroup float nextMaxTile[kVisionAttentionQueries];
+ mpp_vision_attention_bf16_impl<kVisionAttentionRealHeadDim>(
+ Q, K, V, O, sequenceLength, numHeads, layout, tg, lid, simdLane,
+ simdIndex, scoreTile, weightTile, rowMax, rowSum, oldScale, nextMaxTile);
+}
+
+kernel void mpp_vision_attention_bf16_pv80(
+ device bfloat* Q [[buffer(0)]],
+ device bfloat* K [[buffer(1)]],
+ device bfloat* V [[buffer(2)]],
+ device bfloat* O [[buffer(3)]],
+ constant uint& sequenceLength [[buffer(4)]],
+ constant uint& numHeads [[buffer(5)]],
+ constant VisionAttentionLayout& layout [[buffer(6)]],
+ uint3 tg [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ ushort simdLane [[thread_index_in_simdgroup]],
+ ushort simdIndex [[simdgroup_index_in_threadgroup]]) {
+ threadgroup float scoreTile[
+ kVisionAttentionQueries * kVisionAttentionKeys];
+ threadgroup float weightTile[
+ kVisionAttentionQueries * kVisionAttentionKeys];
+ threadgroup float rowMax[kVisionAttentionQueries];
+ threadgroup float rowSum[kVisionAttentionQueries];
+ threadgroup float oldScale[kVisionAttentionQueries];
+ threadgroup float nextMaxTile[kVisionAttentionQueries];
+ mpp_vision_attention_bf16_impl<kVisionAttentionHeadDim>(
+ Q, K, V, O, sequenceLength, numHeads, layout, tg, lid, simdLane,
+ simdIndex, scoreTile, weightTile, rowMax, rowSum, oldScale, nextMaxTile);
+}
+
#endif
+
+#endif // __HAVE_TENSOR__
diff --git a/Sources/TurboFieldfare/Metal/Vision/vision.metal b/Sources/TurboFieldfare/Metal/Vision/vision.metal
new file mode 100644
index 00000000..c6234c2d
--- /dev/null
+++ b/Sources/TurboFieldfare/Metal/Vision/vision.metal
@@ -0,0 +1,556 @@
+#include <metal_stdlib>
+using namespace metal;
+
+constant constexpr uint kVisionHeadDim = 72;
+constant constexpr uint kVisionPaddedHeadDim = 80;
+constant constexpr uint kVisionMaxQueryTile = 16;
+constant constexpr uint kVisionKeyTile = 32;
+constant constexpr uint kVisionThreads = 128;
+
+kernel void vision_pad_heads_72_to_80(
+ device const bfloat* q [[buffer(0)]],
+ device const bfloat* k [[buffer(1)]],
+ device const bfloat* v [[buffer(2)]],
+ device bfloat* paddedQ [[buffer(3)]],
+ device bfloat* paddedK [[buffer(4)]],
+ device bfloat* paddedV [[buffer(5)]],
+ constant uint& rows [[buffer(6)]],
+ constant uint& heads [[buffer(7)]],
+ uint index [[thread_position_in_grid]]) {
+ if (index >= rows * heads * 80u) return;
+ const uint dimension = index % 80u;
+ const uint vector = index / 80u;
+ const uint row = vector % rows;
+ const uint head = vector / rows;
+ const uint source = (row * heads + head) * 72u + dimension;
+ paddedQ[index] = dimension < 72u ? q[source] : bfloat(0.0f);
+ paddedK[index] = dimension < 72u ? k[source] : bfloat(0.0f);
+ paddedV[index] = dimension < 72u ? v[source] : bfloat(0.0f);
+}
+
+kernel void vision_unpad_heads_80_to_72(
+ device const bfloat* input [[buffer(0)]],
+ device bfloat* output [[buffer(1)]],
+ constant uint& rows [[buffer(2)]],
+ constant uint& heads [[buffer(3)]],
+ uint index [[thread_position_in_grid]]) {
+ if (index >= rows * heads * 72u) return;
+ const uint dimension = index % 72u;
+ const uint vector = index / 72u;
+ const uint row = vector / heads;
+ const uint head = vector % heads;
+ output[index] = input[(head * rows + row) * 80u + dimension];
+}
+
+template <uint ComputeDim, uint QueryTile>
+inline void vision_attention_online_impl(
+ device const bfloat* q,
+ device const bfloat* k,
+ device const bfloat* v,
+ device bfloat* output,
+ constant uint& sequenceLength,
+ constant uint& numHeads,
+ uint2 group,
+ uint tid,
+ threadgroup bfloat* qTile,
+ threadgroup bfloat* kTile,
+ threadgroup bfloat* vTile,
+ threadgroup float* probabilities,
+ threadgroup float* accumulator,
+ threadgroup float* oldScale,
+ threadgroup float* rowSum,
+ threadgroup float* rowMax) {
+
+ const uint head = group.y;
+ const uint queryBase = group.x * QueryTile;
+ if (head >= numHeads) return;
+
+ for (uint index = tid; index < QueryTile * kVisionHeadDim;
+ index += kVisionThreads) {
+ const uint localQuery = index / kVisionHeadDim;
+ const uint dimension = index % kVisionHeadDim;
+ const uint query = queryBase + localQuery;
+ qTile[index] = query < sequenceLength
+ ? q[(query * numHeads + head) * kVisionHeadDim + dimension]
+ : bfloat(0.0f);
+ }
+ for (uint index = tid; index < QueryTile * kVisionPaddedHeadDim;
+ index += kVisionThreads) {
+ accumulator[index] = 0.0f;
+ }
+ if (tid < QueryTile) {
+ rowMax[tid] = -INFINITY;
+ rowSum[tid] = 0.0f;
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ for (uint keyBase = 0; keyBase < sequenceLength; keyBase += kVisionKeyTile) {
+ for (uint index = tid; index < kVisionKeyTile * kVisionHeadDim;
+ index += kVisionThreads) {
+ const uint localKey = index / kVisionHeadDim;
+ const uint dimension = index % kVisionHeadDim;
+ const uint keyIndex = keyBase + localKey;
+ const uint source = (keyIndex * numHeads + head) * kVisionHeadDim + dimension;
+ kTile[index] = keyIndex < sequenceLength ? k[source] : bfloat(0.0f);
+ vTile[index] = keyIndex < sequenceLength ? v[source] : bfloat(0.0f);
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ for (uint pair = tid; pair < QueryTile * kVisionKeyTile;
+ pair += kVisionThreads) {
+ const uint localQuery = pair / kVisionKeyTile;
+ const uint localKey = pair % kVisionKeyTile;
+ const uint query = queryBase + localQuery;
+ const uint keyIndex = keyBase + localKey;
+ float score = -INFINITY;
+ if (query < sequenceLength && keyIndex < sequenceLength) {
+ score = 0.0f;
+ for (uint dimension = 0; dimension < ComputeDim; ++dimension) {
+ const float qValue = dimension < kVisionHeadDim
+ ? float(qTile[localQuery * kVisionHeadDim + dimension]) : 0.0f;
+ const float kValue = dimension < kVisionHeadDim
+ ? float(kTile[localKey * kVisionHeadDim + dimension]) : 0.0f;
+ score = fma(qValue, kValue, score);
+ }
+ }
+ probabilities[pair] = score;
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ if (tid < QueryTile) {
+ float tileMax = -INFINITY;
+ for (uint localKey = 0; localKey < kVisionKeyTile; ++localKey) {
+ tileMax = max(tileMax,
+ probabilities[tid * kVisionKeyTile + localKey]);
+ }
+ const float nextMax = max(rowMax[tid], tileMax);
+ const float scale = rowMax[tid] == -INFINITY
+ ? 0.0f : exp(rowMax[tid] - nextMax);
+ float tileSum = 0.0f;
+ for (uint localKey = 0; localKey < kVisionKeyTile; ++localKey) {
+ const uint keyIndex = keyBase + localKey;
+ const float probability = keyIndex < sequenceLength
+ ? exp(probabilities[tid * kVisionKeyTile + localKey] - nextMax)
+ : 0.0f;
+ probabilities[tid * kVisionKeyTile + localKey] = probability;
+ tileSum += probability;
+ }
+ oldScale[tid] = scale;
+ rowSum[tid] = rowSum[tid] * scale + tileSum;
+ rowMax[tid] = nextMax;
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ for (uint index = tid; index < QueryTile * kVisionPaddedHeadDim;
+ index += kVisionThreads) {
+ const uint localQuery = index / kVisionPaddedHeadDim;
+ const uint dimension = index % kVisionPaddedHeadDim;
+ float value = accumulator[index] * oldScale[localQuery];
+ if (dimension < kVisionHeadDim) {
+ for (uint localKey = 0; localKey < kVisionKeyTile; ++localKey) {
+ value = fma(
+ probabilities[localQuery * kVisionKeyTile + localKey],
+ float(vTile[localKey * kVisionHeadDim + dimension]), value);
+ }
+ }
+ accumulator[index] = value;
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ }
+
+ for (uint index = tid; index < QueryTile * kVisionHeadDim;
+ index += kVisionThreads) {
+ const uint localQuery = index / kVisionHeadDim;
+ const uint dimension = index % kVisionHeadDim;
+ const uint query = queryBase + localQuery;
+ if (query < sequenceLength) {
+ output[(query * numHeads + head) * kVisionHeadDim + dimension] =
+ bfloat(accumulator[localQuery * kVisionPaddedHeadDim + dimension]
+ / rowSum[localQuery]);
+ }
+ }
+}
+
+kernel void vision_attention_online_72(
+ device const bfloat* q [[buffer(0)]],
+ device const bfloat* k [[buffer(1)]],
+ device const bfloat* v [[buffer(2)]],
+ device bfloat* output [[buffer(3)]],
+ constant uint& sequenceLength [[buffer(4)]],
+ constant uint& numHeads [[buffer(5)]],
+ uint3 group [[threadgroup_position_in_grid]],
+ uint3 threadPosition [[thread_position_in_threadgroup]]) {
+ threadgroup bfloat qTile[kVisionMaxQueryTile * kVisionHeadDim];
+ threadgroup bfloat kTile[kVisionKeyTile * kVisionHeadDim];
+ threadgroup bfloat vTile[kVisionKeyTile * kVisionHeadDim];
+ threadgroup float probabilities[kVisionMaxQueryTile * kVisionKeyTile];
+ threadgroup float accumulator[kVisionMaxQueryTile * kVisionPaddedHeadDim];
+ threadgroup float oldScale[kVisionMaxQueryTile];
+ threadgroup float rowSum[kVisionMaxQueryTile];
+ threadgroup float rowMax[kVisionMaxQueryTile];
+ vision_attention_online_impl<kVisionHeadDim, 8>(
+ q, k, v, output, sequenceLength, numHeads, group.xy, threadPosition.x,
+ qTile, kTile, vTile, probabilities, accumulator,
+ oldScale, rowSum, rowMax);
+}
+
+kernel void vision_attention_online_80(
+ device const bfloat* q [[buffer(0)]],
+ device const bfloat* k [[buffer(1)]],
+ device const bfloat* v [[buffer(2)]],
+ device bfloat* output [[buffer(3)]],
+ constant uint& sequenceLength [[buffer(4)]],
+ constant uint& numHeads [[buffer(5)]],
+ uint3 group [[threadgroup_position_in_grid]],
+ uint3 threadPosition [[thread_position_in_threadgroup]]) {
+ threadgroup bfloat qTile[kVisionMaxQueryTile * kVisionHeadDim];
+ threadgroup bfloat kTile[kVisionKeyTile * kVisionHeadDim];
+ threadgroup bfloat vTile[kVisionKeyTile * kVisionHeadDim];
+ threadgroup float probabilities[kVisionMaxQueryTile * kVisionKeyTile];
+ threadgroup float accumulator[kVisionMaxQueryTile * kVisionPaddedHeadDim];
+ threadgroup float oldScale[kVisionMaxQueryTile];
+ threadgroup float rowSum[kVisionMaxQueryTile];
+ threadgroup float rowMax[kVisionMaxQueryTile];
+ vision_attention_online_impl<kVisionPaddedHeadDim, 8>(
+ q, k, v, output, sequenceLength, numHeads, group.xy, threadPosition.x,
+ qTile, kTile, vTile, probabilities, accumulator,
+ oldScale, rowSum, rowMax);
+}
+
+kernel void vision_attention_online_72_q16(
+ device const bfloat* q [[buffer(0)]],
+ device const bfloat* k [[buffer(1)]],
+ device const bfloat* v [[buffer(2)]],
+ device bfloat* output [[buffer(3)]],
+ constant uint& sequenceLength [[buffer(4)]],
+ constant uint& numHeads [[buffer(5)]],
+ uint3 group [[threadgroup_position_in_grid]],
+ uint3 threadPosition [[thread_position_in_threadgroup]]) {
+ threadgroup bfloat qTile[kVisionMaxQueryTile * kVisionHeadDim];
+ threadgroup bfloat kTile[kVisionKeyTile * kVisionHeadDim];
+ threadgroup bfloat vTile[kVisionKeyTile * kVisionHeadDim];
+ threadgroup float probabilities[kVisionMaxQueryTile * kVisionKeyTile];
+ threadgroup float accumulator[kVisionMaxQueryTile * kVisionPaddedHeadDim];
+ threadgroup float oldScale[kVisionMaxQueryTile];
+ threadgroup float rowSum[kVisionMaxQueryTile];
+ threadgroup float rowMax[kVisionMaxQueryTile];
+ vision_attention_online_impl<kVisionHeadDim, 16>(
+ q, k, v, output, sequenceLength, numHeads, group.xy, threadPosition.x,
+ qTile, kTile, vTile, probabilities, accumulator,
+ oldScale, rowSum, rowMax);
+}
+
+kernel void vision_normalize_patches(
+ device const bfloat* input [[buffer(0)]],
+ device bfloat* output [[buffer(1)]],
+ constant uint& realRows [[buffer(2)]],
+ constant uint& paddedRows [[buffer(3)]],
+ uint index [[thread_position_in_grid]]) {
+ const uint count = paddedRows * 768u;
+ if (index >= count) return;
+ output[index] = index < realRows * 768u
+ ? bfloat(2.0f * (float(input[index]) - 0.5f))
+ : bfloat(0.0f);
+}
+
+kernel void vision_add_position(
+ device bfloat* hidden [[buffer(0)]],
+ device const bfloat* table [[buffer(1)]],
+ device const int2* positions [[buffer(2)]],
+ constant uint& rows [[buffer(3)]],
+ uint index [[thread_position_in_grid]]) {
+ const uint count = rows * 1152u;
+ if (index >= count) return;
+ const uint row = index / 1152u;
+ const uint dimension = index % 1152u;
+ const int2 position = positions[row];
+ const uint xIndex = uint(position.x) * 1152u + dimension;
+ const uint yIndex = (10240u + uint(position.y)) * 1152u + dimension;
+ hidden[index] = bfloat(float(hidden[index])
+ + float(table[xIndex]) + float(table[yIndex]));
+}
+
+inline float vision_simdgroup_sum(float value,
+ uint lane,
+ uint simdgroup,
+ threadgroup float* partials) {
+ const float subtotal = simd_sum(value);
+ if (lane == 0) partials[simdgroup] = subtotal;
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ if (simdgroup == 0) {
+ float merged = lane < 8u ? partials[lane] : 0.0f;
+ merged = simd_sum(merged);
+ if (lane == 0) partials[0] = merged;
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ return partials[0];
+}
+
+kernel void vision_rmsnorm_rows(
+ device const bfloat* input [[buffer(0)]],
+ device const bfloat* weight [[buffer(1)]],
+ device bfloat* output [[buffer(2)]],
+ constant uint& rows [[buffer(3)]],
+ constant uint& width [[buffer(4)]],
+ uint row [[threadgroup_position_in_grid]],
+ uint tid [[thread_position_in_threadgroup]],
+ uint lane [[thread_index_in_simdgroup]],
+ uint simdgroup [[simdgroup_index_in_threadgroup]]) {
+ if (row >= rows) return;
+ threadgroup float partials[32];
+ threadgroup float inverseRMS[1];
+ float values[4];
+ float sum = 0.0f;
+ const uint base = tid * 4u;
+ for (uint index = 0; index < 4u; ++index) {
+ const uint dimension = base + index;
+ values[index] = dimension < width
+ ? float(input[row * width + dimension]) : 0.0f;
+ sum += values[index] * values[index];
+ }
+ sum = simd_sum(sum);
+ if (simdgroup == 0) partials[lane] = 0.0f;
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ if (lane == 0) partials[simdgroup] = sum;
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ if (simdgroup == 0) {
+ sum = simd_sum(partials[lane]);
+ if (lane == 0) {
+ inverseRMS[0] = metal::precise::rsqrt(sum / float(width) + 1e-6f);
+ }
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ for (uint index = 0; index < 4u; ++index) {
+ const uint dimension = base + index;
+ if (dimension < width) {
+ const bfloat normalized = bfloat(values[index] * inverseRMS[0]);
+ output[row * width + dimension] = bfloat(
+ float(weight[dimension]) * float(normalized));
+ }
+ }
+}
+
+kernel void vision_postnorm_residual(
+ device const bfloat* residual [[buffer(0)]],
+ device const bfloat* branch [[buffer(1)]],
+ device const bfloat* weight [[buffer(2)]],
+ device bfloat* output [[buffer(3)]],
+ constant uint& rows [[buffer(4)]],
+ constant uint& width [[buffer(5)]],
+ uint row [[threadgroup_position_in_grid]],
+ uint tid [[thread_position_in_threadgroup]],
+ uint lane [[thread_index_in_simdgroup]],
+ uint simdgroup [[simdgroup_index_in_threadgroup]]) {
+ if (row >= rows) return;
+ threadgroup float partials[32];
+ threadgroup float inverseRMS[1];
+ float values[4];
+ float sum = 0.0f;
+ const uint base = tid * 4u;
+ for (uint index = 0; index < 4u; ++index) {
+ const uint dimension = base + index;
+ values[index] = dimension < width
+ ? float(branch[row * width + dimension]) : 0.0f;
+ sum += values[index] * values[index];
+ }
+ sum = simd_sum(sum);
+ if (simdgroup == 0) partials[lane] = 0.0f;
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ if (lane == 0) partials[simdgroup] = sum;
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ if (simdgroup == 0) {
+ sum = simd_sum(partials[lane]);
+ if (lane == 0) {
+ inverseRMS[0] = metal::precise::rsqrt(sum / float(width) + 1e-6f);
+ }
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ for (uint element = 0; element < 4u; ++element) {
+ const uint dimension = base + element;
+ if (dimension < width) {
+ const uint index = row * width + dimension;
+ const bfloat scaled = bfloat(values[element] * inverseRMS[0]);
+ const bfloat normalized = bfloat(
+ float(weight[dimension]) * float(scaled));
+ output[index] = bfloat(float(residual[index]) + float(normalized));
+ }
+ }
+}
+
+inline float2 vision_rope_pair(float2 value, int position, uint pairInAxis) {
+ const float exponent = (2.0f / 36.0f) * float(pairInAxis);
+ const float angle = float(position) / powr(100.0f, exponent);
+ const float cosine = cos(angle);
+ const float sine = sin(angle);
+ return float2(value.x * cosine - value.y * sine,
+ value.y * cosine + value.x * sine);
+}
+
+kernel void vision_qkv_norm_rope(
+ device bfloat* q [[buffer(0)]],
+ device bfloat* k [[buffer(1)]],
+ device bfloat* v [[buffer(2)]],
+ device const bfloat* qWeight [[buffer(3)]],
+ device const bfloat* kWeight [[buffer(4)]],
+ device const int2* positions [[buffer(5)]],
+ constant uint& rows [[buffer(6)]],
+ constant uint& heads [[buffer(7)]],
+ uint vectorIndex [[thread_position_in_grid]]) {
+ if (vectorIndex >= rows * heads) return;
+ const uint base = vectorIndex * kVisionHeadDim;
+ float qSquares = 0.0f;
+ float kSquares = 0.0f;
+ float vSquares = 0.0f;
+ for (uint dimension = 0; dimension < kVisionHeadDim; ++dimension) {
+ const float qValue = float(q[base + dimension]);
+ const float kValue = float(k[base + dimension]);
+ const float vValue = float(v[base + dimension]);
+ qSquares = fma(qValue, qValue, qSquares);
+ kSquares = fma(kValue, kValue, kSquares);
+ vSquares = fma(vValue, vValue, vSquares);
+ }
+ const float qInverse = rsqrt(qSquares / 72.0f + 1e-6f);
+ const float kInverse = rsqrt(kSquares / 72.0f + 1e-6f);
+ const float vInverse = rsqrt(vSquares / 72.0f + 1e-6f);
+ const int2 position = positions[vectorIndex / heads];
+ for (uint axis = 0; axis < 2u; ++axis) {
+ const uint axisBase = axis * 36u;
+ const int coordinate = axis == 0u ? position.x : position.y;
+ for (uint pair = 0; pair < 18u; ++pair) {
+ const uint first = base + axisBase + pair;
+ const uint second = first + 18u;
+ float2 qPair = float2(float(q[first]) * qInverse * float(qWeight[axisBase + pair]),
+ float(q[second]) * qInverse * float(qWeight[axisBase + pair + 18u]));
+ float2 kPair = float2(float(k[first]) * kInverse * float(kWeight[axisBase + pair]),
+ float(k[second]) * kInverse * float(kWeight[axisBase + pair + 18u]));
+ qPair = vision_rope_pair(qPair, coordinate, pair);
+ kPair = vision_rope_pair(kPair, coordinate, pair);
+ q[first] = bfloat(qPair.x);
+ q[second] = bfloat(qPair.y);
+ k[first] = bfloat(kPair.x);
+ k[second] = bfloat(kPair.y);
+ }
+ }
+ for (uint dimension = 0; dimension < kVisionHeadDim; ++dimension) {
+ v[base + dimension] = bfloat(float(v[base + dimension]) * vInverse);
+ }
+}
+
+/// Same arithmetic as `vision_qkv_norm_rope` on the head-major padded layout the
+/// QKV projections now write: vector `(head, row)` starts at
+/// `(head * rowStride + row) * 80`. Threads walk rows within a head so the
+/// strided-by-80 accesses stay coalesced.
+kernel void vision_qkv_norm_rope_padded(
+ device bfloat* q [[buffer(0)]],
+ device bfloat* k [[buffer(1)]],
+ device bfloat* v [[buffer(2)]],
+ device const bfloat* qWeight [[buffer(3)]],
+ device const bfloat* kWeight [[buffer(4)]],
+ device const int2* positions [[buffer(5)]],
+ constant uint& rows [[buffer(6)]],
+ constant uint& heads [[buffer(7)]],
+ constant uint& rowStride [[buffer(8)]],
+ uint vectorIndex [[thread_position_in_grid]]) {
+ if (vectorIndex >= rows * heads) return;
+ const uint head = vectorIndex / rows;
+ const uint row = vectorIndex % rows;
+ const uint base = (head * rowStride + row) * kVisionPaddedHeadDim;
+ float qSquares = 0.0f;
+ float kSquares = 0.0f;
+ float vSquares = 0.0f;
+ for (uint dimension = 0; dimension < kVisionHeadDim; ++dimension) {
+ const float qValue = float(q[base + dimension]);
+ const float kValue = float(k[base + dimension]);
+ const float vValue = float(v[base + dimension]);
+ qSquares = fma(qValue, qValue, qSquares);
+ kSquares = fma(kValue, kValue, kSquares);
+ vSquares = fma(vValue, vValue, vSquares);
+ }
+ const float qInverse = rsqrt(qSquares / 72.0f + 1e-6f);
+ const float kInverse = rsqrt(kSquares / 72.0f + 1e-6f);
+ const float vInverse = rsqrt(vSquares / 72.0f + 1e-6f);
+ const int2 position = positions[row];
+ for (uint axis = 0; axis < 2u; ++axis) {
+ const uint axisBase = axis * 36u;
+ const int coordinate = axis == 0u ? position.x : position.y;
+ for (uint pair = 0; pair < 18u; ++pair) {
+ const uint first = base + axisBase + pair;
+ const uint second = first + 18u;
+ float2 qPair = float2(float(q[first]) * qInverse * float(qWeight[axisBase + pair]),
+ float(q[second]) * qInverse * float(qWeight[axisBase + pair + 18u]));
+ float2 kPair = float2(float(k[first]) * kInverse * float(kWeight[axisBase + pair]),
+ float(k[second]) * kInverse * float(kWeight[axisBase + pair + 18u]));
+ qPair = vision_rope_pair(qPair, coordinate, pair);
+ kPair = vision_rope_pair(kPair, coordinate, pair);
+ q[first] = bfloat(qPair.x);
+ q[second] = bfloat(qPair.y);
+ k[first] = bfloat(kPair.x);
+ k[second] = bfloat(kPair.y);
+ }
+ }
+ for (uint dimension = 0; dimension < kVisionHeadDim; ++dimension) {
+ v[base + dimension] = bfloat(float(v[base + dimension]) * vInverse);
+ }
+}
+
+kernel void vision_geglu(
+ device bfloat* gate [[buffer(0)]],
+ device const bfloat* up [[buffer(1)]],
+ constant uint& count [[buffer(2)]],
+ uint index [[thread_position_in_grid]]) {
+ if (index >= count) return;
+ const float x = float(gate[index]);
+ const float inner = clamp(
+ 0.7978845608f * (x + 0.044715f * x * x * x), -20.0f, 20.0f);
+ const float gelu = 0.5f * x * (1.0f + tanh(inner));
+ gate[index] = bfloat(gelu * float(up[index]));
+}
+
+kernel void vision_pool_standardize_norm(
+ device const bfloat* input [[buffer(0)]],
+ device const bfloat* stdBias [[buffer(1)]],
+ device const bfloat* stdScale [[buffer(2)]],
+ device bfloat* output [[buffer(3)]],
+ constant uint& patchWidth [[buffer(4)]],
+ constant uint& patchHeight [[buffer(5)]],
+ uint outputRow [[threadgroup_position_in_grid]],
+ uint tid [[thread_position_in_threadgroup]],
+ uint lane [[thread_index_in_simdgroup]],
+ uint simdgroup [[simdgroup_index_in_threadgroup]]) {
+ const uint outputWidth = patchWidth / 3u;
+ const uint outputHeight = patchHeight / 3u;
+ if (outputRow >= outputWidth * outputHeight) return;
+ const uint outputX = outputRow % outputWidth;
+ const uint outputY = outputRow / outputWidth;
+ threadgroup float partials[8];
+ float squares = 0.0f;
+ for (uint dimension = tid; dimension < 1152u; dimension += 256u) {
+ float pooled = 0.0f;
+ for (uint dy = 0; dy < 3u; ++dy) {
+ for (uint dx = 0; dx < 3u; ++dx) {
+ const uint inputRow = (outputY * 3u + dy) * patchWidth
+ + outputX * 3u + dx;
+ pooled += float(input[inputRow * 1152u + dimension]);
+ }
+ }
+ pooled *= sqrt(1152.0f) / 9.0f;
+ const float standardized = (pooled - float(stdBias[dimension]))
+ * float(stdScale[dimension]);
+ output[outputRow * 1152u + dimension] = bfloat(standardized);
+ squares = fma(standardized, standardized, squares);
+ }
+ const float total = vision_simdgroup_sum(squares, lane, simdgroup, partials);
+ const float inverse = rsqrt(total / 1152.0f + 1e-6f);
+ for (uint dimension = tid; dimension < 1152u; dimension += 256u) {
+ const uint index = outputRow * 1152u + dimension;
+ output[index] = bfloat(float(output[index]) * inverse);
+ }
+}
+
+kernel void vision_bfloat_to_half(
+ device const bfloat* input [[buffer(0)]],
+ device half* output [[buffer(1)]],
+ constant uint& count [[buffer(2)]],
+ uint index [[thread_position_in_grid]]) {
+ if (index < count) output[index] = half(input[index]);
+}
diff --git a/Sources/TurboFieldfare/Metal/Vision/vision_register_gemm.metal b/Sources/TurboFieldfare/Metal/Vision/vision_register_gemm.metal
new file mode 100644
index 00000000..6b057cea
--- /dev/null
+++ b/Sources/TurboFieldfare/Metal/Vision/vision_register_gemm.metal
@@ -0,0 +1,187 @@
+#include <metal_stdlib>
+#include <MetalPerformancePrimitives/MetalPerformancePrimitives.h>
+
+using namespace metal;
+using namespace mpp::tensor_ops;
+
+#if defined(__HAVE_TENSOR__)
+
+/// Head-major padded store descriptor. `rowStride == 0` selects the plain
+/// row-major store `output[m * columns + n]`; otherwise column `n` is split into
+/// head `n / headDim` and lane `n % headDim` and written at
+/// `(head * rowStride + m) * paddedHeadDim + lane`, which is the layout the
+/// padded attention kernel reads. Lanes in `[headDim, paddedHeadDim)` are never
+/// written here; they are zeroed once per image and stay zero.
+struct VisionGEMMPaddedStore {
+ uint rowStride;
+ uint headDim;
+ uint paddedHeadDim;
+};
+
+/// Same expression as the standalone `vision_geglu` kernel. `up` is rounded to
+/// bfloat first because the split path stored it in a bfloat buffer before the
+/// elementwise pass read it back.
+inline bfloat vision_geglu_combine(bfloat gate, float up) {
+ const float x = float(gate);
+ const float tanhInput = clamp(
+ 0.7978845608f * (x + 0.044715f * x * x * x), -20.0f, 20.0f);
+ const float activated = 0.5f * x * (1.0f + tanh(tanhInput));
+ return bfloat(activated * float(bfloat(up)));
+}
+
+/// `FuseGeGLU` folds the elementwise GeGLU into this GEMM's epilogue. The kernel
+/// then computes the `up` projection and combines it with the `gate` values that
+/// a previous dispatch already wrote to `output`, so no separate `up` buffer and
+/// no separate GeGLU dispatch exist. Rounding `up` to bfloat before the GeGLU
+/// math reproduces the round trip through the retired `up` buffer exactly, which
+/// keeps the fused path bit-identical to the split one.
+template <bool FuseGeGLU>
+inline void tff_vision_register_gemm_impl(
+ device bfloat* input,
+ device bfloat* weights,
+ device bfloat* output,
+ constant uint& rows,
+ constant uint& columns,
+ constant uint& inner,
+ constant VisionGEMMPaddedStore& paddedStore,
+ uint2 group,
+ ushort simdgroup) {
+ constexpr int tileM = 64;
+ constexpr int tileN = 128;
+ constexpr int simdTileM = 16;
+ constexpr int simdTileN = 32;
+ constexpr int simdTileK = 32;
+ constexpr int simdgroupsN = tileN / simdTileN;
+ constexpr auto descriptor = matmul2d_descriptor(
+ simdTileM, simdTileN, simdTileK, false, true, true,
+ matmul2d_descriptor::mode::multiply_accumulate);
+ matmul2d<descriptor, execution_simdgroup> operation;
+ using device_bfloat_tensor = tensor<
+ device bfloat, dextents<int32_t, 2>, tensor_inline>;
+ device_bfloat_tensor matrixA(
+ input,
+ dextents<int32_t, 2>(int32_t(inner), int32_t(rows)),
+ array<int32_t, 2>({1, int32_t(inner)}));
+ device_bfloat_tensor matrixB(
+ weights,
+ dextents<int32_t, 2>(int32_t(inner), int32_t(columns)),
+ array<int32_t, 2>({1, int32_t(inner)}));
+
+ const uint localM = uint(simdgroup) / uint(simdgroupsN) * 32;
+ const uint localN = uint(simdgroup) % uint(simdgroupsN) * uint(simdTileN);
+ const uint startM = group.y * uint(tileM);
+ const uint startN = group.x * uint(tileN);
+ auto a0 = operation.get_left_input_cooperative_tensor<bfloat, bfloat, float>();
+ auto a1 = operation.get_left_input_cooperative_tensor<bfloat, bfloat, float>();
+ auto b = operation.get_right_input_cooperative_tensor<bfloat, bfloat, float>();
+ auto accumulator0 = operation.get_destination_cooperative_tensor<
+ remove_addrspace_t<decltype(a0)>, remove_addrspace_t<decltype(b)>, float>();
+ auto accumulator1 = operation.get_destination_cooperative_tensor<
+ remove_addrspace_t<decltype(a1)>, remove_addrspace_t<decltype(b)>, float>();
+ // Each thread owns (simdTileM * simdTileN) / 32 destination elements of the
+ // 16x32 simdgroup tile, and the sums arrays are sized for exactly that.
+ // get_capacity() is an implementation-defined runtime value, so a GPU
+ // family that reports more would run the loops below off the fixed arrays
+ // and corrupt thread-private stack. Bail out instead: the encode then
+ // produces detectably wrong output that the parity gates catch, not
+ // undefined behavior.
+ constexpr int accumulatorSlots = (simdTileM * simdTileN) / 32;
+ if (int(accumulator0.get_capacity()) > accumulatorSlots ||
+ int(accumulator1.get_capacity()) > accumulatorSlots) {
+ return;
+ }
+ float sums0[accumulatorSlots];
+ float sums1[accumulatorSlots];
+ for (int element = 0; element < accumulator0.get_capacity(); ++element) {
+ sums0[element] = 0.0f;
+ sums1[element] = 0.0f;
+ }
+
+ for (uint groupK = 0; groupK < inner; groupK += 64u) {
+ for (int element = 0; element < accumulator0.get_capacity(); ++element) {
+ accumulator0[element] = 0.0f;
+ accumulator1[element] = 0.0f;
+ }
+ for (uint startK = groupK;
+ startK < min(groupK + 64u, inner);
+ startK += uint(simdTileK)) {
+ auto tileA0 = matrixA.slice(
+ int32_t(startK), int32_t(startM + localM));
+ auto tileA1 = matrixA.slice(
+ int32_t(startK), int32_t(startM + localM + 16));
+ auto tileB = matrixB.slice(
+ int32_t(startK), int32_t(startN + localN));
+ a0.load(tileA0);
+ a1.load(tileA1);
+ b.load(tileB);
+ operation.run(a0, b, accumulator0);
+ operation.run(a1, b, accumulator1);
+ }
+ for (int element = 0; element < accumulator0.get_capacity(); ++element) {
+ sums0[element] += accumulator0[element];
+ sums1[element] += accumulator1[element];
+ }
+ }
+
+ const bool storePadded = paddedStore.rowStride != 0u;
+ for (int element = 0; element < accumulator0.get_capacity(); ++element) {
+ const auto position = accumulator0.get_multidimensional_index(element);
+ const uint m0 = startM + localM + uint(position[1]);
+ const uint m1 = m0 + 16;
+ const uint n = startN + localN + uint(position[0]);
+ if (n >= columns) continue;
+ uint offset0;
+ uint offset1;
+ if (storePadded) {
+ const uint head = n / paddedStore.headDim;
+ const uint lane = n % paddedStore.headDim;
+ const uint headBase = head * paddedStore.rowStride;
+ offset0 = (headBase + m0) * paddedStore.paddedHeadDim + lane;
+ offset1 = (headBase + m1) * paddedStore.paddedHeadDim + lane;
+ } else {
+ offset0 = m0 * columns + n;
+ offset1 = m1 * columns + n;
+ }
+ if (FuseGeGLU) {
+ if (m0 < rows) output[offset0] = vision_geglu_combine(
+ output[offset0], sums0[element]);
+ if (m1 < rows) output[offset1] = vision_geglu_combine(
+ output[offset1], sums1[element]);
+ } else {
+ if (m0 < rows) output[offset0] = bfloat(sums0[element]);
+ if (m1 < rows) output[offset1] = bfloat(sums1[element]);
+ }
+ }
+}
+
+kernel void tff_vision_register_gemm(
+ device bfloat* input [[buffer(0)]],
+ device bfloat* weights [[buffer(1)]],
+ device bfloat* output [[buffer(2)]],
+ constant uint& rows [[buffer(3)]],
+ constant uint& columns [[buffer(4)]],
+ constant uint& inner [[buffer(5)]],
+ constant VisionGEMMPaddedStore& paddedStore [[buffer(6)]],
+ uint2 group [[threadgroup_position_in_grid]],
+ ushort simdgroup [[simdgroup_index_in_threadgroup]]) {
+ tff_vision_register_gemm_impl<false>(
+ input, weights, output, rows, columns, inner, paddedStore,
+ group, simdgroup);
+}
+
+kernel void tff_vision_register_gemm_geglu(
+ device bfloat* input [[buffer(0)]],
+ device bfloat* weights [[buffer(1)]],
+ device bfloat* output [[buffer(2)]],
+ constant uint& rows [[buffer(3)]],
+ constant uint& columns [[buffer(4)]],
+ constant uint& inner [[buffer(5)]],
+ constant VisionGEMMPaddedStore& paddedStore [[buffer(6)]],
+ uint2 group [[threadgroup_position_in_grid]],
+ ushort simdgroup [[simdgroup_index_in_threadgroup]]) {
+ tff_vision_register_gemm_impl<true>(
+ input, weights, output, rows, columns, inner, paddedStore,
+ group, simdgroup);
+}
+
+#endif
diff --git a/Sources/TurboFieldfare/Metal/Vision/vision_resize.metal b/Sources/TurboFieldfare/Metal/Vision/vision_resize.metal
new file mode 100644
index 00000000..f570a105
--- /dev/null
+++ b/Sources/TurboFieldfare/Metal/Vision/vision_resize.metal
@@ -0,0 +1,92 @@
+#include <metal_stdlib>
+using namespace metal;
+
+// Separable antialiased bicubic resize, in the same fixed-point arithmetic as
+// `TorchBicubicResize`.
+//
+// The weights are built on the CPU — they depend only on the axis ratio, so
+// there are `dst` of them per axis, not per pixel — and applied here. Every
+// step mirrors the CPU implementation exactly: Int16 weights, an Int32
+// accumulator seeded with the rounding term, an arithmetic shift by the axis
+// precision, and a clamp to 0...255. That is what makes the GPU output
+// byte-identical rather than merely close, which in turn is what lets the CPU
+// path stay the oracle in tests.
+//
+// Two passes, horizontal then vertical, because a separable filter costs
+// `src*dst_w + dst_w*dst_h` taps rather than the product.
+
+struct VisionResizeParams {
+ uint sourceWidth;
+ uint sourceHeight;
+ uint destinationWidth;
+ uint destinationHeight;
+ uint sourceRowBytes;
+ uint destinationRowBytes;
+ uint tapStride; // weights per output index, zero-padded
+ int precision; // fixed-point shift
+};
+
+inline uchar apply_taps(int accumulator, int precision) {
+ int value = accumulator >> precision;
+ return (uchar)clamp(value, 0, 255);
+}
+
+kernel void vision_resize_horizontal(
+ device const uchar *source [[buffer(0)]],
+ device uchar *destination [[buffer(1)]],
+ device const int *starts [[buffer(2)]],
+ device const short *weights [[buffer(3)]],
+ constant VisionResizeParams &params [[buffer(4)]],
+ uint2 gid [[thread_position_in_grid]])
+{
+ if (gid.x >= params.destinationWidth || gid.y >= params.sourceHeight) { return; }
+
+ const int rounding = 1 << (params.precision - 1);
+ const uint start = (uint)starts[gid.x];
+ const device short *tap = weights + gid.x * params.tapStride;
+ const device uchar *inputRow = source + gid.y * params.sourceRowBytes;
+ device uchar *outputRow = destination + gid.y * params.destinationRowBytes;
+
+ int accumulator[4] = { rounding, rounding, rounding, rounding };
+ for (uint index = 0; index < params.tapStride; ++index) {
+ const int weight = (int)tap[index];
+ if (weight == 0) { continue; }
+ const device uchar *pixel = inputRow + (start + index) * 4;
+ accumulator[0] += (int)pixel[0] * weight;
+ accumulator[1] += (int)pixel[1] * weight;
+ accumulator[2] += (int)pixel[2] * weight;
+ accumulator[3] += (int)pixel[3] * weight;
+ }
+ device uchar *out = outputRow + gid.x * 4;
+ out[0] = apply_taps(accumulator[0], params.precision);
+ out[1] = apply_taps(accumulator[1], params.precision);
+ out[2] = apply_taps(accumulator[2], params.precision);
+ out[3] = apply_taps(accumulator[3], params.precision);
+}
+
+kernel void vision_resize_vertical(
+ device const uchar *source [[buffer(0)]],
+ device uchar *destination [[buffer(1)]],
+ device const int *starts [[buffer(2)]],
+ device const short *weights [[buffer(3)]],
+ constant VisionResizeParams &params [[buffer(4)]],
+ uint2 gid [[thread_position_in_grid]])
+{
+ // One thread per output byte, as the CPU pass walks `sourceWidth * 4`.
+ const uint columnBytes = params.sourceWidth * 4;
+ if (gid.x >= columnBytes || gid.y >= params.destinationHeight) { return; }
+
+ const int rounding = 1 << (params.precision - 1);
+ const uint start = (uint)starts[gid.y];
+ const device short *tap = weights + gid.y * params.tapStride;
+
+ int accumulator = rounding;
+ for (uint index = 0; index < params.tapStride; ++index) {
+ const int weight = (int)tap[index];
+ if (weight == 0) { continue; }
+ accumulator += (int)source[(start + index) * params.sourceRowBytes + gid.x]
+ * weight;
+ }
+ destination[gid.y * params.destinationRowBytes + gid.x] =
+ apply_taps(accumulator, params.precision);
+}
diff --git a/Sources/TurboFieldfare/Runtime/Configuration/RuntimeConfiguration.swift b/Sources/TurboFieldfare/Runtime/Configuration/RuntimeConfiguration.swift
index 9533cac7..8105b3e6 100644
--- a/Sources/TurboFieldfare/Runtime/Configuration/RuntimeConfiguration.swift
+++ b/Sources/TurboFieldfare/Runtime/Configuration/RuntimeConfiguration.swift
@@ -21,7 +21,7 @@ public enum RuntimeExpertCachePolicy: String, Codable, Sendable {
public struct RuntimeConfiguration: Sendable, Equatable {
public static let allowedExpertCacheSlots = [8, 16, 24, 32]
- public static let allowedPrefillChunkTokens = [32, 64, 128]
+ public static let allowedPrefillChunkTokens = PrefillRuntimeConfig.allowedChunkTokens
public static let minimumExpertCacheSlotsForChunkedPrefill = 16
public let expertCacheSlots: Int
diff --git a/Sources/TurboFieldfare/Runtime/Generation/Generator.swift b/Sources/TurboFieldfare/Runtime/Generation/Generator.swift
index 52a218b2..ac490189 100644
--- a/Sources/TurboFieldfare/Runtime/Generation/Generator.swift
+++ b/Sources/TurboFieldfare/Runtime/Generation/Generator.swift
@@ -5,6 +5,11 @@ public enum StopReason: Sendable, Equatable {
case endOfTurn
case maxTokens
case stopString
+ /// The caller's `shouldStop` asked the loop to end. Unlike `.stopString` no
+ /// text was withheld: everything decoded was reported, and the final sampled
+ /// token sits in `uncommittedBoundaryTokenIDs` exactly as it does for
+ /// `.maxTokens`.
+ case cancelled
case toolCalls
}
diff --git a/Sources/TurboFieldfare/Runtime/Generation/LogitProducer.swift b/Sources/TurboFieldfare/Runtime/Generation/LogitProducer.swift
index 41881393..5bb351db 100644
--- a/Sources/TurboFieldfare/Runtime/Generation/LogitProducer.swift
+++ b/Sources/TurboFieldfare/Runtime/Generation/LogitProducer.swift
@@ -48,3 +48,12 @@ protocol ChunkedPrefillRunner: LogitProducer {
into logits: MTLBuffer,
onProgress: (Int) -> Void) async throws -> PrefillResult
}
+
+protocol MultimodalPrefillRunner: LogitProducer {
+ func prefillMultimodal(input: MultimodalPrefillInput,
+ startPosition: Int,
+ outputMode: PrefillOutputMode,
+ config: PrefillRuntimeConfig,
+ into logits: MTLBuffer,
+ onProgress: (Int) -> Void) async throws -> PrefillResult
+}
diff --git a/Sources/TurboFieldfare/Runtime/Generation/RawCompletion.swift b/Sources/TurboFieldfare/Runtime/Generation/RawCompletion.swift
index 2f3108c5..af4923f1 100644
--- a/Sources/TurboFieldfare/Runtime/Generation/RawCompletion.swift
+++ b/Sources/TurboFieldfare/Runtime/Generation/RawCompletion.swift
@@ -81,6 +81,7 @@ extension GenerationConfig {
public func runRawCompletion(producer: any LogitProducer,
tokenizer: GFTokenizer,
promptIds: [Int32],
+ multimodalInput: MultimodalPrefillInput? = nil,
config: GenerationConfig,
context: MetalContext,
scratch: RawCompletionScratch,
@@ -114,6 +115,22 @@ public func runRawCompletion(producer: any LogitProducer,
}
cachedPromptTokens = count
}
+ if let multimodalInput {
+ // Under resume the multimodal input is the tail that still has to be
+ // prefilled, so it must match the prompt suffix rather than the whole
+ // prompt. `prefillMultimodal` already prefills from `startPosition`.
+ guard multimodalInput.effectiveTokenIDs
+ == Array(promptIds.dropFirst(cachedPromptTokens)) else {
+ throw GeneratorError.invalidContinuation(
+ "multimodal effective token IDs do not match the prompt")
+ }
+ }
+ // Image spans are served only by the chunked prefill path, and a prefill
+ // config that cannot serve them is a performance setting, not a decision to
+ // drop the images.
+ let prefillConfig = multimodalInput == nil
+ ? prefillConfig
+ : (prefillConfig.coercedForImagePrompt() ?? prefillConfig)
let computedPrefillTokens = promptIds.count - cachedPromptTokens
var detok = GFDetokenizer(tokenizer: tokenizer,
@@ -138,8 +155,41 @@ public func runRawCompletion(producer: any LogitProducer,
var position = cachedPromptTokens
var prefillSeed: PrefillSeed?
let prefillTokens = promptIds[cachedPromptTokens...]
- switch prefillConfig.mode {
- case .chunked where producer is any ChunkedPrefillRunner:
+ switch (multimodalInput, prefillConfig.mode) {
+ case (.some(let input), .chunked) where producer is any MultimodalPrefillRunner:
+ let multimodal = producer as! any MultimodalPrefillRunner
+ let mode: PrefillOutputMode = fusedGreedy ? .greedyIfAvailable : .logits
+ let result = try await multimodal.prefillMultimodal(
+ input: input,
+ startPosition: position,
+ outputMode: mode,
+ config: prefillConfig,
+ into: scratch.logits
+ ) { done in
+ // The suffix-local count plus what the KV already holds. Without the
+ // offset a 300-token image turn on a 5,000-token KV showed 1 of 5,300.
+ onProgress(.prefill(done: cachedPromptTokens + done,
+ total: promptIds.count))
+ }
+ if mode == .logits, result.seed != .logitsWritten {
+ throw PrefillError.unsupportedPrefillSeed(
+ "RawCompletion multimodal prefill requested logits but producer returned \(result.seed)")
+ }
+ if case .greedyToken = result.seed, !config.isPureGreedy {
+ throw PrefillError.unsupportedPrefillSeed(
+ "RawCompletion multimodal prefill returned a greedy token for a sampling config")
+ }
+ position = result.newPosition
+ prefillSeed = result.seed
+ // Only the suffix: under resume the cached prefix is already in history,
+ // and appending the whole prompt would duplicate it.
+ history.append(contentsOf: prefillTokens)
+ case (.some, _):
+ // The coercion above leaves an image prompt in chunked mode, so the only
+ // way here is a producer that cannot run image spans at all.
+ throw PrefillError.chunkedUnsupported(
+ "multimodal prefill requires a MultimodalPrefillRunner-backed runtime")
+ case (.none, .chunked) where producer is any ChunkedPrefillRunner:
let chunked = producer as! any ChunkedPrefillRunner
let mode: PrefillOutputMode = fusedGreedy ? .greedyIfAvailable : .logits
let result = try await chunked.prefillChunked(tokens: prefillTokens,
@@ -160,10 +210,10 @@ public func runRawCompletion(producer: any LogitProducer,
position = result.newPosition
prefillSeed = result.seed
history.append(contentsOf: prefillTokens)
- case .chunked:
+ case (.none, .chunked):
throw PrefillError.chunkedUnsupported(
PrefillError.chunkedRequiresChunkedRunnerReason)
- case .off:
+ case (.none, .off):
for t in prefillTokens {
try Task.checkCancellation()
try await producer.produce(token: t, position: position, into: scratch.logits)
@@ -218,12 +268,17 @@ public func runRawCompletion(producer: any LogitProducer,
let visible = stopMatcher.push(delta)
onProgress(.token(index: generated - 1, id: tokenID, delta: visible))
- let hitStopString = stopMatcher.isStopped || shouldStop()
+ // Cancellation is not a stop-string match: reporting it as one made a
+ // user pressing Stop indistinguishable from a configured stop string,
+ // and `stopStringFiltered` is computed from `isStopped` rather than the
+ // reason, so the two disagreed about the same run.
+ let hitStopString = stopMatcher.isStopped
+ let cancelled = !hitStopString && shouldStop()
let hitMax = generated >= config.maxNewTokens
- if hitStopString || hitMax {
+ if hitStopString || cancelled || hitMax {
let tail = stopMatcher.push(detok.flush()) + stopMatcher.finish()
if !tail.isEmpty { onProgress(.tail(tail)) }
- reason = hitStopString ? .stopString : .maxTokens
+ reason = hitStopString ? .stopString : (cancelled ? .cancelled : .maxTokens)
break
}
diff --git a/Sources/TurboFieldfare/Runtime/Generation/Sampler.swift b/Sources/TurboFieldfare/Runtime/Generation/Sampler.swift
index 16d7b53a..45cb5483 100644
--- a/Sources/TurboFieldfare/Runtime/Generation/Sampler.swift
+++ b/Sources/TurboFieldfare/Runtime/Generation/Sampler.swift
@@ -43,6 +43,16 @@ public struct GenerationConfig: Sendable {
throw GeneratorError.invalidGenerationConfig(
"temperature must be finite and nonnegative")
}
+ // Its sibling above has been checked since this method existed; this one
+ // never was, so an infinite penalty reached the kernel and quietly
+ // degraded the output instead of refusing. Every CLI float guard without
+ // an upper bound admits infinity, and the result was a count that broke
+ // into another language and then apologised for itself, where the
+ // baseline counted correctly to eight.
+ guard repetitionPenalty.isFinite, repetitionPenalty > 0 else {
+ throw GeneratorError.invalidGenerationConfig(
+ "repetitionPenalty must be finite and greater than zero")
+ }
if let topK, !(1...256).contains(topK) {
throw GeneratorError.invalidGenerationConfig(
"topK must be between 1 and 256")
diff --git a/Sources/TurboFieldfare/Runtime/Inference/Model.swift b/Sources/TurboFieldfare/Runtime/Inference/Model.swift
index c1ab8c47..c4e09361 100644
--- a/Sources/TurboFieldfare/Runtime/Inference/Model.swift
+++ b/Sources/TurboFieldfare/Runtime/Inference/Model.swift
@@ -722,4 +722,43 @@ extension Model {
}
}
+
+ /// Releases routed-expert streamers and their slot scratch before vision
+ /// encoding, so the tower's bounded scratch does not stack on top of the
+ /// expert cache on an 8 GB machine.
+ ///
+ /// The caller must serialize this transition against forward execution.
+ public func prepareExpertResidencyForVision(
+ _ policy: VisionResidencyPolicy,
+ gpuDrainNanoseconds: UInt64 = 0
+ ) -> VisionExpertResidencyTransition {
+ let start = clock_gettime_nsec_np(CLOCK_UPTIME_RAW)
+ return streamersQueue.sync {
+ let releasedLayerCount = streamersBox.streamers.compactMap { $0 }.count
+ let releasedBytes = streamersBox.streamers.compactMap { $0 }.reduce(UInt64(0)) {
+ $0 + $1.diagnosticSlotScratchBytes
+ }
+ if policy == .onDemand {
+ var released = streamersBox.streamers
+ streamersBox.streamers = Array(
+ repeating: nil, count: packedExpertsLayout.numLayers)
+ // `layerVerified` deliberately survives the release. Clearing it
+ // would make every image turn from the second on re-verify all
+ // 30 packed expert files, ~12.9 GB, inside this queue.
+ released.removeAll()
+ }
+ let remaining = streamersBox.streamers.compactMap { $0 }
+ return VisionExpertResidencyTransition(
+ policy: policy,
+ gpuDrainNanoseconds: gpuDrainNanoseconds,
+ releasedLayerCount: policy == .onDemand ? releasedLayerCount : 0,
+ releasedSlotScratchBytes: policy == .onDemand ? releasedBytes : 0,
+ remainingOpenLayerCount: remaining.count,
+ remainingSlotScratchBytes: remaining.reduce(UInt64(0)) {
+ $0 + $1.diagnosticSlotScratchBytes
+ },
+ wallNanoseconds: clock_gettime_nsec_np(CLOCK_UPTIME_RAW) - start)
+ }
+ }
+
}
diff --git a/Sources/TurboFieldfare/Runtime/Inference/RealForwardRunner.swift b/Sources/TurboFieldfare/Runtime/Inference/RealForwardRunner.swift
index 04b652e8..d0b12160 100644
--- a/Sources/TurboFieldfare/Runtime/Inference/RealForwardRunner.swift
+++ b/Sources/TurboFieldfare/Runtime/Inference/RealForwardRunner.swift
@@ -130,7 +130,7 @@ internal enum PrefillProjectionDispatchPolicy {
}
}
-public final class RealForwardRunner: ChunkedPrefillRunner, ContextWindowReporting, ContinuableLogitProducer, @unchecked Sendable {
+public final class RealForwardRunner: ChunkedPrefillRunner, MultimodalPrefillRunner, ContextWindowReporting, ContinuableLogitProducer, @unchecked Sendable {
private struct LayerSharedExpertProjections {
let gate: SharedExpertInt8Proj
let up: SharedExpertInt8Proj
@@ -247,7 +247,9 @@ public final class RealForwardRunner: ChunkedPrefillRunner, ContextWindowReporti
maxContext: maxContext,
fp16RingEnabled: useFP16Ring,
slidingWindow: cfg.slidingWindow,
- maxPrefillChunkTokens: PrefillRuntimeConfig.maxChunkTokens)
+ maxPrefillChunkTokens: max(
+ PrefillRuntimeConfig.maxChunkTokens,
+ VisionConfig().maximumPooledTokens))
self.embedInt4 = try EmbedLookupInt4(context: context)
self.rms = try RMSNorm(context: context)
@@ -516,7 +518,7 @@ public final class RealForwardRunner: ChunkedPrefillRunner, ContextWindowReporti
let spans = PrefillChunkPlanner.spans(tokenCount: tokens.count,
startPosition: startPosition,
config: config)
- for (spanIndex, span) in spans.enumerated() {
+ try await PrefillSpanIteration.forEachSpan(spans) { spanIndex, span in
let lower = tokens.index(tokens.startIndex, offsetBy: span.tokenOffset)
let upper = tokens.index(lower, offsetBy: span.tokenCount)
try await executePrefillChunk(
@@ -537,9 +539,102 @@ public final class RealForwardRunner: ChunkedPrefillRunner, ContextWindowReporti
seed: .logitsWritten)
}
+
+ public func prefillMultimodal(input: MultimodalPrefillInput,
+ startPosition: Int,
+ outputMode: PrefillOutputMode,
+ config: PrefillRuntimeConfig,
+ into logits: MTLBuffer,
+ onProgress: (Int) -> Void) async throws -> PrefillResult {
+ try prefillChunkState.requireClean(operation: "prefillMultimodal")
+ // The same property `coercedForImagePrompt()` repairs, so the guard and
+ // the coercion cannot drift apart.
+ guard config.servesImagePrompt else {
+ throw PrefillError.chunkedUnsupported(
+ "multimodal prefill requires the complete chunked prefill path")
+ }
+ let tokens = input.embeddingTokenIDs
+ guard startPosition >= 0,
+ startPosition + tokens.count <= maxContext else {
+ throw PrefillError.chunkedUnsupported(
+ "multimodal prefill range exceeds maxContext \(maxContext)")
+ }
+ let kvPosition = kv?.position ?? 0
+ guard kvPosition == startPosition else {
+ throw PrefillError.chunkedUnsupported(
+ "multimodal prefill cursor \(kvPosition) != startPosition \(startPosition)")
+ }
+ guard !tokens.isEmpty else {
+ return PrefillResult(newPosition: startPosition, seed: .logitsWritten)
+ }
+
+ // The planner applies the same clamp the scratch layout does. Cutting at
+ // the raw `config.chunkTokens` let a caller size a 280-token scratch and
+ // then hand it a larger chunk, which died on the guard.
+ let textChunkTokens = min(config.chunkTokens, PrefillRuntimeConfig.maxChunkTokens)
+ let work = PrefillChunkPlanner.multimodalWork(
+ tokenCount: tokens.count,
+ imageRanges: input.imageSpans.map(\.tokenRange),
+ chunkTokens: config.chunkTokens)
+ let imageBuffers = input.imageSpans.map(\.features.buffer)
+
+ // One layout for the whole turn, sized for the largest item in it.
+ // Keying the single-slot cache on each item's exact chunk size made a
+ // text-image-text prompt free and reallocate the entire chunk scratch at
+ // every boundary, twice per image span, every turn.
+ let pooledTokens = VisionConfig().maximumPooledTokens
+ let hasImages = work.contains(where: \.isImage)
+ let layoutTokens = hasImages
+ ? max(config.chunkTokens, pooledTokens)
+ : config.chunkTokens
+ let layoutLimit = hasImages
+ ? max(PrefillRuntimeConfig.maxChunkTokens, pooledTokens)
+ : PrefillRuntimeConfig.maxChunkTokens
+ let scratch = try ensurePrefillScratch(
+ config: config.replacingChunkTokens(layoutTokens),
+ chunkTokenLimit: layoutLimit)
+
+ var completed = 0
+ for (index, item) in work.enumerated() {
+ try Task.checkCancellation()
+ let isImage = item.isImage
+ let imageFeatures = item.imageIndex.map { imageBuffers[$0] }
+ // Every item executes under the chunk size it was planned at.
+ let chunkConfig = config.replacingChunkTokens(
+ isImage ? item.range.count : textChunkTokens)
+ let lower = tokens.index(tokens.startIndex, offsetBy: item.range.lowerBound)
+ let upper = tokens.index(tokens.startIndex, offsetBy: item.range.upperBound)
+ try await executePrefillChunk(
+ tokens: tokens[lower..<upper],
+ startPosition: startPosition + item.range.lowerBound,
+ outputMode: outputMode,
+ logits: logits,
+ scratch: scratch,
+ config: chunkConfig,
+ writeFinalHead: index == work.count - 1,
+ embeddingOverride: imageFeatures,
+ bidirectionalBlock: isImage
+ ? (startPosition + item.range.lowerBound)..<(startPosition + item.range.upperBound)
+ : nil)
+ completed += item.range.count
+ onProgress(completed)
+ }
+ if outputMode == .greedyIfAvailable, useFusedGreedyHead {
+ return PrefillResult(newPosition: startPosition + tokens.count,
+ seed: .greedyToken(lastGreedyToken))
+ }
+ return PrefillResult(newPosition: startPosition + tokens.count,
+ seed: .logitsWritten)
+ }
+
@discardableResult
- private func ensurePrefillScratch(config: PrefillRuntimeConfig) throws -> PrefillChunkScratchBuffers {
- let layout = PrefillChunkScratchLayout(config: cfg, runtime: config)
+ private func ensurePrefillScratch(
+ config: PrefillRuntimeConfig,
+ chunkTokenLimit: Int = PrefillRuntimeConfig.maxChunkTokens
+ ) throws -> PrefillChunkScratchBuffers {
+ let layout = PrefillChunkScratchLayout(config: cfg,
+ chunkTokens: config.chunkTokens,
+ chunkTokenLimit: chunkTokenLimit)
if let scratch = prefillScratch, scratch.layout == layout {
return scratch
}
@@ -554,7 +649,9 @@ public final class RealForwardRunner: ChunkedPrefillRunner, ContextWindowReporti
logits: MTLBuffer,
scratch: PrefillChunkScratchBuffers,
config: PrefillRuntimeConfig,
- writeFinalHead: Bool) async throws {
+ writeFinalHead: Bool,
+ embeddingOverride: MTLBuffer? = nil,
+ bidirectionalBlock: Range<Int>? = nil) async throws {
guard !tokens.isEmpty else { return }
guard kv != nil else {
throw PrefillError.chunkedUnsupported("chunked prefill attention requires FP16 KV")
@@ -646,7 +743,7 @@ public final class RealForwardRunner: ChunkedPrefillRunner, ContextWindowReporti
if tokenCount >= 32,
family == .q || family == .kv || family == .o,
let candidate = prefillMPPAffineInt4 {
- let path = candidate.encode(
+ let metadata = candidate.encode(
commandBuffer: commandBuffer,
weights: weights.buffer,
weightsOffset: Int(weights.offset),
@@ -659,7 +756,7 @@ public final class RealForwardRunner: ChunkedPrefillRunner, ContextWindowReporti
m: tokenCount,
n: rows,
k: columns)
- if path == .affineThreadgroupF16 {
+ if metadata.path == .affineThreadgroupF16 {
return
}
}
@@ -764,6 +861,23 @@ public final class RealForwardRunner: ChunkedPrefillRunner, ContextWindowReporti
guard var cb = ctx.queue.makeCommandBuffer() else {
throw ModelError.residentBufferWrapFailed
}
+ if let embeddingOverride {
+ // The override spans the whole chunk — the planner emits image spans
+ // as standalone chunks — so the INT4 gather it would cover is
+ // skipped rather than encoded and fully overwritten.
+ let bytes = t * D * MemoryLayout<Float16>.stride
+ guard embeddingOverride.length >= bytes,
+ let blit = cb.makeBlitCommandEncoder() else {
+ throw VisionRuntimeError.invalidInput(
+ "projected image feature buffer is too small")
+ }
+ blit.copy(from: embeddingOverride,
+ sourceOffset: 0,
+ to: scratch.hidden,
+ destinationOffset: 0,
+ size: bytes)
+ blit.endEncoding()
+ } else {
prefillEmbed.encode(commandBuffer: cb,
table: emb.buffer,
tableOffset: Int(emb.offset),
@@ -776,6 +890,7 @@ public final class RealForwardRunner: ChunkedPrefillRunner, ContextWindowReporti
t: UInt32(t),
d: UInt32(D),
outScale: sqrtHidden)
+ }
for L in 0..<cfg.numLayers {
model.beginOpeningRoutedExpertStreamer(layer: L)
@@ -869,7 +984,11 @@ public final class RealForwardRunner: ChunkedPrefillRunner, ContextWindowReporti
kvTokenStrideElements: UInt32(kvDim),
qTokenStrideElements: UInt32(qDim),
oTokenStrideElements: UInt32(qDim),
- scale: 1.0)
+ scale: 1.0,
+ bidirectionalBlockStart: UInt32(
+ isFull ? 0 : bidirectionalBlock?.lowerBound ?? 0),
+ bidirectionalBlockEnd: UInt32(
+ isFull ? 0 : bidirectionalBlock?.upperBound ?? 0))
if let kv {
let keyBuffer = kv.keyBuffer(layer: L, validTokenCount: startPosition + t)
let valueBuffer = kv.valueBuffer(layer: L, validTokenCount: startPosition + t)
@@ -884,6 +1003,7 @@ public final class RealForwardRunner: ChunkedPrefillRunner, ContextWindowReporti
out: scratch.attentionOutput,
params: params,
kvRingCapacity: activeRingCapacity,
+ layerKind: isFull ? .full : .slidingWindow,
path: prefillAttentionPath)
} else {
throw PrefillError.chunkedUnsupported(
diff --git a/Sources/TurboFieldfare/Runtime/Prefill/PrefillChunkScratch.swift b/Sources/TurboFieldfare/Runtime/Prefill/PrefillChunkScratch.swift
index e154e8b0..20413358 100644
--- a/Sources/TurboFieldfare/Runtime/Prefill/PrefillChunkScratch.swift
+++ b/Sources/TurboFieldfare/Runtime/Prefill/PrefillChunkScratch.swift
@@ -12,8 +12,9 @@ struct PrefillChunkScratchLayout: Sendable, Equatable {
init(config: ArchConfig,
chunkTokens: Int,
- routedPairMicrobatchRows: Int = 32) {
- self.chunkTokens = max(1, min(chunkTokens, 128))
+ routedPairMicrobatchRows: Int = 32,
+ chunkTokenLimit: Int = PrefillRuntimeConfig.maxChunkTokens) {
+ self.chunkTokens = max(1, min(chunkTokens, chunkTokenLimit))
self.hiddenSize = config.hiddenSize
self.maxQElementsPerToken = config.numHeads * max(config.headDim, config.fullHeadDim)
self.maxKVElementsPerToken = max(config.numKVHeads * config.headDim,
@@ -24,10 +25,6 @@ struct PrefillChunkScratchLayout: Sendable, Equatable {
self.routedPairMicrobatchRows = max(1, min(routedPairMicrobatchRows, 128))
}
- init(config: ArchConfig, runtime: PrefillRuntimeConfig) {
- self.init(config: config,
- chunkTokens: runtime.chunkTokens)
- }
var hiddenElements: Int { chunkTokens * hiddenSize }
var normedElements: Int { hiddenElements }
diff --git a/Sources/TurboFieldfare/Runtime/Prefill/PrefillRuntimeConfig.swift b/Sources/TurboFieldfare/Runtime/Prefill/PrefillRuntimeConfig.swift
index b72fa7be..41a4ac60 100644
--- a/Sources/TurboFieldfare/Runtime/Prefill/PrefillRuntimeConfig.swift
+++ b/Sources/TurboFieldfare/Runtime/Prefill/PrefillRuntimeConfig.swift
@@ -83,7 +83,54 @@ struct PrefillChunkSpan: Sendable, Equatable {
}
+/// One item of a multimodal prefill turn: either a run of text small enough to
+/// fit the chunk scratch, or exactly one image span, which executes whole.
+struct PrefillWorkItem: Sendable, Equatable {
+ let range: Range<Int>
+ let imageIndex: Int?
+
+ init(range: Range<Int>, imageIndex: Int?) {
+ self.range = range
+ self.imageIndex = imageIndex
+ }
+
+ var isImage: Bool { imageIndex != nil }
+}
+
enum PrefillChunkPlanner {
+ /// Splits a multimodal prompt into the items a turn executes, in order.
+ ///
+ /// Text is cut at the same clamp the scratch layout applies, so the split
+ /// and the buffer it runs against can never disagree; image spans pass
+ /// through whole, because an image's features are one indivisible block.
+ /// `imageRanges` must be sorted, non-overlapping, and inside `tokenCount`.
+ static func multimodalWork(tokenCount: Int,
+ imageRanges: [Range<Int>],
+ chunkTokens: Int) -> [PrefillWorkItem] {
+ precondition(tokenCount >= 0, "prefill tokenCount must be non-negative")
+ let chunk = max(1, min(chunkTokens, PrefillRuntimeConfig.maxChunkTokens))
+ var work: [PrefillWorkItem] = []
+
+ func appendText(_ range: Range<Int>) {
+ guard !range.isEmpty else { return }
+ var offset = range.lowerBound
+ while offset < range.upperBound {
+ let end = min(range.upperBound, offset + chunk)
+ work.append(PrefillWorkItem(range: offset..<end, imageIndex: nil))
+ offset = end
+ }
+ }
+
+ var cursor = 0
+ for (index, imageRange) in imageRanges.enumerated() {
+ appendText(cursor..<imageRange.lowerBound)
+ work.append(PrefillWorkItem(range: imageRange, imageIndex: index))
+ cursor = imageRange.upperBound
+ }
+ appendText(cursor..<tokenCount)
+ return work
+ }
+
static func spans(tokenCount: Int,
startPosition: Int,
config: PrefillRuntimeConfig) -> [PrefillChunkSpan] {
@@ -168,7 +215,48 @@ public struct PrefillRuntimeConfig: Sendable, Equatable {
case chunked
}
- public static let maxChunkTokens = 128
+ /// Chunked prefill loops chunks outside layers, so each chunk streams that
+ /// layer's experts again and read volume tracks chunk count and nothing
+ /// else. On an 11,612-token prompt that meant 578 GB read from a 12 GB pool
+ /// with no cache hits at all.
+ ///
+ /// 256 is free: the runner floors the chunk at
+ /// `VisionConfig().maximumPooledTokens` (280) for the KV ring and for the
+ /// multimodal scratch layout, so every size up to 280 produces byte-identical
+ /// geometry. 512 is the first size that costs anything, and raising this past
+ /// 280 should come with a test that asserts ring bytes the way
+ /// `PrefillChunkScratchTests` asserts scratch.
+ public static let maxChunkTokens = 256
+
+ /// Chunk sizes a caller may select. Capped at `maxChunkTokens` - see there
+ /// for why the larger sizes the scratch layout can handle are not offered.
+ public static let allowedChunkTokens = [32, 64, 128, 256]
+
+ /// The largest selectable chunk no greater than `requested`.
+ ///
+ /// Capping at `maxChunkTokens` is not enough on its own: a bare cap lets a
+ /// caller ask for a size `--prefill-chunk-tokens` rejects. Snapping to the
+ /// same list keeps the two doors agreeing on what is legal.
+ public static func supportedChunkTokens(_ requested: Int) -> Int {
+ let capped = max(1, min(requested, maxChunkTokens))
+ return allowedChunkTokens.last { $0 <= capped } ?? capped
+ }
+
+ /// The smallest allowed chunk that covers `promptTokens`, capped.
+ ///
+ /// One chunk means each layer's experts are read once for the whole
+ /// prefill, which is the floor, so this asks for the smallest size that
+ /// reaches it and never more than the prompt needs.
+ public static func autoChunkTokens(
+ promptTokens: Int,
+ cap: Int = maxChunkTokens
+ ) -> Int {
+ let ceiling = min(cap, maxChunkTokens)
+ for candidate in allowedChunkTokens where candidate >= promptTokens {
+ return min(candidate, ceiling)
+ }
+ return ceiling
+ }
public let mode: Mode
public let chunkTokens: Int
@@ -188,6 +276,30 @@ public struct PrefillRuntimeConfig: Sendable, Equatable {
production(chunkTokens: 128)
}
+ /// This config at a different chunk size, all other settings intact. The
+ /// multimodal path runs each work item at the size it was planned at.
+ public func replacingChunkTokens(_ tokens: Int) -> PrefillRuntimeConfig {
+ PrefillRuntimeConfig(mode: mode, chunkTokens: max(1, tokens))
+ }
+
+ /// Whether the chunked path an image prompt needs is switched on. This tree
+ /// has no per-stage toggles, so the mode is the whole requirement.
+ ///
+ /// This is deliberately not "the image turn will succeed": a chunked config
+ /// is still held to its prompt-token budget afterwards.
+ public var servesImagePrompt: Bool { mode == .chunked }
+
+ /// The config an image prompt can run under, or nil when it already runs.
+ ///
+ /// Image spans are only served by the chunked multimodal path, so anything
+ /// short of it threw after the model was loaded and every image had been
+ /// encoded on the GPU. Prefill mode is a performance choice; whether images
+ /// work at all is not, so an image turn is coerced rather than refused.
+ /// Callers report the coercion.
+ public func coercedForImagePrompt() -> PrefillRuntimeConfig? {
+ servesImagePrompt ? nil : .defaultChunked
+ }
+
public static func production(chunkTokens: Int) -> PrefillRuntimeConfig {
precondition(RuntimeConfiguration.allowedPrefillChunkTokens.contains(chunkTokens),
"unsupported prefill chunk size")
diff --git a/Sources/TurboFieldfare/Runtime/Prefill/PrefillSpanIteration.swift b/Sources/TurboFieldfare/Runtime/Prefill/PrefillSpanIteration.swift
new file mode 100644
index 00000000..d2cbf71f
--- /dev/null
+++ b/Sources/TurboFieldfare/Runtime/Prefill/PrefillSpanIteration.swift
@@ -0,0 +1,27 @@
+import Foundation
+
+/// Iterates prefill spans, polling cancellation before each one.
+///
+/// This exists to be testable. The cancellation check lives inside
+/// `RealForwardRunner.prefillChunked`, and every test double for that runner
+/// implements `prefillChunked` itself - the protocol seam *is* the loop - so no
+/// test in the suite could reach it. The defect it guards against was found by
+/// timing a `SIGINT` by hand: a cancelled 7,000-token prompt kept prefilling for
+/// 50 seconds, against 0.58 seconds when the same interrupt arrived during
+/// decode, because this loop never polled while the multimodal loop beside it
+/// always had.
+enum PrefillSpanIteration {
+ /// Runs `body` for each span, throwing `CancellationError` before the next
+ /// one if the task was cancelled. A chunk already in flight still finishes:
+ /// its GPU work is not interruptible, which is why the observed latency
+ /// after the fix is one chunk rather than zero.
+ static func forEachSpan(
+ _ spans: [PrefillChunkSpan],
+ _ body: (Int, PrefillChunkSpan) async throws -> Void
+ ) async throws {
+ for (index, span) in spans.enumerated() {
+ try Task.checkCancellation()
+ try await body(index, span)
+ }
+ }
+}
diff --git a/Sources/TurboFieldfare/Runtime/Vision/MultimodalPrefillInput.swift b/Sources/TurboFieldfare/Runtime/Vision/MultimodalPrefillInput.swift
new file mode 100644
index 00000000..2578f2d2
--- /dev/null
+++ b/Sources/TurboFieldfare/Runtime/Vision/MultimodalPrefillInput.swift
@@ -0,0 +1,122 @@
+import Metal
+
+public enum MultimodalPrefillInputError: Error, Equatable {
+ case tokenCountMismatch
+ case invalidImageTokenRange
+ case featureShapeMismatch
+}
+
+public struct MultimodalImageSpan: Sendable {
+ public let tokenRange: Range<Int>
+ public let features: VisionFeatures
+
+ public init(tokenRange: Range<Int>, features: VisionFeatures) {
+ self.tokenRange = tokenRange
+ self.features = features
+ }
+}
+
+public struct MultimodalPrefillInput: Sendable {
+ public let effectiveTokenIDs: [Int32]
+ public let embeddingTokenIDs: [Int32]
+ public let imageSpans: [MultimodalImageSpan]
+
+ public var imageTokenRange: Range<Int> { imageSpans[0].tokenRange }
+ public var imageFeatures: VisionFeatures { imageSpans[0].features }
+
+ /// The same input with `tokens` placed in front of it, spans shifted to
+ /// match. Used when a turn has to replay a boundary token the previous run
+ /// left outside the KV: without this the multimodal input no longer lines
+ /// up with the prefill suffix and the images were dropped instead.
+ public func prepending(_ tokens: [Int32]) throws -> MultimodalPrefillInput {
+ guard !tokens.isEmpty else { return self }
+ let shift = tokens.count
+ return try MultimodalPrefillInput(
+ effectiveTokenIDs: tokens + effectiveTokenIDs,
+ embeddingTokenIDs: tokens + embeddingTokenIDs,
+ imageSpans: imageSpans.map {
+ MultimodalImageSpan(
+ tokenRange: ($0.tokenRange.lowerBound + shift)
+ ..< ($0.tokenRange.upperBound + shift),
+ features: $0.features)
+ })
+ }
+
+ /// The tail of a rendered prompt, for resuming on a cached KV prefix. Spans
+ /// are rebased to the tail; a span that starts before `dropping` belongs to
+ /// the cached prefix, whose features are already in the KV and are not
+ /// available here, so it is rejected rather than re-injected.
+ public func suffix(dropping cachedTokens: Int) throws -> MultimodalPrefillInput {
+ guard cachedTokens >= 0, cachedTokens < effectiveTokenIDs.count else {
+ throw MultimodalPrefillInputError.invalidImageTokenRange
+ }
+ let kept = imageSpans.filter { $0.tokenRange.lowerBound >= cachedTokens }
+ guard kept.count == imageSpans.filter({
+ $0.tokenRange.upperBound > cachedTokens
+ }).count else {
+ // A span straddling the boundary cannot be split.
+ throw MultimodalPrefillInputError.invalidImageTokenRange
+ }
+ guard !kept.isEmpty else {
+ // Every image is already inside the cached prefix, so the tail is
+ // plain text and needs no multimodal input at all.
+ throw MultimodalPrefillInputError.invalidImageTokenRange
+ }
+ return try MultimodalPrefillInput(
+ effectiveTokenIDs: Array(effectiveTokenIDs.dropFirst(cachedTokens)),
+ embeddingTokenIDs: Array(embeddingTokenIDs.dropFirst(cachedTokens)),
+ imageSpans: kept.map {
+ MultimodalImageSpan(
+ tokenRange: ($0.tokenRange.lowerBound - cachedTokens)
+ ..< ($0.tokenRange.upperBound - cachedTokens),
+ features: $0.features)
+ })
+ }
+
+ public init(effectiveTokenIDs: [Int32],
+ embeddingTokenIDs: [Int32],
+ imageTokenRange: Range<Int>,
+ imageFeatures: VisionFeatures) throws {
+ try self.init(
+ effectiveTokenIDs: effectiveTokenIDs,
+ embeddingTokenIDs: embeddingTokenIDs,
+ imageSpans: [MultimodalImageSpan(
+ tokenRange: imageTokenRange,
+ features: imageFeatures)])
+ }
+
+ public init(effectiveTokenIDs: [Int32],
+ embeddingTokenIDs: [Int32],
+ imageSpans: [MultimodalImageSpan]) throws {
+ guard effectiveTokenIDs.count == embeddingTokenIDs.count else {
+ throw MultimodalPrefillInputError.tokenCountMismatch
+ }
+ // The span count is self-limiting: spans are ordered, non-overlapping and
+ // bounded by the prompt, so the prompt length caps how many can exist.
+ guard !imageSpans.isEmpty else {
+ throw MultimodalPrefillInputError.invalidImageTokenRange
+ }
+ var previousUpperBound = 0
+ for span in imageSpans {
+ let range = span.tokenRange
+ guard !range.isEmpty,
+ range.lowerBound >= previousUpperBound,
+ range.upperBound <= embeddingTokenIDs.count,
+ range.count <= VisionConfig().maximumPooledTokens else {
+ throw MultimodalPrefillInputError.invalidImageTokenRange
+ }
+ let featureBytes = range.count
+ * VisionConfig().textHiddenSize
+ * MemoryLayout<Float16>.stride
+ guard span.features.tokenCount == range.count,
+ span.features.hiddenSize == VisionConfig().textHiddenSize,
+ span.features.buffer.length >= featureBytes else {
+ throw MultimodalPrefillInputError.featureShapeMismatch
+ }
+ previousUpperBound = range.upperBound
+ }
+ self.effectiveTokenIDs = effectiveTokenIDs
+ self.embeddingTokenIDs = embeddingTokenIDs
+ self.imageSpans = imageSpans
+ }
+}
diff --git a/Sources/TurboFieldfare/Runtime/Vision/MultimodalPromptRenderer.swift b/Sources/TurboFieldfare/Runtime/Vision/MultimodalPromptRenderer.swift
new file mode 100644
index 00000000..a6e12b1a
--- /dev/null
+++ b/Sources/TurboFieldfare/Runtime/Vision/MultimodalPromptRenderer.swift
@@ -0,0 +1,148 @@
+import Foundation
+
+public enum MultimodalContentPart: Sendable, Equatable {
+ case text(String)
+ case image(id: UUID)
+}
+
+/// A continuation turn's content, before image token counts are known.
+public enum MultimodalContinuationPart: Sendable, Equatable {
+ case text(String)
+ case image
+}
+
+/// Tokens for a continuation turn. Ranges are relative to this turn, which is
+/// also the suffix handed to the runner, so they need no rebasing.
+public struct MultimodalContinuationTokens: Sendable, Equatable {
+ public let effectiveTokenIDs: [Int32]
+ public let embeddingTokenIDs: [Int32]
+ public let imageTokenRanges: [Range<Int>]
+}
+
+public struct MultimodalMessage: Sendable, Equatable {
+ public let role: GFTokenizer.Role
+ public let content: [MultimodalContentPart]
+ public let toolCalls: [GFTokenizer.HistoricalToolCall]
+ public let toolCallID: String?
+ public let name: String?
+
+ public init(role: GFTokenizer.Role,
+ content: [MultimodalContentPart],
+ toolCalls: [GFTokenizer.HistoricalToolCall] = [],
+ toolCallID: String? = nil,
+ name: String? = nil) {
+ self.role = role
+ self.content = content
+ self.toolCalls = toolCalls
+ self.toolCallID = toolCallID
+ self.name = name
+ }
+}
+
+public enum MultimodalPromptRendererError: Error, Equatable {
+ case emptyMessages
+ case emptyContent
+ case reservedImageMarker
+ case missingImage(UUID)
+ case unexpectedImage(UUID)
+ case placeholderMismatch
+}
+
+public enum MultimodalPromptRenderer {
+ public static let placeholder = "<|image|>"
+ public static let imageTokenID = Int32(258_880)
+ public static let beginImageTokenID = Int32(255_999)
+ public static let endImageTokenID = Int32(258_882)
+
+ public static func render(
+ messages: [MultimodalMessage],
+ featuresByID: [UUID: VisionFeatures],
+ tokenizer: GFTokenizer,
+ tools: [GFTokenizer.FunctionDefinition] = []
+ ) throws -> MultimodalPrefillInput {
+ guard !messages.isEmpty else { throw MultimodalPromptRendererError.emptyMessages }
+ var orderedImages: [(UUID, VisionFeatures)] = []
+ let tokenizerMessages = try messages.map { message in
+ guard !message.content.isEmpty || !message.toolCalls.isEmpty else {
+ throw MultimodalPromptRendererError.emptyContent
+ }
+ var text = ""
+ for part in message.content {
+ switch part {
+ case .text(let value):
+ guard !value.contains(placeholder) else {
+ throw MultimodalPromptRendererError.reservedImageMarker
+ }
+ text += value
+ case .image(let id):
+ guard let features = featuresByID[id] else {
+ throw MultimodalPromptRendererError.missingImage(id)
+ }
+ text += placeholder
+ orderedImages.append((id, features))
+ }
+ }
+ return GFTokenizer.Message(
+ role: message.role,
+ content: text,
+ toolCalls: message.toolCalls,
+ toolCallID: message.toolCallID,
+ name: message.name)
+ }
+ guard Set(orderedImages.map(\.0)) == Set(featuresByID.keys) else {
+ let used = Set(orderedImages.map(\.0))
+ throw MultimodalPromptRendererError.unexpectedImage(
+ featuresByID.keys.first { !used.contains($0) }!)
+ }
+
+ let usesToolTemplate = !tools.isEmpty || tokenizerMessages.contains {
+ $0.role == .developer || $0.role == .tool || !$0.toolCalls.isEmpty
+ }
+ let templateTokens: [Int32]
+ if usesToolTemplate {
+ templateTokens = try tokenizer.encodeToolChat(
+ messages: tokenizerMessages,
+ tools: tools)
+ } else {
+ let rendered = try tokenizer.applyChatTemplate(tokenizerMessages)
+ templateTokens = tokenizer.encode(rendered, addBOS: false)
+ }
+ let placeholders = templateTokens.indices.filter {
+ templateTokens[$0] == imageTokenID
+ }
+ guard placeholders.count == orderedImages.count else {
+ throw MultimodalPromptRendererError.placeholderMismatch
+ }
+
+ var effective: [Int32] = []
+ var embedding: [Int32] = []
+ var spans: [MultimodalImageSpan] = []
+ effective.reserveCapacity(
+ templateTokens.count + orderedImages.reduce(0) { $0 + $1.1.tokenCount + 1 })
+ embedding.reserveCapacity(effective.capacity)
+ var imageIndex = 0
+ for token in templateTokens {
+ guard token == imageTokenID else {
+ effective.append(token)
+ embedding.append(token)
+ continue
+ }
+ let features = orderedImages[imageIndex].1
+ effective.append(beginImageTokenID)
+ embedding.append(beginImageTokenID)
+ let lower = effective.count
+ effective.append(contentsOf: repeatElement(imageTokenID, count: features.tokenCount))
+ embedding.append(contentsOf: repeatElement(Int32(0), count: features.tokenCount))
+ spans.append(MultimodalImageSpan(
+ tokenRange: lower..<effective.count,
+ features: features))
+ effective.append(endImageTokenID)
+ embedding.append(endImageTokenID)
+ imageIndex += 1
+ }
+ return try MultimodalPrefillInput(
+ effectiveTokenIDs: effective,
+ embeddingTokenIDs: embedding,
+ imageSpans: spans)
+ }
+}
diff --git a/Sources/TurboFieldfare/Runtime/Vision/Preprocessing/Gemma4ImageGeometry.swift b/Sources/TurboFieldfare/Runtime/Vision/Preprocessing/Gemma4ImageGeometry.swift
new file mode 100644
index 00000000..11ea3eb2
--- /dev/null
+++ b/Sources/TurboFieldfare/Runtime/Vision/Preprocessing/Gemma4ImageGeometry.swift
@@ -0,0 +1,74 @@
+import Foundation
+
+public struct Gemma4ImageGeometry: Sendable, Equatable {
+ /// This initialiser is public and validates its inputs, so a degenerate
+ /// aspect ratio must throw rather than trap on overflow.
+ private static func checked(_ lhs: Int, _ rhs: Int) throws -> Int {
+ let (value, overflow) = lhs.multipliedReportingOverflow(by: rhs)
+ guard !overflow else {
+ throw VisionImageError.invalidMetadata("source dimensions overflow")
+ }
+ return value
+ }
+
+ public let processedWidth: Int
+ public let processedHeight: Int
+ public let patchGridWidth: Int
+ public let patchGridHeight: Int
+ public let patchCount: Int
+ public let softTokenCount: Int
+
+ public init(
+ sourceWidth: Int,
+ sourceHeight: Int,
+ config: VisionConfig = VisionConfig()
+ ) throws {
+ guard sourceWidth > 0, sourceHeight > 0 else {
+ throw VisionImageError.invalidMetadata("source dimensions must be positive")
+ }
+ let (sourcePixels, sourceOverflow) = sourceWidth.multipliedReportingOverflow(
+ by: sourceHeight)
+ guard !sourceOverflow else {
+ throw VisionImageError.invalidMetadata("source dimensions overflow")
+ }
+ let patchPixels = config.patchSize * config.patchSize
+ let targetPixels = config.maximumPatches * patchPixels
+ let factor = sqrt(Double(targetPixels) / Double(sourcePixels))
+ let sideMultiple = config.patchSize * config.poolingKernel
+ var height = Int(floor(factor * Double(sourceHeight) / Double(sideMultiple)))
+ * sideMultiple
+ var width = Int(floor(factor * Double(sourceWidth) / Double(sideMultiple)))
+ * sideMultiple
+ let maximumSide = (config.maximumPatches
+ / (config.poolingKernel * config.poolingKernel)) * sideMultiple
+ if height == 0 && width == 0 {
+ throw VisionImageError.invalidMetadata("aspect ratio produces zero target dimensions")
+ } else if height == 0 {
+ height = sideMultiple
+ width = min(try Self.checked(sourceWidth / sourceHeight, sideMultiple), maximumSide)
+ } else if width == 0 {
+ width = sideMultiple
+ height = min(try Self.checked(sourceHeight / sourceWidth, sideMultiple), maximumSide)
+ }
+ let (processedPixels, processedOverflow) = width.multipliedReportingOverflow(by: height)
+ guard !processedOverflow, processedPixels <= targetPixels else {
+ throw VisionImageError.invalidMetadata("target geometry exceeds patch budget")
+ }
+
+ let gridWidth = width / config.patchSize
+ let gridHeight = height / config.patchSize
+ let patches = gridWidth * gridHeight
+ guard gridWidth > 0, gridHeight > 0,
+ gridWidth.isMultiple(of: config.poolingKernel),
+ gridHeight.isMultiple(of: config.poolingKernel),
+ patches <= config.maximumPatches else {
+ throw VisionImageError.invalidMetadata("target patch grid is invalid")
+ }
+ processedWidth = width
+ processedHeight = height
+ patchGridWidth = gridWidth
+ patchGridHeight = gridHeight
+ patchCount = patches
+ softTokenCount = patches / (config.poolingKernel * config.poolingKernel)
+ }
+}
diff --git a/Sources/TurboFieldfare/Runtime/Vision/Preprocessing/Gemma4ImagePreprocessor.swift b/Sources/TurboFieldfare/Runtime/Vision/Preprocessing/Gemma4ImagePreprocessor.swift
new file mode 100644
index 00000000..59d4192b
--- /dev/null
+++ b/Sources/TurboFieldfare/Runtime/Vision/Preprocessing/Gemma4ImagePreprocessor.swift
@@ -0,0 +1,263 @@
+import CoreGraphics
+import Foundation
+import ImageIO
+import Metal
+
+public final class Gemma4ImagePreprocessor {
+ private static let unitBF16 = (0...255).map {
+ Quantization.bf16Bits(Float($0) / 255)
+ }
+
+ private let device: MTLDevice
+ private let config: VisionConfig
+ private let metadataReader: ImageMetadataReader
+ /// Set when the reduction runs on the GPU. Building it needs a full
+ /// `MetalContext`, so callers that only have a device keep the CPU filter.
+ private let gpuResize: VisionResize?
+
+ public init(
+ device: MTLDevice,
+ config: VisionConfig = VisionConfig(),
+ limits: VisionImageLimits = VisionImageLimits(),
+ gpuResize: VisionResize? = nil
+ ) {
+ self.device = device
+ self.config = config
+ self.metadataReader = ImageMetadataReader(limits: limits)
+ self.gpuResize = gpuResize
+ }
+
+ public func preprocess(fileURL: URL) throws -> VisionPixelBuffer {
+ try preprocess(VisionImageSource(fileURL: fileURL))
+ }
+
+ public func preprocess(_ image: VisionImageSource) throws -> VisionPixelBuffer {
+ try preprocess(plan(image))
+ }
+
+ public func plan(fileURL: URL) throws -> VisionImagePlan {
+ try plan(VisionImageSource(fileURL: fileURL))
+ }
+
+ /// The geometry a request's admission needs, from headers alone. The soft
+ /// token count follows from oriented dimensions, so admission has no
+ /// reason to pay the JPEG scan-termination walk a full plan performs —
+ /// the encode that follows re-plans with full verification anyway.
+ public func admissionGeometry(fileURL: URL) throws -> Gemma4ImageGeometry {
+ let image = try VisionImageSource(fileURL: fileURL)
+ let opened = try image.open(
+ maximumEncodedBytes: metadataReader.limits.maximumEncodedBytes)
+ let metadata = try metadataReader.read(
+ opened: opened, verifyStreamCompleteness: false)
+ return try Gemma4ImageGeometry(
+ sourceWidth: metadata.orientedWidth,
+ sourceHeight: metadata.orientedHeight,
+ config: config)
+ }
+
+ public func plan(_ image: VisionImageSource) throws -> VisionImagePlan {
+ let started = ContinuousClock.now
+ let opened = try image.open(
+ maximumEncodedBytes: metadataReader.limits.maximumEncodedBytes)
+ let metadata = try metadataReader.read(opened: opened)
+ let geometry = try Gemma4ImageGeometry(
+ sourceWidth: metadata.orientedWidth,
+ sourceHeight: metadata.orientedHeight,
+ config: config)
+ return VisionImagePlan(
+ metadata: metadata, geometry: geometry, opened: opened, started: started)
+ }
+
+ /// The size ImageIO is asked to decode at.
+ ///
+ /// **Known gap, deliberately left open.** For a source larger than the
+ /// target, ImageIO's own scaler does the reduction and `TorchBicubicResize`
+ /// — the stage that exists to match the reference implementation — runs on
+ /// pre-scaled pixels. A 4032x3024 photo bound for 912x672 is reduced
+ /// 4032->912 by ImageIO and only 684->672 by bicubic, so downscales are not
+ /// bit-comparable with the pinned Transformers/PIL reference. Every corpus
+ /// fixture is an upscale, so this is unmeasured as well as unfixed.
+ ///
+ /// Handing the whole reduction to bicubic restores parity and was tried:
+ /// it costs 4.5 s for a 1600x1200 source, 18.6 s at 12 MP and 61 s with
+ /// 240 MB of footprint at 48 MP, because the resampler is CPU and runs at
+ /// about 1.5 us per source pixel. That is far worse than the gap it closes.
+ /// Closing it properly needs a fast resampler (vImage or GPU) first.
+ static func decodeMaxPixelSize(
+ metadata: VisionImageMetadata,
+ geometry: Gemma4ImageGeometry
+ ) -> Int {
+ // The whole reduction belongs to our filter, which is the pinned
+ // reference's. Decoding at the target instead handed it to ImageIO's
+ // undocumented scaler: on a UI screenshot that changed the model's
+ // transcription, dropping whole lines of text. It was reverted once for
+ // costing seconds — a debug-build measurement. Release, on the GPU, it
+ // is a few milliseconds.
+ max(metadata.orientedWidth, metadata.orientedHeight)
+ }
+
+ public func preprocess(_ plan: VisionImagePlan) throws -> VisionPixelBuffer {
+ let source = plan.opened.source
+ let metadata = plan.metadata
+ let geometry = plan.geometry
+ let thumbnailOptions: [CFString: Any] = [
+ kCGImageSourceCreateThumbnailFromImageAlways: true,
+ kCGImageSourceCreateThumbnailWithTransform: true,
+ kCGImageSourceThumbnailMaxPixelSize:
+ Self.decodeMaxPixelSize(metadata: metadata, geometry: geometry),
+ kCGImageSourceShouldCacheImmediately: true,
+ kCGImageSourceShouldAllowFloat: false,
+ ]
+ guard let decoded = CGImageSourceCreateThumbnailAtIndex(
+ source, 0, thumbnailOptions as CFDictionary) else {
+ throw VisionImageError.decodeFailed
+ }
+
+ let sourceRowBytes = try checkedMultiply(decoded.width, 4)
+ let sourceBytes = try checkedMultiply(sourceRowBytes, decoded.height)
+ // Decoded straight into GPU-visible memory when the GPU filter will
+ // read it, which removes one copy but not the fundamental cost: ImageIO
+ // materialises a full-resolution CGImage and `draw` needs both it and
+ // this surface live at once. For a 48 MP source that is two ~192 MB
+ // surfaces, about 400 MB, on a machine already holding the model — the
+ // reason the decoded-byte ceiling is what it is, and why both are
+ // counted in `allocatedBytes` below rather than only ours.
+ let sourceBuffer = gpuResize == nil
+ ? nil
+ : device.makeBuffer(length: sourceBytes, options: .storageModeShared)
+ let sourceRGBA = sourceBuffer?.contents()
+ ?? UnsafeMutableRawPointer.allocate(byteCount: sourceBytes, alignment: 64)
+ sourceRGBA.initializeMemory(as: UInt8.self, repeating: 255, count: sourceBytes)
+ defer { if sourceBuffer == nil { sourceRGBA.deallocate() } }
+ guard let colorSpace = CGColorSpace(name: CGColorSpace.sRGB),
+ let sourceDrawing = CGContext(
+ data: sourceRGBA,
+ width: decoded.width,
+ height: decoded.height,
+ bitsPerComponent: 8,
+ bytesPerRow: sourceRowBytes,
+ space: colorSpace,
+ bitmapInfo: CGBitmapInfo.byteOrder32Big.rawValue
+ | CGImageAlphaInfo.premultipliedLast.rawValue) else {
+ throw VisionImageError.allocationFailed
+ }
+ sourceDrawing.setFillColor(CGColor(gray: 1, alpha: 1))
+ sourceDrawing.fill(CGRect(x: 0, y: 0, width: decoded.width, height: decoded.height))
+ sourceDrawing.draw(
+ decoded, in: CGRect(x: 0, y: 0, width: decoded.width, height: decoded.height))
+ withExtendedLifetime(sourceDrawing) {}
+
+ let rowBytes = try checkedMultiply(geometry.processedWidth, 4)
+ let rgbaBytes = try checkedMultiply(rowBytes, geometry.processedHeight)
+ let rgba = UnsafeMutableRawPointer.allocate(byteCount: rgbaBytes, alignment: 64)
+ defer { rgba.deallocate() }
+ // Same filter either way — the GPU path applies the weights this one
+ // builds, and the parity tests assert byte equality — so this chooses
+ // only where the arithmetic runs.
+ // Both surfaces plus whatever the resize holds. Reporting only our own
+ // allocation understated the peak by about half, and a test uses this
+ // number as a footprint guard.
+ let decodedSurfaceBytes = sourceBytes
+ var resizeScratchBytes = 0
+ if let gpuResize, let sourceBuffer {
+ resizeScratchBytes = gpuResize.scratchBytes(
+ sourceWidth: decoded.width, sourceHeight: decoded.height,
+ destinationWidth: geometry.processedWidth,
+ destinationHeight: geometry.processedHeight)
+ try gpuResize.resize(
+ sourceBuffer: sourceBuffer,
+ sourceWidth: decoded.width,
+ sourceHeight: decoded.height,
+ sourceRowBytes: sourceRowBytes,
+ destination: rgba,
+ destinationWidth: geometry.processedWidth,
+ destinationHeight: geometry.processedHeight,
+ destinationRowBytes: rowBytes)
+ } else {
+ resizeScratchBytes = TorchBicubicResize.resize(
+ source: sourceRGBA.assumingMemoryBound(to: UInt8.self),
+ sourceWidth: decoded.width,
+ sourceHeight: decoded.height,
+ sourceRowBytes: sourceRowBytes,
+ destination: rgba.assumingMemoryBound(to: UInt8.self),
+ destinationWidth: geometry.processedWidth,
+ destinationHeight: geometry.processedHeight,
+ destinationRowBytes: rowBytes)
+ }
+
+ let patchElements = try checkedMultiply(geometry.patchCount, config.patchDimension)
+ let patchBytes = try checkedMultiply(patchElements, MemoryLayout<UInt16>.stride)
+ let positionElements = try checkedMultiply(geometry.patchCount, 2)
+ let positionBytes = try checkedMultiply(
+ positionElements, MemoryLayout<Int32>.stride)
+ guard let patches = device.makeBuffer(length: patchBytes, options: .storageModeShared),
+ let positions = device.makeBuffer(
+ length: positionBytes, options: .storageModeShared) else {
+ throw VisionImageError.allocationFailed
+ }
+ patchify(
+ rgba: rgba.assumingMemoryBound(to: UInt8.self),
+ rowBytes: rowBytes,
+ geometry: geometry,
+ patches: patches,
+ positions: positions)
+ return VisionPixelBuffer(
+ patchesBF16: patches,
+ positionsInt32x2: positions,
+ metadata: metadata,
+ geometry: geometry,
+ wallNanoseconds: nanoseconds(plan.started.duration(to: .now)),
+ // Both full-resolution surfaces: ImageIO's decoded CGImage and
+ // ours, which `draw` holds simultaneously.
+ allocatedBytes: decodedSurfaceBytes + sourceBytes + rgbaBytes
+ + resizeScratchBytes
+ + patchBytes + positionBytes)
+ }
+
+ private func patchify(
+ rgba: UnsafePointer<UInt8>,
+ rowBytes: Int,
+ geometry: Gemma4ImageGeometry,
+ patches: MTLBuffer,
+ positions: MTLBuffer
+ ) {
+ let patchPointer = patches.contents().bindMemory(
+ to: UInt16.self, capacity: geometry.patchCount * config.patchDimension)
+ let positionPointer = positions.contents().bindMemory(
+ to: Int32.self, capacity: geometry.patchCount * 2)
+ let size = config.patchSize
+ for patchY in 0..<geometry.patchGridHeight {
+ for patchX in 0..<geometry.patchGridWidth {
+ let row = patchY * geometry.patchGridWidth + patchX
+ positionPointer[row * 2] = Int32(patchX)
+ positionPointer[row * 2 + 1] = Int32(patchY)
+ var output = row * config.patchDimension
+ for pixelY in 0..<size {
+ let inputRow = (patchY * size + pixelY) * rowBytes
+ for pixelX in 0..<size {
+ let input = inputRow + (patchX * size + pixelX) * 4
+ patchPointer[output] = Self.unitBF16[Int(rgba[input])]
+ patchPointer[output + 1] = Self.unitBF16[Int(rgba[input + 1])]
+ patchPointer[output + 2] = Self.unitBF16[Int(rgba[input + 2])]
+ output += 3
+ }
+ }
+ }
+ }
+ }
+
+ private func checkedMultiply(_ lhs: Int, _ rhs: Int) throws -> Int {
+ let (value, overflow) = lhs.multipliedReportingOverflow(by: rhs)
+ guard !overflow else {
+ throw VisionImageError.invalidMetadata("buffer size overflow")
+ }
+ return value
+ }
+
+ private func nanoseconds(_ duration: Duration) -> UInt64 {
+ let components = duration.components
+ let seconds = UInt64(max(0, components.seconds))
+ let fractional = UInt64(max(0, components.attoseconds / 1_000_000_000))
+ return seconds * 1_000_000_000 + fractional
+ }
+}
diff --git a/Sources/TurboFieldfare/Runtime/Vision/Preprocessing/ImageMetadataReader.swift b/Sources/TurboFieldfare/Runtime/Vision/Preprocessing/ImageMetadataReader.swift
new file mode 100644
index 00000000..3736ec24
--- /dev/null
+++ b/Sources/TurboFieldfare/Runtime/Vision/Preprocessing/ImageMetadataReader.swift
@@ -0,0 +1,167 @@
+import Foundation
+import ImageIO
+import UniformTypeIdentifiers
+
+public struct VisionImageLimits: Sendable, Equatable {
+ public let maximumEncodedBytes: Int
+ public let maximumSourcePixels: Int
+ public let maximumSourceDimension: Int
+ /// Decoders the pack is validated against. ImageIO sniffs the real bytes, so
+ /// without this a request labelled `image/png` can reach the camera-RAW or
+ /// EXR decoder — a far larger surface than the formats actually supported.
+ public let allowedTypeIdentifiers: Set<String>
+ /// Decoded bytes, not pixels. The pixel cap alone lets a 16-bit image expand
+ /// about four times further than an 8-bit one at the same pixel count.
+ /// Ceiling on one decoded surface. The 50-million-pixel source contract
+ /// needs 200,000,000 bytes for an 8-bit RGBA surface, including an 8,000 by
+ /// 6,000 camera image. ImageIO's decoded image and our drawing surface can
+ /// overlap, so the M2 acceptance gate measures the resulting transient.
+ public let maximumDecodedBytes: Int
+
+ public init(
+ maximumEncodedBytes: Int = 64 * 1_024 * 1_024,
+ maximumSourcePixels: Int = 50_000_000,
+ maximumSourceDimension: Int = 32_768,
+ allowedTypeIdentifiers: Set<String> = [
+ "public.jpeg", "public.png", "public.heic", "public.heif",
+ "public.tiff", "com.compuserve.gif", "public.heics",
+ ],
+ maximumDecodedBytes: Int = 200_000_000
+ ) {
+ precondition(
+ maximumEncodedBytes > 0 && maximumSourcePixels > 0
+ && maximumSourceDimension > 0)
+ self.maximumEncodedBytes = maximumEncodedBytes
+ self.maximumSourcePixels = maximumSourcePixels
+ self.maximumSourceDimension = maximumSourceDimension
+ self.allowedTypeIdentifiers = allowedTypeIdentifiers
+ self.maximumDecodedBytes = maximumDecodedBytes
+ }
+
+ /// `allowedTypeIdentifiers` as `UTType`s, for the picker and pasteboard
+ /// gates that admit an attachment in the first place.
+ ///
+ /// Those gates used to admit anything conforming to `public.image`, which is
+ /// a far wider set than this one: a camera RAW, EXR or WebP was copied at
+ /// full size, decoded in-process for its thumbnail beside a loaded model,
+ /// and only then refused by `ImageMetadataReader`. Sorted so the picker's
+ /// type list is stable between launches.
+ public var allowedContentTypes: [UTType] {
+ allowedTypeIdentifiers
+ .compactMap(UTType.init(_:))
+ .sorted { $0.identifier < $1.identifier }
+ }
+}
+
+public struct VisionImageMetadata: Sendable, Equatable {
+ public let encodedBytes: Int
+ public let encodedWidth: Int
+ public let encodedHeight: Int
+ public let orientedWidth: Int
+ public let orientedHeight: Int
+ public let orientation: Int
+ public let bitsPerComponent: Int?
+ public let colorModel: String?
+ public let typeIdentifier: String?
+}
+
+public struct ImageMetadataReader: Sendable {
+ public let limits: VisionImageLimits
+
+ public init(limits: VisionImageLimits = VisionImageLimits()) {
+ self.limits = limits
+ }
+
+ /// `verifyStreamCompleteness` walks a JPEG's whole entropy-coded scan to
+ /// prove the file is not truncated — a read of every encoded byte. A
+ /// caller that only needs dimensions (admission token counting) can skip
+ /// it: a truncated file still fails at encode time, where the walk runs.
+ package func read(
+ opened: OpenedVisionImage,
+ verifyStreamCompleteness: Bool = true
+ ) throws -> VisionImageMetadata {
+ let source = opened.source
+ let frameCount = CGImageSourceGetCount(source)
+ guard frameCount == 1 else {
+ throw VisionImageError.unsupportedFrameCount(frameCount)
+ }
+ guard let typeIdentifier = CGImageSourceGetType(source) as String?,
+ let sourceType = UTType(typeIdentifier),
+ sourceType.conforms(to: .image) else {
+ throw VisionImageError.invalidMetadata("unsupported image type")
+ }
+ // Checked against the sniffed type, not the caller's label: a data URL
+ // announcing image/png can carry anything ImageIO recognises.
+ guard limits.allowedTypeIdentifiers.contains(typeIdentifier) else {
+ throw VisionImageError.invalidMetadata(
+ "unsupported image type \(typeIdentifier)")
+ }
+ // A truncated JPEG decodes to gray filler rather than failing, so the
+ // stream has to be checked structurally; see `hasCompleteJPEGStream`.
+ if verifyStreamCompleteness, sourceType.conforms(to: .jpeg),
+ !opened.hasCompleteJPEGStream() {
+ throw VisionImageError.invalidMetadata(
+ "JPEG scan is not terminated: the file is truncated")
+ }
+ // PNG fails the same way and used to pass: the undecoded remainder
+ // reads as black and the answer describes a black square.
+ if verifyStreamCompleteness, sourceType.conforms(to: .png),
+ !opened.hasCompletePNGStream() {
+ throw VisionImageError.invalidMetadata(
+ "PNG has no IEND chunk: the file is truncated")
+ }
+ guard let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) else {
+ throw VisionImageError.invalidMetadata("missing frame properties")
+ }
+ let dictionary = properties as NSDictionary
+ guard let width = (dictionary[kCGImagePropertyPixelWidth] as? NSNumber)?.intValue,
+ let height = (dictionary[kCGImagePropertyPixelHeight] as? NSNumber)?.intValue,
+ width > 0, height > 0 else {
+ throw VisionImageError.invalidMetadata("missing positive pixel dimensions")
+ }
+ guard width <= limits.maximumSourceDimension,
+ height <= limits.maximumSourceDimension else {
+ throw VisionImageError.sideTooLarge(
+ width: width, height: height, sideLimit: limits.maximumSourceDimension)
+ }
+ let (pixels, overflow) = width.multipliedReportingOverflow(by: height)
+ guard !overflow, pixels <= limits.maximumSourcePixels else {
+ throw VisionImageError.dimensionsTooLarge(
+ width: width, height: height, pixelLimit: limits.maximumSourcePixels)
+ }
+ let depth = (dictionary[kCGImagePropertyDepth] as? NSNumber)?.intValue ?? 8
+ // Four channels is the decode target; source depth drives how much
+ // ImageIO materialises before the thumbnail conversion.
+ let (depthBytes, depthOverflow) = pixels.multipliedReportingOverflow(
+ by: max(1, depth / 8) * 4)
+ // One ceiling, because every format is now decoded at native size:
+ // the reduction belongs to our own filter, so ImageIO no longer gets to
+ // subsample JPEG or HEIF. The split that gave those formats 320 MB
+ // rested on a shortcut this path deliberately gave up, and the cost is
+ // two full surfaces live at once — the decoded CGImage and the one we
+ // draw into — so the bound has to cover both.
+ guard !depthOverflow, depthBytes <= limits.maximumDecodedBytes else {
+ throw VisionImageError.decodedBytesTooLarge(
+ width: width, height: height, byteLimit: limits.maximumDecodedBytes)
+ }
+ let orientation = (dictionary[kCGImagePropertyOrientation] as? NSNumber)?.intValue ?? 1
+ guard (1...8).contains(orientation) else {
+ throw VisionImageError.invalidMetadata("unsupported EXIF orientation \(orientation)")
+ }
+ let bitsPerComponent = (dictionary[kCGImagePropertyDepth] as? NSNumber)?.intValue
+ let colorModel = dictionary[kCGImagePropertyColorModel] as? String
+ // The bounded ImageIO thumbnail decode converts source depth and color space
+ // into the preprocessor's RGBA8 sRGB context.
+ let swapsAxes = (5...8).contains(orientation)
+ return VisionImageMetadata(
+ encodedBytes: opened.encodedBytes,
+ encodedWidth: width,
+ encodedHeight: height,
+ orientedWidth: swapsAxes ? height : width,
+ orientedHeight: swapsAxes ? width : height,
+ orientation: orientation,
+ bitsPerComponent: bitsPerComponent,
+ colorModel: colorModel,
+ typeIdentifier: typeIdentifier)
+ }
+}
diff --git a/Sources/TurboFieldfare/Runtime/Vision/Preprocessing/TorchBicubicResize.swift b/Sources/TurboFieldfare/Runtime/Vision/Preprocessing/TorchBicubicResize.swift
new file mode 100644
index 00000000..55680af4
--- /dev/null
+++ b/Sources/TurboFieldfare/Runtime/Vision/Preprocessing/TorchBicubicResize.swift
@@ -0,0 +1,223 @@
+import Foundation
+
+package enum TorchBicubicResize {
+ /// The weights for one axis, flattened for a GPU that cannot chase arrays
+ /// of arrays: `starts[i]` is where output `i` begins reading, and its taps
+ /// are `weights[i * tapStride ..< (i + 1) * tapStride]`, zero-padded.
+ ///
+ /// Exposed so the Metal path applies the same numbers rather than its own —
+ /// the weights depend only on the axis ratio, so building them stays on the
+ /// CPU where the arithmetic is already proven.
+ package struct WeightTable {
+ package let starts: [Int32]
+ package let weights: [Int16]
+ package let tapStride: Int
+ package let precision: Int
+ }
+
+ package static func weightTable(input: Int, output: Int) -> WeightTable {
+ let axis = axis(input: input, output: output)
+ let stride = axis.samples.map(\.weights.count).max() ?? 0
+ var starts: [Int32] = []
+ var weights: [Int16] = []
+ starts.reserveCapacity(axis.samples.count)
+ weights.reserveCapacity(axis.samples.count * max(stride, 1))
+ for sample in axis.samples {
+ starts.append(Int32(sample.start))
+ weights.append(contentsOf: sample.weights)
+ weights.append(contentsOf: repeatElement(0, count: stride - sample.weights.count))
+ }
+ return WeightTable(starts: starts, weights: weights,
+ tapStride: max(stride, 1), precision: axis.precision)
+ }
+
+ private struct Sample {
+ let start: Int
+ let weights: [Int16]
+ }
+
+ private struct Axis {
+ let samples: [Sample]
+ let precision: Int
+ }
+
+ package static func resize(
+ source: UnsafePointer<UInt8>,
+ sourceWidth: Int,
+ sourceHeight: Int,
+ sourceRowBytes: Int,
+ destination: UnsafeMutablePointer<UInt8>,
+ destinationWidth: Int,
+ destinationHeight: Int,
+ destinationRowBytes: Int
+ ) -> Int {
+ if sourceWidth == destinationWidth && sourceHeight == destinationHeight {
+ for row in 0..<sourceHeight {
+ memcpy(
+ destination.advanced(by: row * destinationRowBytes),
+ source.advanced(by: row * sourceRowBytes),
+ sourceWidth * 4)
+ }
+ return 0
+ }
+
+ if sourceWidth == destinationWidth {
+ let vertical = axis(input: sourceHeight, output: destinationHeight)
+ resizeVertical(
+ source: source,
+ sourceWidth: sourceWidth,
+ sourceRowBytes: sourceRowBytes,
+ destination: destination,
+ destinationHeight: destinationHeight,
+ destinationRowBytes: destinationRowBytes,
+ axis: vertical)
+ return 0
+ }
+ let horizontal = axis(input: sourceWidth, output: destinationWidth)
+ if sourceHeight == destinationHeight {
+ resizeHorizontal(
+ source: source,
+ sourceHeight: sourceHeight,
+ sourceRowBytes: sourceRowBytes,
+ destination: destination,
+ destinationWidth: destinationWidth,
+ destinationRowBytes: destinationRowBytes,
+ axis: horizontal)
+ return 0
+ }
+
+ let temporaryRowBytes = destinationWidth * 4
+ let temporaryBytes = temporaryRowBytes * sourceHeight
+ let temporary = UnsafeMutablePointer<UInt8>.allocate(capacity: temporaryBytes)
+ defer { temporary.deallocate() }
+ resizeHorizontal(
+ source: source,
+ sourceHeight: sourceHeight,
+ sourceRowBytes: sourceRowBytes,
+ destination: temporary,
+ destinationWidth: destinationWidth,
+ destinationRowBytes: temporaryRowBytes,
+ axis: horizontal)
+ let vertical = axis(input: sourceHeight, output: destinationHeight)
+ resizeVertical(
+ source: UnsafePointer(temporary),
+ sourceWidth: destinationWidth,
+ sourceRowBytes: temporaryRowBytes,
+ destination: destination,
+ destinationHeight: destinationHeight,
+ destinationRowBytes: destinationRowBytes,
+ axis: vertical)
+ return temporaryBytes
+ }
+
+ private static func axis(input: Int, output: Int) -> Axis {
+ let scale = Double(input) / Double(output)
+ let support = scale >= 1 ? 2 * scale : 2
+ let inverseScale = scale >= 1 ? 1 / scale : 1
+ let maximumCount = Int(ceil(support)) * 2 + 1
+ var floating: [(start: Int, weights: [Double])] = []
+ floating.reserveCapacity(output)
+ var maximumWeight = 0.0
+ for outputIndex in 0..<output {
+ let center = scale * (Double(outputIndex) + 0.5)
+ let start = max(Int(center - support + 0.5), 0)
+ let count = min(
+ max(min(Int(center + support + 0.5), input) - start, 0),
+ maximumCount)
+ var weights: [Double] = []
+ weights.reserveCapacity(count)
+ var total = 0.0
+ for offset in 0..<count {
+ let distance = (Double(offset + start) - center + 0.5) * inverseScale
+ let weight = cubic(distance)
+ weights.append(weight)
+ total += weight
+ }
+ if total != 0 {
+ for index in weights.indices {
+ weights[index] /= total
+ maximumWeight = max(maximumWeight, weights[index])
+ }
+ }
+ floating.append((start, weights))
+ }
+
+ var precision = 0
+ while precision < 22 {
+ let next = Int(0.5 + maximumWeight * Double(1 << (precision + 1)))
+ if next >= 1 << 15 { break }
+ precision += 1
+ }
+ let scaleFactor = Double(1 << precision)
+ let samples = floating.map { item in
+ Sample(start: item.start, weights: item.weights.map { value in
+ let scaled = value * scaleFactor
+ return Int16(scaled < 0 ? Int(scaled - 0.5) : Int(scaled + 0.5))
+ })
+ }
+ return Axis(samples: samples, precision: precision)
+ }
+
+ private static func cubic(_ value: Double) -> Double {
+ let x = abs(value)
+ let a = -0.5
+ if x < 1 {
+ return ((a + 2) * x - (a + 3)) * x * x + 1
+ }
+ if x < 2 {
+ return ((a * x - 5 * a) * x + 8 * a) * x - 4 * a
+ }
+ return 0
+ }
+
+ private static func resizeHorizontal(
+ source: UnsafePointer<UInt8>,
+ sourceHeight: Int,
+ sourceRowBytes: Int,
+ destination: UnsafeMutablePointer<UInt8>,
+ destinationWidth: Int,
+ destinationRowBytes: Int,
+ axis: Axis
+ ) {
+ let rounding = 1 << (axis.precision - 1)
+ for row in 0..<sourceHeight {
+ let inputRow = source.advanced(by: row * sourceRowBytes)
+ let outputRow = destination.advanced(by: row * destinationRowBytes)
+ for x in 0..<destinationWidth {
+ let sample = axis.samples[x]
+ for channel in 0..<4 {
+ var value = rounding
+ for index in sample.weights.indices {
+ value += Int(inputRow[(sample.start + index) * 4 + channel])
+ * Int(sample.weights[index])
+ }
+ outputRow[x * 4 + channel] = UInt8(clamping: value >> axis.precision)
+ }
+ }
+ }
+ }
+
+ private static func resizeVertical(
+ source: UnsafePointer<UInt8>,
+ sourceWidth: Int,
+ sourceRowBytes: Int,
+ destination: UnsafeMutablePointer<UInt8>,
+ destinationHeight: Int,
+ destinationRowBytes: Int,
+ axis: Axis
+ ) {
+ let rounding = 1 << (axis.precision - 1)
+ for y in 0..<destinationHeight {
+ let sample = axis.samples[y]
+ let outputRow = destination.advanced(by: y * destinationRowBytes)
+ for x in 0..<(sourceWidth * 4) {
+ var value = rounding
+ for index in sample.weights.indices {
+ value += Int(source[(sample.start + index) * sourceRowBytes + x])
+ * Int(sample.weights[index])
+ }
+ outputRow[x] = UInt8(clamping: value >> axis.precision)
+ }
+ }
+ }
+}
diff --git a/Sources/TurboFieldfare/Runtime/Vision/Preprocessing/VisionImageSource.swift b/Sources/TurboFieldfare/Runtime/Vision/Preprocessing/VisionImageSource.swift
new file mode 100644
index 00000000..9a4897d7
--- /dev/null
+++ b/Sources/TurboFieldfare/Runtime/Vision/Preprocessing/VisionImageSource.swift
@@ -0,0 +1,268 @@
+import CoreGraphics
+import Darwin
+import Foundation
+import ImageIO
+
+public enum VisionImageError: Error, CustomStringConvertible {
+ case invalidSource(String)
+ case invalidMetadata(String)
+ case unsupportedFrameCount(Int)
+ case sourceTooLarge(bytes: Int, limit: Int)
+ case dimensionsTooLarge(width: Int, height: Int, pixelLimit: Int)
+ case sideTooLarge(width: Int, height: Int, sideLimit: Int)
+ case decodedBytesTooLarge(width: Int, height: Int, byteLimit: Int)
+ case decodeFailed
+ case allocationFailed
+
+ public var description: String {
+ switch self {
+ case .invalidSource(let detail): "invalid image source: \(detail)"
+ case .invalidMetadata(let detail): "invalid image metadata: \(detail)"
+ case .unsupportedFrameCount(let count): "image must contain one frame, found \(count)"
+ case .sourceTooLarge(let bytes, let limit):
+ "encoded image has \(bytes) bytes, limit is \(limit)"
+ case .dimensionsTooLarge(let width, let height, let limit):
+ "image dimensions \(width)x\(height) exceed the \(limit)-pixel limit"
+ case .sideTooLarge(let width, let height, let limit):
+ "image dimensions \(width)x\(height) exceed the \(limit)-pixel per-side limit"
+ case .decodedBytesTooLarge(let width, let height, let limit):
+ "image \(width)x\(height) would decode to more than \(limit) bytes"
+ case .decodeFailed: "ImageIO could not decode the image"
+ case .allocationFailed: "image preprocessing buffer allocation failed"
+ }
+ }
+}
+
+public struct VisionImageSource: Sendable {
+ public let fileURL: URL
+
+ public init(fileURL: URL) throws {
+ guard fileURL.isFileURL else {
+ throw VisionImageError.invalidSource("a file URL is required")
+ }
+ self.fileURL = fileURL.standardizedFileURL
+ }
+
+ package func open(maximumEncodedBytes: Int) throws -> OpenedVisionImage {
+ let descriptor = fileURL.path.withCString {
+ // O_NONBLOCK or a FIFO blocks here forever: the regular-file check
+ // below runs only once open returns. pread on a regular file ignores
+ // it, so nothing downstream changes. Matches every other open here.
+ Darwin.open($0, O_RDONLY | O_NONBLOCK | O_CLOEXEC | O_NOFOLLOW)
+ }
+ guard descriptor >= 0 else {
+ throw VisionImageError.invalidSource(
+ "open failed for \(fileURL.lastPathComponent): \(String(cString: strerror(errno)))")
+ }
+ var status = stat()
+ guard fstat(descriptor, &status) == 0 else {
+ let savedErrno = errno
+ Darwin.close(descriptor)
+ throw VisionImageError.invalidSource(
+ "fstat failed: \(String(cString: strerror(savedErrno)))")
+ }
+ guard (status.st_mode & S_IFMT) == S_IFREG, status.st_size >= 0,
+ let encodedBytes = Int(exactly: status.st_size) else {
+ Darwin.close(descriptor)
+ throw VisionImageError.invalidSource("a regular file is required")
+ }
+ guard encodedBytes <= maximumEncodedBytes else {
+ Darwin.close(descriptor)
+ throw VisionImageError.sourceTooLarge(
+ bytes: encodedBytes, limit: maximumEncodedBytes)
+ }
+
+ let fileProvider = VisionFileProvider(
+ descriptor: descriptor, encodedBytes: encodedBytes)
+ let context = Unmanaged.passRetained(fileProvider)
+ var callbacks = CGDataProviderDirectCallbacks(
+ version: 0,
+ getBytePointer: nil,
+ releaseBytePointer: nil,
+ getBytesAtPosition: { opaque, buffer, position, count in
+ guard let opaque else { return 0 }
+ return Unmanaged<VisionFileProvider>.fromOpaque(opaque)
+ .takeUnretainedValue()
+ .read(into: buffer, position: position, count: count)
+ },
+ releaseInfo: { opaque in
+ guard let opaque else { return }
+ Unmanaged<VisionFileProvider>.fromOpaque(opaque).release()
+ })
+ guard let provider = CGDataProvider(
+ directInfo: context.toOpaque(), size: off_t(encodedBytes), callbacks: &callbacks) else {
+ context.release()
+ throw VisionImageError.invalidSource("could not create image data provider")
+ }
+ let options = [kCGImageSourceShouldCache: false] as CFDictionary
+ guard let source = CGImageSourceCreateWithDataProvider(provider, options) else {
+ throw VisionImageError.invalidSource("ImageIO rejected \(fileURL.lastPathComponent)")
+ }
+ return OpenedVisionImage(
+ source: source,
+ provider: provider,
+ fileProvider: fileProvider,
+ encodedBytes: encodedBytes)
+ }
+}
+
+package struct OpenedVisionImage {
+ let source: CGImageSource
+ private let provider: CGDataProvider
+ private let fileProvider: VisionFileProvider
+ let encodedBytes: Int
+
+ fileprivate init(
+ source: CGImageSource,
+ provider: CGDataProvider,
+ fileProvider: VisionFileProvider,
+ encodedBytes: Int
+ ) {
+ self.source = source
+ self.provider = provider
+ self.fileProvider = fileProvider
+ self.encodedBytes = encodedBytes
+ }
+
+
+ /// Whether the JPEG's entropy-coded scan is terminated by an end-of-image
+ /// marker, which is the only question that separates a truncated file from
+ /// a complete one.
+ ///
+ /// Neither simpler test works. ImageIO reports `statusComplete` for a file
+ /// truncated to a fifth of its length — the incomplete statuses only apply
+ /// to incremental sources — and it then decodes the partial scan with gray
+ /// filler, so the model describes an image the file does not contain.
+ /// Scanning the tail for `FF D9` fails in both directions: a truncated photo
+ /// still carries the EOI of its EXIF thumbnail near the front, and a Motion
+ /// Photo's appended MP4 pushes the real EOI outside any fixed window.
+ ///
+ /// Markers are walked from the front to find the start of scan; anything
+ /// before it (thumbnails, ICC, XMP) is skipped by construction. A single
+ /// `FF D9` anywhere after that point means the scan was terminated, which
+ /// tolerates trailing video and padding.
+ func hasCompleteJPEGStream() -> Bool {
+ guard let scanStart = startOfScanOffset() else { return false }
+ var position = scanStart
+ var carry: UInt8 = 0
+ var buffer = [UInt8](repeating: 0, count: Self.scanChunkBytes)
+ while position < encodedBytes {
+ let count = min(Self.scanChunkBytes, encodedBytes - position)
+ let read = buffer.withUnsafeMutableBytes {
+ fileProvider.read(into: $0.baseAddress!,
+ position: off_t(position), count: count)
+ }
+ guard read == count else { return false }
+ if carry == 0xFF, buffer[0] == 0xD9 { return true }
+ var index = 0
+ while index + 1 < count {
+ if buffer[index] == 0xFF, buffer[index + 1] == 0xD9 { return true }
+ index += 1
+ }
+ carry = buffer[count - 1]
+ position += count
+ }
+ return false
+ }
+
+ /// Whether the PNG ends with its `IEND` chunk, which is the same question
+ /// `hasCompleteJPEGStream` asks of a JPEG.
+ ///
+ /// A PNG cut short decodes exactly as badly and just as silently: ImageIO
+ /// returns the rows it has and leaves the rest black, so the model
+ /// confidently describes a black square. `IEND` is a fixed 12-byte trailer
+ /// with a constant CRC, so the check is a single tail read rather than a
+ /// walk, and appended data after `IEND` is not something PNG permits.
+ func hasCompletePNGStream() -> Bool {
+ let trailer = 12
+ guard encodedBytes >= 8 + trailer else { return false }
+ var tail = [UInt8](repeating: 0, count: trailer)
+ let read = tail.withUnsafeMutableBytes {
+ fileProvider.read(into: $0.baseAddress!,
+ position: off_t(encodedBytes - trailer),
+ count: trailer)
+ }
+ guard read == trailer else { return false }
+ return tail == [0x00, 0x00, 0x00, 0x00,
+ 0x49, 0x45, 0x4E, 0x44,
+ 0xAE, 0x42, 0x60, 0x82]
+ }
+
+ /// Offset just past the SOS segment header, or nil if the file ends before
+ /// one appears.
+ private func startOfScanOffset() -> Int? {
+ var position = 2 // past SOI
+ var header = [UInt8](repeating: 0, count: 4)
+ while position + 4 <= min(encodedBytes, Self.markerScanLimitBytes) {
+ let read = header.withUnsafeMutableBytes {
+ fileProvider.read(into: $0.baseAddress!,
+ position: off_t(position), count: 4)
+ }
+ guard read == 4, header[0] == 0xFF else { return nil }
+ // Fill bytes: any number of 0xFF may precede a marker (ITU T.81
+ // B.1.1.2), and scanners and older camera firmware emit them.
+ // Reading one as the marker made its length the real marker byte
+ // and half the real length — a jump to nothing, and an intact photo
+ // reported as truncated.
+ if header[1] == 0xFF {
+ position += 1
+ continue
+ }
+ let marker = header[1]
+ // Standalone markers carry no length. SOI and EOI belong here too:
+ // treating them as length-prefixed walked off into the entropy data.
+ if marker == 0x01 || marker == 0xD8 || marker == 0xD9
+ || (0xD0...0xD7).contains(marker) {
+ position += 2
+ continue
+ }
+ let length = Int(header[2]) << 8 | Int(header[3])
+ guard length >= 2 else { return nil }
+ if marker == 0xDA { return position + 2 + length }
+ position += 2 + length
+ }
+ return nil
+ }
+
+ /// Read granularity for the scan search.
+ static let scanChunkBytes = 256 * 1_024
+ /// How far into the file the marker walk may go before giving up. Headers
+ /// live at the front; a file whose SOS is beyond this is not one we serve.
+ static let markerScanLimitBytes = 8 * 1_024 * 1_024
+}
+
+private final class VisionFileProvider {
+ private let descriptor: Int32
+ private let encodedBytes: Int
+
+ init(descriptor: Int32, encodedBytes: Int) {
+ self.descriptor = descriptor
+ self.encodedBytes = encodedBytes
+ }
+
+ deinit {
+ Darwin.close(descriptor)
+ }
+
+ func read(into buffer: UnsafeMutableRawPointer, position: off_t, count: Int) -> Int {
+ guard position >= 0, let offset = Int(exactly: position),
+ offset <= encodedBytes else { return 0 }
+ let requested = min(count, encodedBytes - offset)
+ var completed = 0
+ while completed < requested {
+ let result = pread(
+ descriptor,
+ buffer.advanced(by: completed),
+ requested - completed,
+ off_t(offset + completed))
+ if result > 0 {
+ completed += result
+ } else if result == 0 {
+ break
+ } else if errno != EINTR {
+ break
+ }
+ }
+ return completed
+ }
+}
diff --git a/Sources/TurboFieldfare/Runtime/Vision/Preprocessing/VisionPixelBuffer.swift b/Sources/TurboFieldfare/Runtime/Vision/Preprocessing/VisionPixelBuffer.swift
new file mode 100644
index 00000000..583178b6
--- /dev/null
+++ b/Sources/TurboFieldfare/Runtime/Vision/Preprocessing/VisionPixelBuffer.swift
@@ -0,0 +1,17 @@
+import Metal
+
+public struct VisionImagePlan {
+ public let metadata: VisionImageMetadata
+ public let geometry: Gemma4ImageGeometry
+ package let opened: OpenedVisionImage
+ package let started: ContinuousClock.Instant
+}
+
+public struct VisionPixelBuffer {
+ public let patchesBF16: MTLBuffer
+ public let positionsInt32x2: MTLBuffer
+ public let metadata: VisionImageMetadata
+ public let geometry: Gemma4ImageGeometry
+ public let wallNanoseconds: UInt64
+ public let allocatedBytes: Int
+}
diff --git a/Sources/TurboFieldfare/Runtime/Vision/VisionConfig.swift b/Sources/TurboFieldfare/Runtime/Vision/VisionConfig.swift
new file mode 100644
index 00000000..2ea2526e
--- /dev/null
+++ b/Sources/TurboFieldfare/Runtime/Vision/VisionConfig.swift
@@ -0,0 +1,23 @@
+import Foundation
+
+public struct VisionConfig: Sendable, Equatable {
+ public let hiddenSize = 1_152
+ public let intermediateSize = 4_304
+ public let numLayers = 27
+ public let numHeads = 16
+ public let headDimension = 72
+ public let patchSize = 16
+ public let patchDimension = 768
+ public let maximumPatches = 2_520
+ public let poolingKernel = 3
+ public let textHiddenSize = 2_816
+ public let positionEmbeddingSize = 10_240
+ public let rmsEpsilon: Float = 1e-6
+ public let ropeTheta: Float = 100
+
+ public var maximumPooledTokens: Int {
+ maximumPatches / (poolingKernel * poolingKernel)
+ }
+
+ public init() {}
+}
diff --git a/Sources/TurboFieldfare/Runtime/Vision/VisionImageTokenBudget.swift b/Sources/TurboFieldfare/Runtime/Vision/VisionImageTokenBudget.swift
new file mode 100644
index 00000000..14d256a2
--- /dev/null
+++ b/Sources/TurboFieldfare/Runtime/Vision/VisionImageTokenBudget.swift
@@ -0,0 +1,62 @@
+import Foundation
+
+/// What bounds an image request is context, not a fixed image count.
+///
+/// This lives in the runtime rather than in one surface because the server, the
+/// CLI and the Mac app all have to answer "can these images be sent" the same
+/// way. They did not: the server derived a budget from the context while the
+/// app kept a hard limit of four, so the same conversation was accepted by one
+/// and refused by the other.
+public enum VisionImageTokenBudget {
+ /// A rendered image placeholder becomes one BOI marker, the projected image
+ /// tokens, and one EOI marker.
+ public static let markerTokensPerImage = 2
+
+ /// The most tokens a single image can cost, whatever its dimensions. A
+ /// caller that has measured the real geometry should use it; one that has
+ /// not — the app, deciding whether to accept a drop before anything is
+ /// preprocessed — can bound the answer with this.
+ public static var maximumTokensPerImage: Int {
+ VisionConfig().maximumPooledTokens + markerTokensPerImage
+ }
+
+ public static func imageTokens(softTokenCounts: [Int]) -> Int {
+ softTokenCounts.reduce(0) { $0 + $1 + markerTokensPerImage }
+ }
+
+ /// Only the prompt is required to fit. The requested reply is deliberately
+ /// not counted: the text path clamps the reply length to the remaining
+ /// context rather than refusing, and clients routinely ask for far more
+ /// than the context holds — pinned Pi 0.82.1 sends `max_tokens: 16384`
+ /// against an 8,192-token context. Counting it rejected requests the text
+ /// path would have served.
+ public static func requiredTokens(
+ softTokenCounts: [Int],
+ textTokens: Int
+ ) -> Int {
+ textTokens + imageTokens(softTokenCounts: softTokenCounts)
+ }
+
+ public static func fits(
+ softTokenCounts: [Int],
+ textTokens: Int,
+ maxContext: Int
+ ) -> Bool {
+ requiredTokens(
+ softTokenCounts: softTokenCounts,
+ textTokens: textTokens) < maxContext
+ }
+
+ /// How many images of unknown size can still be accepted, assuming each
+ /// costs the maximum. `reservedTextTokens` is the room left for the prompt
+ /// itself; the runtime still rejects a combination that does not fit, so
+ /// this only has to be a defensible ceiling rather than an exact one.
+ public static func capacity(
+ maxContext: Int,
+ reservedTextTokens: Int
+ ) -> Int {
+ let available = maxContext - reservedTextTokens
+ guard available > 0 else { return 0 }
+ return max(0, available / maximumTokensPerImage)
+ }
+}
diff --git a/Sources/TurboFieldfare/Runtime/Vision/VisionPackUseLease.swift b/Sources/TurboFieldfare/Runtime/Vision/VisionPackUseLease.swift
new file mode 100644
index 00000000..04d8df67
--- /dev/null
+++ b/Sources/TurboFieldfare/Runtime/Vision/VisionPackUseLease.swift
@@ -0,0 +1,149 @@
+import Darwin
+import Foundation
+import TurboFieldfareFormat
+
+public final class VisionPackUseLease: @unchecked Sendable {
+ /// How long `acquireShared` waits for a mutation to finish before giving
+ /// up. A blocking `flock` would wait forever, so a stuck installer would
+ /// hang model load with nothing to report.
+ public static let acquisitionTimeout: Duration = .seconds(5)
+
+ public let lockFileURL: URL
+ private let descriptor: Int32
+
+ private init(lockFileURL: URL, descriptor: Int32) {
+ self.lockFileURL = lockFileURL
+ self.descriptor = descriptor
+ }
+
+ deinit {
+ _ = flock(descriptor, LOCK_UN)
+ close(descriptor)
+ }
+
+ public static func acquireShared(
+ companionURL: URL,
+ timeout: Duration = acquisitionTimeout
+ ) throws -> VisionPackUseLease {
+ let lockURL = lockURL(for: companionURL)
+ let created = open(
+ lockURL.path,
+ O_RDWR | O_CREAT | O_NOFOLLOW | O_CLOEXEC,
+ 0o600)
+ if created >= 0 {
+ return try lease(descriptor: created, lockURL: lockURL, timeout: timeout)
+ }
+ let createErrno = errno
+ guard createErrno == EROFS || createErrno == EACCES || createErrno == EPERM else {
+ throw VisionPackError.invalidMetadata(
+ "could not open use lock at \(lockURL.path): errno \(createErrno)")
+ }
+ // A verified pack can live where the process cannot write: a read-only
+ // DMG or share, or another user's directory. `flock(LOCK_SH)` works on
+ // an O_RDONLY descriptor, so an existing lock file still coordinates
+ // with a writer even when this process cannot create one. O_NONBLOCK
+ // guards the open itself: a FIFO planted at the lock path would block
+ // a plain O_RDONLY open forever, before any flock timeout applies;
+ // opened nonblocking it proceeds and the S_IFREG check rejects it.
+ let readOnly = open(lockURL.path, O_RDONLY | O_NONBLOCK | O_NOFOLLOW | O_CLOEXEC)
+ if readOnly >= 0 {
+ return try lease(descriptor: readOnly, lockURL: lockURL, timeout: timeout)
+ }
+ let openErrno = errno
+ guard openErrno == ENOENT, createErrno == EROFS else {
+ throw VisionPackError.invalidMetadata(
+ "could not open use lock at \(lockURL.path): errno \(openErrno)")
+ }
+ // No lock file and a read-only volume: no mutator can exist there, so
+ // using the pack without a lock is sound. Hold the companion itself so
+ // the lease still owns a descriptor whose lifetime brackets the use.
+ // An unwritable directory on a writable volume deliberately stays an
+ // error above: a privileged writer could still mutate the pack there.
+ let companion = open(companionURL.standardizedFileURL.path, O_RDONLY | O_CLOEXEC)
+ guard companion >= 0 else {
+ let companionErrno = errno
+ throw VisionPackError.invalidMetadata(
+ "could not open vision companion at \(companionURL.path): "
+ + "errno \(companionErrno)")
+ }
+ return VisionPackUseLease(lockFileURL: lockURL, descriptor: companion)
+ }
+
+ private static func lease(
+ descriptor: Int32, lockURL: URL, timeout: Duration
+ ) throws -> VisionPackUseLease {
+ var info = stat()
+ guard fstat(descriptor, &info) == 0,
+ (info.st_mode & S_IFMT) == S_IFREG else {
+ let savedErrno = errno
+ close(descriptor)
+ throw VisionPackError.invalidMetadata(
+ "invalid use lock at \(lockURL.path): errno \(savedErrno)")
+ }
+ do {
+ try lock(descriptor, path: lockURL.path, timeout: timeout)
+ // The lock file could have been replaced between `open` and the
+ // successful `flock` — by a reinstall, say — in which case this
+ // holds a shared lock on an unlinked inode and the writer's
+ // exclusive lock on the new one excludes nothing.
+ guard try descriptorMatchesPath(descriptor, path: lockURL.path) else {
+ throw VisionPackError.invalidMetadata(
+ "use lock at \(lockURL.path) was replaced during acquisition")
+ }
+ } catch {
+ _ = flock(descriptor, LOCK_UN)
+ close(descriptor)
+ throw error
+ }
+ return VisionPackUseLease(lockFileURL: lockURL, descriptor: descriptor)
+ }
+
+ /// The derivation is shared with any writer-side mutation lock through
+ /// `GTurboVisionLockPathsV1`, next to the format it protects; deriving it
+ /// independently per module does not fail on mismatch — it silently leaves
+ /// the two sides locking different files.
+ public static func lockURL(for companionURL: URL) -> URL {
+ GTurboVisionLockPathsV1.useLockURL(forCompanion: companionURL)
+ }
+
+ /// Polls instead of blocking, so a mutation that never finishes surfaces as
+ /// an error rather than a hang.
+ private static func lock(
+ _ descriptor: Int32, path: String, timeout: Duration
+ ) throws {
+ let deadline = ContinuousClock.now + timeout
+ while true {
+ if flock(descriptor, LOCK_SH | LOCK_NB) == 0 { return }
+ let savedErrno = errno
+ guard savedErrno == EWOULDBLOCK else {
+ throw VisionPackError.invalidMetadata(
+ "could not acquire use lock at \(path): errno \(savedErrno)")
+ }
+ guard ContinuousClock.now < deadline else {
+ throw VisionPackError.invalidMetadata(
+ "vision companion at \(path) is being modified; "
+ + "timed out after \(timeout)")
+ }
+ var pause = timespec(tv_sec: 0, tv_nsec: 20_000_000)
+ nanosleep(&pause, nil)
+ }
+ }
+
+ private static func descriptorMatchesPath(
+ _ descriptor: Int32, path: String
+ ) throws -> Bool {
+ var descriptorInfo = stat()
+ guard fstat(descriptor, &descriptorInfo) == 0 else {
+ throw VisionPackError.invalidMetadata(
+ "could not stat use lock descriptor for \(path): errno \(errno)")
+ }
+ var pathInfo = stat()
+ guard lstat(path, &pathInfo) == 0 else {
+ throw VisionPackError.invalidMetadata(
+ "could not stat use lock at \(path): errno \(errno)")
+ }
+ return descriptorInfo.st_dev == pathInfo.st_dev
+ && descriptorInfo.st_ino == pathInfo.st_ino
+ && (pathInfo.st_mode & S_IFMT) == S_IFREG
+ }
+}
diff --git a/Sources/TurboFieldfare/Runtime/Vision/VisionResidencyPolicy.swift b/Sources/TurboFieldfare/Runtime/Vision/VisionResidencyPolicy.swift
new file mode 100644
index 00000000..bc6e89b3
--- /dev/null
+++ b/Sources/TurboFieldfare/Runtime/Vision/VisionResidencyPolicy.swift
@@ -0,0 +1,22 @@
+public enum VisionResidencyPolicy: String, Sendable, CaseIterable, Codable {
+ case onDemand = "on-demand"
+ case keepReady = "keep-ready"
+
+ /// The default every entry point uses. It is one constant because the four
+ /// entry points — runtime, conversation, session, CLI — each wrote their own
+ /// default, and one of them drifted to `keepReady`, so a conversation held
+ /// 1.1 GB of tower mappings open for the life of the process while the CLI
+ /// released them. Measured, keeping them costs ~5 MB of footprint and saves
+ /// ~105 ms of remapping, which is not worth pinning by default.
+ public static let defaultPolicy: VisionResidencyPolicy = .onDemand
+}
+
+public struct VisionExpertResidencyTransition: Sendable, Equatable {
+ public let policy: VisionResidencyPolicy
+ public let gpuDrainNanoseconds: UInt64
+ public let releasedLayerCount: Int
+ public let releasedSlotScratchBytes: UInt64
+ public let remainingOpenLayerCount: Int
+ public let remainingSlotScratchBytes: UInt64
+ public let wallNanoseconds: UInt64
+}
diff --git a/Sources/TurboFieldfare/Runtime/Vision/VisionRuntime.swift b/Sources/TurboFieldfare/Runtime/Vision/VisionRuntime.swift
new file mode 100644
index 00000000..f286fc4c
--- /dev/null
+++ b/Sources/TurboFieldfare/Runtime/Vision/VisionRuntime.swift
@@ -0,0 +1,863 @@
+import Darwin
+import Foundation
+import Metal
+import TurboFieldfareFormat
+
+public enum VisionRuntimeError: Error, CustomStringConvertible {
+ case disabled
+ case invalidInput(String)
+ case commandFailed(String)
+ case unsupportedKernel(String)
+
+ public var description: String {
+ switch self {
+ case .disabled: "vision runtime is unavailable"
+ case .invalidInput(let detail): "invalid vision input: \(detail)"
+ case .commandFailed(let detail): "vision Metal command failed: \(detail)"
+ case .unsupportedKernel(let detail): "vision kernel unavailable: \(detail)"
+ }
+ }
+}
+
+public struct VisionFeatures: @unchecked Sendable {
+ public let buffer: MTLBuffer
+ public let tokenCount: Int
+ public let hiddenSize: Int
+ public let gpuNanoseconds: UInt64
+ public let scratchBytes: Int
+ public let attentionVariant: VisionAttention.Variant
+ public let projectorPath: MPPPrefillInt4QMM.Path
+ public let expertResidencyTransition: VisionExpertResidencyTransition?
+ public let preprocessing: VisionPreprocessingReport?
+ public var wall: VisionWallBreakdown = .unmeasured
+}
+
+/// Splits tower wall time into the buckets that decide whether GPU-time work or
+/// pipelining work is worth doing: scratch allocation, weight mapping and page
+/// faults, blocking GPU waits, and the CPU encode remainder.
+public struct VisionWallBreakdown: Sendable, Equatable {
+ public static let unmeasured = VisionWallBreakdown(
+ scratchAllocationNanoseconds: 0, weightMapNanoseconds: 0,
+ gpuWaitNanoseconds: 0, totalNanoseconds: 0)
+
+ public let scratchAllocationNanoseconds: UInt64
+ public let weightMapNanoseconds: UInt64
+ public let gpuWaitNanoseconds: UInt64
+ public let totalNanoseconds: UInt64
+
+ public var encodeNanoseconds: UInt64 {
+ totalNanoseconds
+ - min(totalNanoseconds,
+ scratchAllocationNanoseconds + weightMapNanoseconds
+ + gpuWaitNanoseconds)
+ }
+}
+
+public struct VisionPreprocessingReport: Sendable, Equatable {
+ public let metadata: VisionImageMetadata
+ public let geometry: Gemma4ImageGeometry
+ public let wallNanoseconds: UInt64
+ public let allocatedBytes: Int
+}
+
+enum VisionStageClass {
+ case patchPosition
+ case attention
+ case linear
+ case elementwise
+ case poolProjector
+}
+
+/// Diagnostic-only attribution produced under TURBO_FIELDFARE_VISION_STAGE_PROFILE=1,
+/// which splits stage classes into separate command buffers. Its per-buffer sync
+/// overhead makes the totals incomparable to the promotion gpu_ms.
+public struct VisionStageProfile: Sendable, Equatable {
+ public let patchPositionNanoseconds: UInt64
+ public let attentionNanoseconds: UInt64
+ public let attentionPadNanoseconds: UInt64
+ public let attentionCoreNanoseconds: UInt64
+ public let attentionUnpadNanoseconds: UInt64
+ public let linearNanoseconds: UInt64
+ public let elementwiseNanoseconds: UInt64
+ public let poolProjectorNanoseconds: UInt64
+ public let commandBufferCount: Int
+ public let layerCount: Int
+
+ public var totalNanoseconds: UInt64 {
+ patchPositionNanoseconds + attentionNanoseconds + linearNanoseconds
+ + elementwiseNanoseconds + poolProjectorNanoseconds
+ }
+}
+
+public final class VisionRuntime {
+ public let config = VisionConfig()
+
+ private let context: MetalContext
+ private let store: VisionWeightStore
+ private let useLease: VisionPackUseLease
+ private let linear: VisionLinearBF16
+ private let primitives: VisionPrimitives
+ private let attention: VisionAttention
+ private let usesBF16Projector: Bool
+ private let splitsStagesForProfile: Bool
+ private let fusesGeGLU: Bool
+ public private(set) var lastStageProfile: VisionStageProfile?
+ /// Mapped weight regions retained across images under `.keepReady`. Mapping
+ /// and first-touching the 1.08 GB the tower reads costs the same every image
+ /// otherwise; holding the mappings pays it once. Pages are clean, file-backed
+ /// and evictable, like the routed expert pool.
+ private var cachedRegions: [String: VisionMappedWeightRegion] = [:]
+
+ /// Drops retained mappings. Called when residency returns to on-demand.
+ public func releaseCachedWeightRegions() {
+ cachedRegions.removeAll(keepingCapacity: false)
+ }
+
+ /// Maps every tower region up front and retains them, as `.keepReady` does
+ /// lazily on its first encode.
+ ///
+ /// Without this, choosing Keep Ready changed nothing until an image was
+ /// sent: the first image still paid the mapping cost the setting exists to
+ /// avoid, and any figure reporting held bytes read zero until then, which
+ /// makes the setting look inert. Pages are clean and file-backed, so this
+ /// costs mappings and page-cache residency, not process footprint.
+ @discardableResult
+ public func prewarmWeightRegions() throws -> Int {
+ for layer in 0..<config.numLayers {
+ let prefix = "vision_tower.encoder.layers.\(layer)."
+ let names = store.tensorNames(withPrefix: prefix)
+ guard !names.isEmpty else { continue }
+ let key = names.first ?? ""
+ if cachedRegions[key] == nil {
+ cachedRegions[key] = try store.mapRegion(
+ tensorNames: names, device: context.device)
+ }
+ }
+ // The same groups, in the same order, that `encodePreparedPatches` maps —
+ // the cache is keyed on a group's first tensor name, so prewarming a
+ // different grouping fills it with entries no encode ever looks up. The
+ // first version walked `vision_tower.embeddings.`, which matches nothing
+ // in this pack, and an `embed_vision.` group whose key differed from the
+ // projector's: the patch embedder was never prewarmed and the projector
+ // was mapped a second time and then held for the life of the runtime.
+ for names in [Self.patchEmbedderTensorNames, Self.projectorTensorNames] {
+ let key = names.first ?? ""
+ guard cachedRegions[key] == nil else { continue }
+ cachedRegions[key] = try store.mapRegion(
+ tensorNames: names, device: context.device)
+ }
+ return retainedWeightBytes
+ }
+
+ /// Bytes of tower weights this runtime is holding mapped.
+ ///
+ /// They are clean and file-backed, so they never appear in the process
+ /// footprint however many are held — only in resident bytes, and only once
+ /// touched. Reporting them separately is the only way to answer "what is
+ /// keep-ready costing me", which neither figure can.
+ public var retainedWeightBytes: Int {
+ cachedRegions.values.reduce(0) { $0 + $1.buffer.length }
+ }
+
+ public static func open(
+ textModelURL: URL,
+ context: MetalContext,
+ visionPackURL: URL? = nil,
+ environment: [String: String] = ProcessInfo.processInfo.environment
+ ) throws -> VisionRuntime {
+ try requireSupportedDevice(context.device)
+ let manifest = try ManifestReader.load(
+ directoryURL: textModelURL,
+ expecting: .gemma4_26B_A4B)
+ guard let source = manifest.sourceSnapshotHash else {
+ throw VisionRuntimeError.invalidInput("text model has no source identity")
+ }
+ let textManifestSHA = try Sha256Verifier.hashFile(
+ at: textModelURL.appendingPathComponent("manifest.json"))
+ let companion = try visionPackURL
+ ?? VisionPackLocation.companionURL(forTextModel: textModelURL)
+ // The pack has to exist before anything is created beside it. The lease
+ // opens its lock with O_CREAT, so taking it first meant a text-only
+ // install got a permanent stray dotfile, and a pack on a read-only
+ // volume failed with "could not open use lock ... errno 30" — a lock
+ // error standing in for a perfectly valid pack.
+ guard FileManager.default.fileExists(atPath: companion.path) else {
+ // Absence is not invalid metadata. Saying "metadata is invalid" for
+ // a pack nobody installed sends the reader looking for corruption
+ // in a file that is not there.
+ throw VisionPackError.packNotFound(companion.path)
+ }
+ // ... and it has to look like a pack, for the same reason the existence
+ // check above exists. A directory that is merely *there* — a `.partial`
+ // download, a mistyped path — also got a permanent stray lock file
+ // beside it, because the lease is created before the store validates
+ // anything. One `lstat` moves that decision ahead of the `O_CREAT`.
+ let manifestPath = companion
+ .appendingPathComponent(GTurboVisionFormatV1.manifestFile).path
+ guard FileManager.default.fileExists(atPath: manifestPath) else {
+ throw VisionPackError.invalidMetadata(
+ "no \(GTurboVisionFormatV1.manifestFile) in \(companion.path)")
+ }
+ let useLease = try VisionPackUseLease.acquireShared(companionURL: companion)
+ let store = try VisionWeightStore.open(
+ directoryURL: companion,
+ compatibleTextSourceSnapshotHash: source,
+ compatibleTextManifestSha256: textManifestSHA)
+ let runtimeEnvironment = resolvedKernelEnvironment(environment)
+ return try VisionRuntime(
+ context: context,
+ store: store,
+ useLease: useLease,
+ environment: runtimeEnvironment)
+ }
+
+ static func resolvedKernelEnvironment(
+ _ environment: [String: String]
+ ) -> [String: String] {
+ var runtimeEnvironment = environment
+ if environment["TURBO_FIELDFARE_VISION_BASELINE_KERNELS"] != "1" {
+ let explicitAttention = [
+ "TURBO_FIELDFARE_VISION_ATTENTION_Q8",
+ "TURBO_FIELDFARE_VISION_ATTENTION_Q16",
+ "TURBO_FIELDFARE_VISION_ATTENTION_MPP",
+ "TURBO_FIELDFARE_VISION_ATTENTION_PAD80",
+ "TURBO_FIELDFARE_VISION_MLX_METALLIB",
+ ].contains { environment[$0] != nil }
+ if !explicitAttention {
+ runtimeEnvironment["TURBO_FIELDFARE_VISION_ATTENTION_MPP"] = "1"
+ }
+ let explicitLinear = [
+ "TURBO_FIELDFARE_VISION_REGISTER_GEMM",
+ "TURBO_FIELDFARE_VISION_REGISTER_ATTENTION",
+ "TURBO_FIELDFARE_VISION_REGISTER_MLP",
+ "TURBO_FIELDFARE_VISION_MLX_GEMM_METALLIB",
+ ].contains { environment[$0] != nil }
+ if !explicitLinear {
+ runtimeEnvironment["TURBO_FIELDFARE_VISION_REGISTER_GEMM"] = "1"
+ }
+ }
+ return runtimeEnvironment
+ }
+
+ public static func isSupported(on device: MTLDevice) -> Bool {
+ device.supportsFamily(.apple8)
+ }
+
+ public static var isSupportedOnDefaultDevice: Bool {
+ guard let device = MTLCreateSystemDefaultDevice() else { return false }
+ return isSupported(on: device)
+ }
+
+ public static func requireSupportedDevice(_ device: MTLDevice) throws {
+ try requireSupportedDevice(supportsApple8: isSupported(on: device))
+ }
+
+ static func requireSupportedDevice(supportsApple8: Bool) throws {
+ guard supportsApple8 else {
+ throw VisionRuntimeError.unsupportedKernel(
+ "the image tower requires an M2 or newer Apple Silicon Mac")
+ }
+ }
+
+ init(context: MetalContext, store: VisionWeightStore,
+ useLease: VisionPackUseLease,
+ environment: [String: String]) throws {
+ self.context = context
+ self.store = store
+ self.useLease = useLease
+ let linear = try VisionLinearBF16(context: context, environment: environment)
+ self.linear = linear
+ self.primitives = try VisionPrimitives(context: context, environment: environment)
+ // The fused-padded-layout decision has one owner: the attention object,
+ // told here whether the linear path can write the padded head-major
+ // store. Re-deriving the AND at encode time let the two sides disagree
+ // and run a different kernel than the one diagnostics reported.
+ let shape = VisionConfig()
+ self.attention = try VisionAttention(
+ context: context, environment: environment,
+ allowFusedPaddedLayout: linear.supportsPaddedHeadStore(
+ n: shape.hiddenSize, k: shape.hiddenSize))
+ self.usesBF16Projector = context.device.supportsFamily(.apple10)
+ && environment["TURBO_FIELDFARE_VISION_FP16_PROJECTOR"] != "1"
+ self.splitsStagesForProfile =
+ environment["TURBO_FIELDFARE_VISION_STAGE_PROFILE"] == "1"
+ self.fusesGeGLU =
+ environment["TURBO_FIELDFARE_VISION_SPLIT_GEGLU"] != "1"
+ // The reduction runs on the GPU unless the environment says otherwise.
+ // Both paths apply the same weights, so this is where the arithmetic
+ // happens, not which arithmetic it is; the flag exists to fall back if
+ // a device ever disagrees with the CPU oracle.
+ self.imageResize = environment["TURBO_FIELDFARE_VISION_CPU_RESIZE"] == "1"
+ ? nil
+ : try? VisionResize(context: context)
+ // Built once per runtime; the tensorops library behind it is shared
+ // with the linear and attention kernels through
+ // `MetalContext.privateLibrary`'s cache instead of compiled per
+ // constructor.
+ self.projectorKernel = MPPPrefillInt4QMM(
+ context: context,
+ variant: usesBF16Projector
+ ? .apple10BF16
+ : context.device.supportsFamily(.apple10) ? .apple10V1 : .control)
+ }
+
+ private let projectorKernel: MPPPrefillInt4QMM
+ private let imageResize: VisionResize?
+
+ /// The tensor groups the encode path maps, named once so prewarm cannot
+ /// map a different grouping into the same cache.
+ static let patchEmbedderTensorNames = [
+ "vision_tower.patch_embedder.input_proj.weight",
+ "vision_tower.patch_embedder.position_embedding_table",
+ ]
+ static let projectorTensorNames = [
+ "vision_tower.std_bias",
+ "vision_tower.std_scale",
+ "embed_vision.embedding_projection.weight",
+ "embed_vision.embedding_projection.scales",
+ "embed_vision.embedding_projection.biases",
+ ]
+
+ public func preprocessImage(at fileURL: URL) throws -> VisionPixelBuffer {
+ try Gemma4ImagePreprocessor(device: context.device, config: config,
+ gpuResize: imageResize)
+ .preprocess(fileURL: fileURL)
+ }
+
+ public func encodeImage(
+ at fileURL: URL,
+ languageModel: Model? = nil,
+ residencyPolicy: VisionResidencyPolicy = .defaultPolicy,
+ checkCancellation: () throws -> Void = {}
+ ) throws -> VisionFeatures {
+ let preprocessor = Gemma4ImagePreprocessor(device: context.device, config: config,
+ gpuResize: imageResize)
+ return try encodeImage(
+ plan: try preprocessor.plan(fileURL: fileURL),
+ languageModel: languageModel,
+ residencyPolicy: residencyPolicy,
+ checkCancellation: checkCancellation)
+ }
+
+ /// Encodes an image the caller has already planned.
+ ///
+ /// Callers plan first to learn the token count, and re-planning here opened
+ /// the file a second time for another ImageIO sniff, metadata parse and
+ /// marker walk — per image, per turn. It also validated the encode against
+ /// metadata that a file swapped between the two opens would no longer match.
+ public func encodeImage(
+ plan: VisionImagePlan,
+ languageModel: Model? = nil,
+ residencyPolicy: VisionResidencyPolicy = .defaultPolicy,
+ checkCancellation: () throws -> Void = {}
+ ) throws -> VisionFeatures {
+ try checkCancellation()
+ let preprocessor = Gemma4ImagePreprocessor(device: context.device, config: config,
+ gpuResize: imageResize)
+ try checkCancellation()
+ let gpuDrainNanoseconds = try languageModel != nil && residencyPolicy == .onDemand
+ ? drainGPU() : 0
+ try checkCancellation()
+ let transition = languageModel?.prepareExpertResidencyForVision(
+ residencyPolicy, gpuDrainNanoseconds: gpuDrainNanoseconds)
+ try checkCancellation()
+ let input = try preprocessor.preprocess(plan)
+ return try encodePreparedPatches(
+ patchesBF16: input.patchesBF16,
+ positionsInt32x2: input.positionsInt32x2,
+ patchGridWidth: input.geometry.patchGridWidth,
+ patchGridHeight: input.geometry.patchGridHeight,
+ expertResidencyTransition: transition,
+ preprocessing: VisionPreprocessingReport(
+ metadata: input.metadata,
+ geometry: input.geometry,
+ wallNanoseconds: input.wallNanoseconds,
+ allocatedBytes: input.allocatedBytes),
+ retainsWeightRegions: residencyPolicy == .keepReady,
+ checkCancellation: checkCancellation)
+ }
+
+ public func encodePatches(
+ patchesBF16: MTLBuffer,
+ positionsInt32x2: MTLBuffer,
+ patchGridWidth: Int,
+ patchGridHeight: Int,
+ languageModel: Model? = nil,
+ residencyPolicy: VisionResidencyPolicy = .defaultPolicy,
+ checkCancellation: () throws -> Void = {}
+ ) throws -> VisionFeatures {
+ try checkCancellation()
+ let rows = patchGridWidth * patchGridHeight
+ guard patchGridWidth > 0, patchGridHeight > 0,
+ patchGridWidth.isMultiple(of: config.poolingKernel),
+ patchGridHeight.isMultiple(of: config.poolingKernel),
+ rows <= config.maximumPatches else {
+ throw VisionRuntimeError.invalidInput(
+ "patch grid must be positive, 3-aligned, and no larger than 2520")
+ }
+ // Coordinates are validated here, once, rather than per element in the
+ // kernel: `vision.metal` reinterprets them as unsigned and multiplies
+ // them into the position table, so a -1 from a caller building its own
+ // buffers wraps to 4294967295 and reads far past the mapping — a GPU
+ // fault, or a confident description of an image nobody sent.
+ // `contents()` is invalid for private storage, so the CPU-side loop
+ // below would fault on exactly the caller-built buffer it validates.
+ guard positionsInt32x2.storageMode != .private else {
+ throw VisionRuntimeError.invalidInput(
+ "patch positions must be CPU-visible (shared) so they can be validated")
+ }
+ let positionCount = positionsInt32x2.length / (2 * MemoryLayout<Int32>.stride)
+ if positionCount >= rows {
+ let coordinates = positionsInt32x2.contents()
+ .bindMemory(to: Int32.self, capacity: positionCount * 2)
+ let limit = Int32(config.positionEmbeddingSize)
+ for index in 0..<(rows * 2) {
+ let value = coordinates[index]
+ guard value >= 0, value < limit else {
+ throw VisionRuntimeError.invalidInput(
+ "patch position \(value) outside 0..<\(limit)")
+ }
+ }
+ }
+ guard patchesBF16.length >= rows * config.patchDimension * 2,
+ positionsInt32x2.length >= rows * 2 * MemoryLayout<Int32>.stride else {
+ throw VisionRuntimeError.invalidInput("patch or position buffer is too small")
+ }
+
+ let gpuDrainNanoseconds = try languageModel != nil && residencyPolicy == .onDemand
+ ? drainGPU() : 0
+ try checkCancellation()
+ let transition = languageModel?.prepareExpertResidencyForVision(
+ residencyPolicy, gpuDrainNanoseconds: gpuDrainNanoseconds)
+ try checkCancellation()
+ return try encodePreparedPatches(
+ patchesBF16: patchesBF16,
+ positionsInt32x2: positionsInt32x2,
+ patchGridWidth: patchGridWidth,
+ patchGridHeight: patchGridHeight,
+ expertResidencyTransition: transition,
+ preprocessing: nil,
+ retainsWeightRegions: residencyPolicy == .keepReady,
+ checkCancellation: checkCancellation)
+ }
+
+ private func encodePreparedPatches(
+ patchesBF16: MTLBuffer,
+ positionsInt32x2: MTLBuffer,
+ patchGridWidth: Int,
+ patchGridHeight: Int,
+ expertResidencyTransition: VisionExpertResidencyTransition?,
+ preprocessing: VisionPreprocessingReport?,
+ retainsWeightRegions: Bool,
+ checkCancellation: () throws -> Void
+ ) throws -> VisionFeatures {
+ if !retainsWeightRegions { releaseCachedWeightRegions() }
+ try checkCancellation()
+ let rows = patchGridWidth * patchGridHeight
+
+ let wallStarted = clock_gettime_nsec_np(CLOCK_UPTIME_RAW)
+ // The QKV projections write the padded head-major layout directly when the
+ // register GEMM and the MPP attention kernel both support it, which removes
+ // the pad/unpad dispatches and the hidden-width K/V scratch. The attention
+ // object owns the decision — it was constructed with the linear path's
+ // capability — so it is read, never re-derived, here.
+ let fusedPaddedLayout = attention.usesFusedPaddedLayout
+ // The up projection folds GeGLU into its epilogue, which removes the
+ // separate elementwise dispatch and the `up` scratch buffer.
+ let fusedGeGLU = fusesGeGLU
+ && linear.supportsFusedGeGLU(n: config.intermediateSize,
+ k: config.hiddenSize)
+ let scratch = try VisionScratch(device: context.device, rows: rows,
+ config: config,
+ needsSeparateKV: !fusedPaddedLayout,
+ needsSeparateUp: !fusedGeGLU)
+ let qBuffer = fusedPaddedLayout ? (attention.fusedQ ?? scratch.q) : scratch.q
+ let kBuffer = fusedPaddedLayout ? (attention.fusedK ?? scratch.q) : (scratch.k ?? scratch.q)
+ let vBuffer = fusedPaddedLayout ? (attention.fusedV ?? scratch.q) : (scratch.v ?? scratch.q)
+ let paddedHeadStore = fusedPaddedLayout
+ ? VisionLinearBF16.PaddedHeadStore(
+ rowStride: scratch.paddedRows,
+ headDim: VisionAttention.headDimension,
+ paddedHeadDim: VisionAttention.paddedHeadDimension)
+ : nil
+ let scratchAllocationNanoseconds =
+ clock_gettime_nsec_np(CLOCK_UPTIME_RAW) - wallStarted
+ var weightMapNanoseconds: UInt64 = 0
+ var gpuWaitNanoseconds: UInt64 = 0
+ func mapRegion(_ tensorNames: [String]) throws -> VisionMappedWeightRegion {
+ let started = clock_gettime_nsec_np(CLOCK_UPTIME_RAW)
+ defer {
+ weightMapNanoseconds += clock_gettime_nsec_np(CLOCK_UPTIME_RAW) - started
+ }
+ let key = tensorNames.first ?? ""
+ if retainsWeightRegions, let cached = cachedRegions[key] {
+ return cached
+ }
+ let region = try store.mapRegion(
+ tensorNames: tensorNames, device: context.device)
+ if retainsWeightRegions { cachedRegions[key] = region }
+ return region
+ }
+ func commitMeasured(_ commandBuffer: MTLCommandBuffer) throws -> UInt64 {
+ let started = clock_gettime_nsec_np(CLOCK_UPTIME_RAW)
+ defer {
+ gpuWaitNanoseconds += clock_gettime_nsec_np(CLOCK_UPTIME_RAW) - started
+ }
+ return try commitAndMeasure(commandBuffer)
+ }
+ var gpuNanoseconds: UInt64 = 0
+ // The non-profile encode pipelines command buffers: the CPU encodes
+ // the next layer while the GPU executes the previous one, instead of
+ // a blocking drain per layer — 29 per image before this. An in-flight
+ // entry keeps its mapped weight region alive until its buffer
+ // completes, and the window bounds `.onDemand` residency to
+ // `pipelineDepth + 1` regions instead of the whole tower.
+ var inFlight: [(buffer: MTLCommandBuffer, region: VisionMappedWeightRegion?)] = []
+ let pipelineDepth = 2
+ func drainOldest() throws {
+ let entry = inFlight.removeFirst()
+ let started = clock_gettime_nsec_np(CLOCK_UPTIME_RAW)
+ entry.buffer.waitUntilCompleted()
+ gpuWaitNanoseconds += clock_gettime_nsec_np(CLOCK_UPTIME_RAW) - started
+ if let error = entry.buffer.error {
+ throw VisionRuntimeError.commandFailed(String(describing: error))
+ }
+ gpuNanoseconds += UInt64(
+ max(0, entry.buffer.gpuEndTime - entry.buffer.gpuStartTime)
+ * 1_000_000_000)
+ }
+ func commitPipelined(_ buffer: MTLCommandBuffer,
+ retaining region: VisionMappedWeightRegion?) throws {
+ buffer.commit()
+ inFlight.append((buffer, region))
+ while inFlight.count > pipelineDepth { try drainOldest() }
+ }
+ // A throw mid-encode must not release mapped regions while the GPU is
+ // still reading them; defers run before locals, so drain first.
+ defer {
+ for entry in inFlight { entry.buffer.waitUntilCompleted() }
+ }
+ var stagePatchPosition: UInt64 = 0
+ var stageAttention: UInt64 = 0
+ var stageLinear: UInt64 = 0
+ var stageElementwise: UInt64 = 0
+ var stagePoolProjector: UInt64 = 0
+ var stageCommandBuffers = 0
+ var stageAttentionPad: UInt64 = 0
+ var stageAttentionCore: UInt64 = 0
+ var stageAttentionUnpad: UInt64 = 0
+ var lastStageElapsed: UInt64 = 0
+ lastStageProfile = nil
+
+ // In stage-profile mode each stage class runs in its own command buffer so
+ // its GPU time is attributable; otherwise `shared` carries the whole layer.
+ func stage(_ kind: VisionStageClass, on shared: MTLCommandBuffer?,
+ _ body: (MTLCommandBuffer) throws -> Void) throws {
+ if let shared {
+ try body(shared)
+ return
+ }
+ let buffer = try makeCommandBuffer()
+ try body(buffer)
+ let elapsed = try commitMeasured(buffer)
+ gpuNanoseconds += elapsed
+ lastStageElapsed = elapsed
+ stageCommandBuffers += 1
+ switch kind {
+ case .patchPosition: stagePatchPosition += elapsed
+ case .attention: stageAttention += elapsed
+ case .linear: stageLinear += elapsed
+ case .elementwise: stageElementwise += elapsed
+ case .poolProjector: stagePoolProjector += elapsed
+ }
+ }
+
+ let patchWeight = Self.patchEmbedderTensorNames[0]
+ let positionTable = Self.patchEmbedderTensorNames[1]
+ do {
+ let fixed = try mapRegion(Self.patchEmbedderTensorNames)
+ let shared = splitsStagesForProfile ? nil : try makeCommandBuffer()
+ try stage(.patchPosition, on: shared) { commandBuffer in
+ try scratch.encodeClear(commandBuffer: commandBuffer)
+ attention.encodeClearPadding(commandBuffer: commandBuffer)
+ primitives.encodeNormalize(commandBuffer: commandBuffer,
+ input: patchesBF16,
+ output: scratch.normalizedPatches,
+ rows: rows, paddedRows: scratch.paddedRows)
+ linear.encode(
+ commandBuffer: commandBuffer,
+ input: scratch.normalizedPatches,
+ weights: fixed.buffer, weightsOffset: try fixed.offset(of: patchWeight),
+ output: scratch.hiddenA,
+ m: scratch.paddedRows, n: config.hiddenSize, k: config.patchDimension)
+ primitives.encodeAddPosition(
+ commandBuffer: commandBuffer,
+ hidden: scratch.hiddenA,
+ table: fixed.buffer, tableOffset: try fixed.offset(of: positionTable),
+ positions: positionsInt32x2, rows: rows)
+ }
+ if let shared {
+ try commitPipelined(shared, retaining: fixed)
+ }
+ }
+
+ for layer in 0..<config.numLayers {
+ try checkCancellation()
+ let prefix = "vision_tower.encoder.layers.\(layer)."
+ let names = store.tensorNames(withPrefix: prefix)
+ guard names.count == 13 else {
+ throw VisionRuntimeError.invalidInput(
+ "layer \(layer) expected 13 tensors, found \(names.count)")
+ }
+ let weights = try mapRegion(names)
+ let shared = splitsStagesForProfile ? nil : try makeCommandBuffer()
+ func offset(_ suffix: String) throws -> Int {
+ try weights.offset(of: prefix + suffix)
+ }
+
+ try stage(.elementwise, on: shared) { commandBuffer in
+ primitives.encodeRMSNorm(
+ commandBuffer: commandBuffer,
+ input: scratch.hiddenA, output: scratch.hiddenB,
+ weightBuffer: weights.buffer,
+ weightOffset: try offset("input_layernorm.weight"), rows: rows)
+ }
+ try stage(.linear, on: shared) { commandBuffer in
+ for (suffix, output) in [
+ ("self_attn.q_proj.linear.weight", qBuffer),
+ ("self_attn.k_proj.linear.weight", kBuffer),
+ ("self_attn.v_proj.linear.weight", vBuffer),
+ ] {
+ linear.encode(
+ commandBuffer: commandBuffer,
+ input: scratch.hiddenB,
+ weights: weights.buffer, weightsOffset: try offset(suffix),
+ output: output,
+ m: scratch.paddedRows, n: config.hiddenSize, k: config.hiddenSize,
+ paddedHeadStore: paddedHeadStore)
+ }
+ }
+ try stage(.elementwise, on: shared) { commandBuffer in
+ primitives.encodeQKV(
+ commandBuffer: commandBuffer,
+ q: qBuffer, k: kBuffer, v: vBuffer,
+ weights: weights.buffer,
+ qWeightOffset: try offset("self_attn.q_norm.weight"),
+ kWeightOffset: try offset("self_attn.k_norm.weight"),
+ positions: positionsInt32x2,
+ rows: rows, heads: config.numHeads,
+ paddedRowStride: fusedPaddedLayout ? scratch.paddedRows : 0)
+ }
+ let inputRowStride = fusedPaddedLayout ? scratch.paddedRows : 0
+ if let shared {
+ attention.encode(commandBuffer: shared,
+ q: qBuffer, k: kBuffer, v: vBuffer,
+ output: scratch.attention,
+ sequenceLength: rows, numHeads: config.numHeads,
+ inputRowStride: inputRowStride)
+ } else {
+ var phaseError: Error?
+ attention.encodePhased(
+ q: qBuffer, k: kBuffer, v: vBuffer,
+ output: scratch.attention,
+ sequenceLength: rows, numHeads: config.numHeads,
+ inputRowStride: inputRowStride
+ ) { phase, body in
+ guard phaseError == nil else { return }
+ do {
+ try stage(.attention, on: nil) { commandBuffer in
+ body(commandBuffer)
+ }
+ switch phase {
+ case .pad: stageAttentionPad += lastStageElapsed
+ case .core: stageAttentionCore += lastStageElapsed
+ case .unpad: stageAttentionUnpad += lastStageElapsed
+ }
+ } catch {
+ phaseError = error
+ }
+ }
+ if let phaseError { throw phaseError }
+ }
+ try stage(.linear, on: shared) { commandBuffer in
+ linear.encode(
+ commandBuffer: commandBuffer,
+ input: scratch.attention,
+ weights: weights.buffer,
+ weightsOffset: try offset("self_attn.o_proj.linear.weight"),
+ output: scratch.q,
+ m: scratch.paddedRows, n: config.hiddenSize, k: config.hiddenSize)
+ }
+ try stage(.elementwise, on: shared) { commandBuffer in
+ primitives.encodePostnormResidual(
+ commandBuffer: commandBuffer,
+ residual: scratch.hiddenA, branch: scratch.q,
+ weightBuffer: weights.buffer,
+ weightOffset: try offset("post_attention_layernorm.weight"),
+ output: scratch.hiddenB, rows: rows)
+ primitives.encodeRMSNorm(
+ commandBuffer: commandBuffer,
+ input: scratch.hiddenB, output: scratch.q,
+ weightBuffer: weights.buffer,
+ weightOffset: try offset("pre_feedforward_layernorm.weight"), rows: rows)
+ }
+ try stage(.linear, on: shared) { commandBuffer in
+ linear.encode(
+ commandBuffer: commandBuffer,
+ input: scratch.q,
+ weights: weights.buffer,
+ weightsOffset: try offset("mlp.gate_proj.linear.weight"),
+ output: scratch.gate,
+ m: scratch.paddedRows, n: config.intermediateSize,
+ k: config.hiddenSize)
+ linear.encode(
+ commandBuffer: commandBuffer,
+ input: scratch.q,
+ weights: weights.buffer,
+ weightsOffset: try offset("mlp.up_proj.linear.weight"),
+ output: fusedGeGLU ? scratch.gate : (scratch.up ?? scratch.gate),
+ m: scratch.paddedRows, n: config.intermediateSize,
+ k: config.hiddenSize,
+ fusesGeGLU: fusedGeGLU)
+ }
+ if !fusedGeGLU, let up = scratch.up {
+ try stage(.elementwise, on: shared) { commandBuffer in
+ primitives.encodeGeGLU(commandBuffer: commandBuffer,
+ gate: scratch.gate, up: up,
+ count: rows * config.intermediateSize)
+ }
+ }
+ try stage(.linear, on: shared) { commandBuffer in
+ linear.encode(
+ commandBuffer: commandBuffer,
+ input: scratch.gate,
+ weights: weights.buffer,
+ weightsOffset: try offset("mlp.down_proj.linear.weight"),
+ output: scratch.q,
+ m: scratch.paddedRows, n: config.hiddenSize, k: config.intermediateSize)
+ }
+ try stage(.elementwise, on: shared) { commandBuffer in
+ primitives.encodePostnormResidual(
+ commandBuffer: commandBuffer,
+ residual: scratch.hiddenB, branch: scratch.q,
+ weightBuffer: weights.buffer,
+ weightOffset: try offset("post_feedforward_layernorm.weight"),
+ output: scratch.hiddenA, rows: rows)
+ }
+ if let shared {
+ try commitPipelined(shared, retaining: weights)
+ }
+ }
+
+ let outputRows = (patchGridWidth / config.poolingKernel)
+ * (patchGridHeight / config.poolingKernel)
+ try checkCancellation()
+ let projectorNames = Self.projectorTensorNames
+ let projector = try mapRegion(projectorNames)
+ guard let features = context.device.makeBuffer(
+ length: outputRows * config.textHiddenSize * MemoryLayout<Float16>.stride,
+ options: .storageModeShared) else {
+ throw MetalError.noDevice
+ }
+ guard projectorKernel.isAvailable else {
+ throw VisionRuntimeError.unsupportedKernel(
+ projectorKernel.unavailableReason ?? "INT4 projector unavailable")
+ }
+ let shared = splitsStagesForProfile ? nil : try makeCommandBuffer()
+ var projectorMetadata: MPPPrefillInt4QMM.PathMetadata?
+ try stage(.poolProjector, on: shared) { commandBuffer in
+ primitives.encodePool(
+ commandBuffer: commandBuffer,
+ input: scratch.hiddenA,
+ weights: projector.buffer,
+ stdBiasOffset: try projector.offset(of: "vision_tower.std_bias"),
+ stdScaleOffset: try projector.offset(of: "vision_tower.std_scale"),
+ output: scratch.attention,
+ patchWidth: patchGridWidth, patchHeight: patchGridHeight)
+ if !usesBF16Projector {
+ primitives.encodeBFloatToHalf(
+ commandBuffer: commandBuffer,
+ input: scratch.attention, output: scratch.hiddenB,
+ count: outputRows * config.hiddenSize)
+ }
+ projectorMetadata = projectorKernel.encode(
+ commandBuffer: commandBuffer,
+ weights: projector.buffer,
+ weightsOffset: try projector.offset(
+ of: "embed_vision.embedding_projection.weight"),
+ scales: projector.buffer,
+ scalesOffset: try projector.offset(
+ of: "embed_vision.embedding_projection.scales"),
+ biases: projector.buffer,
+ biasesOffset: try projector.offset(
+ of: "embed_vision.embedding_projection.biases"),
+ x: usesBF16Projector ? scratch.attention : scratch.hiddenB,
+ y: features,
+ m: outputRows, n: config.textHiddenSize, k: config.hiddenSize)
+ }
+ guard let projectorMetadata, projectorMetadata.path != .fallback else {
+ throw VisionRuntimeError.unsupportedKernel("INT4 projector fell back")
+ }
+ if let shared {
+ try commitPipelined(shared, retaining: projector)
+ }
+ while !inFlight.isEmpty { try drainOldest() }
+ if splitsStagesForProfile {
+ lastStageProfile = VisionStageProfile(
+ patchPositionNanoseconds: stagePatchPosition,
+ attentionNanoseconds: stageAttention,
+ attentionPadNanoseconds: stageAttentionPad,
+ attentionCoreNanoseconds: stageAttentionCore,
+ attentionUnpadNanoseconds: stageAttentionUnpad,
+ linearNanoseconds: stageLinear,
+ elementwiseNanoseconds: stageElementwise,
+ poolProjectorNanoseconds: stagePoolProjector,
+ commandBufferCount: stageCommandBuffers,
+ layerCount: config.numLayers)
+ }
+
+ return VisionFeatures(buffer: features,
+ tokenCount: outputRows,
+ hiddenSize: config.textHiddenSize,
+ gpuNanoseconds: gpuNanoseconds,
+ scratchBytes: scratch.allocatedBytes
+ + attention.additionalScratchBytes,
+ attentionVariant: attention.variant,
+ projectorPath: projectorMetadata.path,
+ expertResidencyTransition: expertResidencyTransition,
+ preprocessing: preprocessing,
+ wall: VisionWallBreakdown(
+ scratchAllocationNanoseconds: scratchAllocationNanoseconds,
+ weightMapNanoseconds: weightMapNanoseconds,
+ gpuWaitNanoseconds: gpuWaitNanoseconds,
+ totalNanoseconds: clock_gettime_nsec_np(CLOCK_UPTIME_RAW)
+ - wallStarted))
+ }
+
+ private func makeCommandBuffer() throws -> MTLCommandBuffer {
+ guard let value = context.queue.makeCommandBuffer() else { throw MetalError.noQueue }
+ return value
+ }
+
+ private func drainGPU() throws -> UInt64 {
+ let started = clock_gettime_nsec_np(CLOCK_UPTIME_RAW)
+ let commandBuffer = try makeCommandBuffer()
+ commandBuffer.commit()
+ commandBuffer.waitUntilCompleted()
+ if let error = commandBuffer.error {
+ throw VisionRuntimeError.commandFailed(String(describing: error))
+ }
+ return clock_gettime_nsec_np(CLOCK_UPTIME_RAW) - started
+ }
+
+ private func commitAndMeasure(_ commandBuffer: MTLCommandBuffer) throws -> UInt64 {
+ commandBuffer.commit()
+ commandBuffer.waitUntilCompleted()
+ if let error = commandBuffer.error {
+ throw VisionRuntimeError.commandFailed(String(describing: error))
+ }
+ return UInt64(max(0, commandBuffer.gpuEndTime - commandBuffer.gpuStartTime)
+ * 1_000_000_000)
+ }
+
+}
diff --git a/Sources/TurboFieldfare/Runtime/Vision/VisionScratch.swift b/Sources/TurboFieldfare/Runtime/Vision/VisionScratch.swift
new file mode 100644
index 00000000..07ec7b9b
--- /dev/null
+++ b/Sources/TurboFieldfare/Runtime/Vision/VisionScratch.swift
@@ -0,0 +1,75 @@
+import Metal
+
+package final class VisionScratch {
+ package let paddedRows: Int
+ /// Live rows, so the clear can skip everything a dispatch will overwrite.
+ package let rows: Int
+ private let hiddenSize: Int
+ package let normalizedPatches: MTLBuffer
+ package let hiddenA: MTLBuffer
+ package let hiddenB: MTLBuffer
+ package let q: MTLBuffer
+ /// Nil under the fused padded attention layout, where the QKV projections
+ /// write the attention-owned padded buffers instead of hidden-width scratch.
+ package let k: MTLBuffer?
+ package let v: MTLBuffer?
+ package let attention: MTLBuffer
+ package let gate: MTLBuffer
+ /// Nil when the up projection folds GeGLU into its epilogue.
+ package let up: MTLBuffer?
+
+ package init(device: MTLDevice, rows: Int, config: VisionConfig,
+ needsSeparateKV: Bool = true,
+ needsSeparateUp: Bool = true) throws {
+ paddedRows = ((rows + 63) / 64) * 64
+ self.rows = rows
+ self.hiddenSize = config.hiddenSize
+ func buffer(_ elements: Int) throws -> MTLBuffer {
+ guard let value = device.makeBuffer(
+ length: elements * MemoryLayout<UInt16>.stride,
+ options: .storageModePrivate) else {
+ throw MetalError.noDevice
+ }
+ return value
+ }
+ normalizedPatches = try buffer(paddedRows * config.patchDimension)
+ hiddenA = try buffer(paddedRows * config.hiddenSize)
+ hiddenB = try buffer(paddedRows * config.hiddenSize)
+ q = try buffer(paddedRows * config.hiddenSize)
+ k = needsSeparateKV ? try buffer(paddedRows * config.hiddenSize) : nil
+ v = needsSeparateKV ? try buffer(paddedRows * config.hiddenSize) : nil
+ attention = try buffer(paddedRows * config.hiddenSize)
+ gate = try buffer(paddedRows * config.intermediateSize + 64)
+ up = needsSeparateUp
+ ? try buffer(paddedRows * config.intermediateSize + 64) : nil
+ }
+
+ private var buffers: [MTLBuffer] {
+ [normalizedPatches, hiddenA, hiddenB, q, attention, gate]
+ + [k, v, up].compactMap(\.self)
+ }
+
+ /// Zeroes only what a later read can actually see.
+ ///
+ /// Clearing every buffer meant about 47 MiB of blit fills per image at the
+ /// 2,520-patch maximum, nearly all of it dead: `normalizedPatches`, `q` and
+ /// `gate` are fully overwritten by the dispatch that follows, which zeroes
+ /// its own pad region. What genuinely has to start clean is the padding
+ /// rows of the two buffers whose tails are read back — `hiddenB` and
+ /// `attention` — which is under 300 KB.
+ package func encodeClear(commandBuffer: MTLCommandBuffer) throws {
+ guard let blit = commandBuffer.makeBlitCommandEncoder() else {
+ throw MetalError.noDevice
+ }
+ let liveBytes = rows * hiddenSize * MemoryLayout<UInt16>.stride
+ for buffer in [hiddenB, attention] {
+ guard buffer.length > liveBytes else { continue }
+ blit.fill(buffer: buffer, range: liveBytes..<buffer.length, value: 0)
+ }
+ blit.endEncoding()
+ }
+
+ package var allocatedBytes: Int {
+ buffers.reduce(0) { $0 + $1.length }
+ }
+}
diff --git a/Sources/TurboFieldfare/Runtime/Vision/VisionWeightStore.swift b/Sources/TurboFieldfare/Runtime/Vision/VisionWeightStore.swift
new file mode 100644
index 00000000..029f0be4
--- /dev/null
+++ b/Sources/TurboFieldfare/Runtime/Vision/VisionWeightStore.swift
@@ -0,0 +1,279 @@
+import Darwin
+import Foundation
+import Metal
+import TurboFieldfareFormat
+
+public enum VisionPackError: Error, Equatable, CustomStringConvertible, Sendable {
+ case invalidTextModelPath(String)
+ case packNotFound(String)
+ case invalidMetadata(String)
+ case incompatibleTextArtifact
+ case invalidReceipt(String)
+ case invalidDirectoryEntries(String)
+ case fileSizeMismatch(file: String, expected: UInt64, actual: UInt64)
+ case regionExceedsDevice(name: String, bytes: UInt64, maximum: UInt64)
+
+ public var description: String {
+ switch self {
+ case let .invalidTextModelPath(path):
+ "text model path is not a .gturbo directory: \(path)"
+ case let .packNotFound(path):
+ "no vision companion pack at \(path)"
+ case let .invalidMetadata(detail):
+ "vision companion metadata is invalid: \(detail)"
+ case .incompatibleTextArtifact:
+ "vision companion does not match the loaded text artifact"
+ case let .invalidReceipt(detail):
+ "vision companion receipt is invalid: \(detail)"
+ case let .invalidDirectoryEntries(difference):
+ "vision companion directory does not match the v1 contract: \(difference)"
+ case let .fileSizeMismatch(file, expected, actual):
+ "\(file) size \(actual) does not match manifest size \(expected)"
+ case let .regionExceedsDevice(name, bytes, maximum):
+ "vision tensor \(name) region \(bytes) exceeds Metal maximum \(maximum)"
+ }
+ }
+}
+
+public enum VisionPackLocation {
+ public static func companionURL(forTextModel textModelURL: URL) throws -> URL {
+ let standardized = textModelURL.standardizedFileURL
+ let name = standardized.lastPathComponent
+ guard name.hasSuffix(".gturbo"), name.count > ".gturbo".count else {
+ throw VisionPackError.invalidTextModelPath(standardized.path)
+ }
+ let stem = name.dropLast(".gturbo".count)
+ return standardized.deletingLastPathComponent()
+ .appendingPathComponent("\(stem).vision.gturbo", isDirectory: true)
+ }
+}
+
+final class VisionWeightStore {
+ let directoryURL: URL
+ let manifest: GTurboVisionManifestV1
+ private let directory: GTurboModelDirectory
+ private let weightsFD: Int32
+
+ static func open(
+ directoryURL: URL,
+ compatibleTextSourceSnapshotHash: String,
+ compatibleTextManifestSha256: String
+ ) throws -> VisionWeightStore {
+ // "Metadata is invalid" for a pack that was never installed sends the
+ // reader looking for corruption. Absence is its own answer.
+ var isDirectory: ObjCBool = false
+ guard FileManager.default.fileExists(
+ atPath: directoryURL.standardizedFileURL.path,
+ isDirectory: &isDirectory), isDirectory.boolValue else {
+ throw VisionPackError.packNotFound(directoryURL.standardizedFileURL.path)
+ }
+ let directory: GTurboModelDirectory
+ do { directory = try GTurboModelDirectory(rootURL: directoryURL) }
+ catch { throw VisionPackError.invalidMetadata("\(error)") }
+
+ let manifestData: Data
+ let receiptData: Data
+ do {
+ manifestData = try directory.readMetadata(
+ GTurboVisionFormatV1.manifestFile,
+ maxBytes: GTurboVisionFormatV1.metadataMaxBytes)
+ receiptData = try directory.readMetadata(
+ GTurboVisionFormatV1.receiptFile,
+ maxBytes: GTurboVisionFormatV1.metadataMaxBytes)
+ } catch {
+ throw VisionPackError.invalidMetadata("\(error)")
+ }
+
+ let manifest: GTurboVisionManifestV1
+ let receipt: GTurboVisionReceiptV1
+ do {
+ manifest = try GTurboVisionManifestCodec.decode(manifestData)
+ receipt = try GTurboVisionReceiptCodec.decode(receiptData)
+ } catch {
+ throw VisionPackError.invalidMetadata("\(error)")
+ }
+ guard manifest.compatibleTextSourceSnapshotHash
+ == compatibleTextSourceSnapshotHash,
+ manifest.compatibleTextManifestSha256.lowercased()
+ == compatibleTextManifestSha256.lowercased() else {
+ throw VisionPackError.incompatibleTextArtifact
+ }
+
+ let manifestSHA = Sha256Verifier.hashData(manifestData)
+ let receiptDirectory = canonicalVisionDirectoryPath(URL(
+ fileURLWithPath: receipt.companionDirectoryPath,
+ isDirectory: true))
+ let openedDirectory = canonicalVisionDirectoryPath(directoryURL)
+ guard receipt.manifestSha256.lowercased() == manifestSHA,
+ receipt.compatibleTextManifestSha256.lowercased()
+ == compatibleTextManifestSha256.lowercased(),
+ receipt.sourceRepoID == manifest.modelID,
+ receipt.sourceRevision == manifest.sourceRevision,
+ receiptDirectory == openedDirectory else {
+ throw VisionPackError.invalidReceipt("path or manifest binding mismatch")
+ }
+ let manifestEntry = receipt.files[GTurboVisionFormatV1.manifestFile]
+ guard manifestEntry?.size == UInt64(manifestData.count),
+ manifestEntry?.sha256.lowercased() == manifestSHA else {
+ throw VisionPackError.invalidReceipt("manifest entry mismatch")
+ }
+ for (path, file) in manifest.files {
+ guard let receiptFile = receipt.files[path],
+ receiptFile.size == file.size,
+ receiptFile.sha256.lowercased() == file.sha256.lowercased() else {
+ throw VisionPackError.invalidReceipt("payload entry mismatch for \(path)")
+ }
+ }
+
+ let expectedEntries = Set([
+ GTurboVisionFormatV1.manifestFile,
+ GTurboVisionFormatV1.weightsFile,
+ GTurboVisionFormatV1.processorFile,
+ GTurboVisionFormatV1.receiptFile,
+ ])
+ let actualEntries: Set<String>
+ do { actualEntries = try directory.basenames() }
+ catch { throw VisionPackError.invalidMetadata("\(error)") }
+ // Ignoring what the OS puts there on its own, exactly as the installer's
+ // verifier does. Requiring an exact match meant opening the pack folder
+ // in Finder once left `.DS_Store` behind and every later load failed as
+ // an invalid pack, reporting "image support is unavailable" for a pack
+ // that installed and verified cleanly.
+ let entries = actualEntries.filter { !GTurboVisionFormatV1.isSidecarEntry($0) }
+ guard entries == expectedEntries else {
+ throw VisionPackError.invalidDirectoryEntries(
+ GTurboVisionFormatV1.entryDifference(
+ expected: expectedEntries, actual: entries))
+ }
+
+ for (path, file) in manifest.files {
+ let actual: UInt64
+ do { actual = try directory.fileSize(path) }
+ catch { throw VisionPackError.invalidMetadata("\(error)") }
+ guard actual == file.size else {
+ throw VisionPackError.fileSizeMismatch(
+ file: path, expected: file.size, actual: actual)
+ }
+ }
+ // Both sides of the old check came out of the same manifest, so it was
+ // self-consistent by construction and could only catch a mis-built
+ // pack. The processor config is small and is the one payload file whose
+ // content changes behaviour, so its bytes are hashed here — the weights
+ // are covered by the receipt and their size, as before.
+ let processorPath = GTurboVisionFormatV1.processorFile
+ guard let processorEntry = manifest.files[processorPath] else {
+ throw VisionPackError.invalidMetadata("manifest has no \(processorPath)")
+ }
+ guard manifest.processorConfigSha256.lowercased()
+ == processorEntry.sha256.lowercased() else {
+ throw VisionPackError.invalidMetadata("processor hash binding mismatch")
+ }
+ let processorFD: Int32
+ do { processorFD = try directory.openFile(processorPath) }
+ catch { throw VisionPackError.invalidMetadata("\(error)") }
+ defer { close(processorFD) }
+ do {
+ try Sha256Verifier.verifyFile(
+ fileDescriptor: processorFD,
+ named: processorPath,
+ expectedHex: processorEntry.sha256)
+ } catch {
+ throw VisionPackError.invalidMetadata(
+ "\(processorPath) does not match its manifest hash")
+ }
+
+ let weightsFD: Int32
+ do { weightsFD = try directory.openFile(GTurboVisionFormatV1.weightsFile) }
+ catch { throw VisionPackError.invalidMetadata("\(error)") }
+ return VisionWeightStore(directoryURL: directoryURL.standardizedFileURL,
+ directory: directory, manifest: manifest,
+ weightsFD: weightsFD)
+ }
+
+ private init(directoryURL: URL, directory: GTurboModelDirectory,
+ manifest: GTurboVisionManifestV1, weightsFD: Int32) {
+ self.directoryURL = directoryURL
+ self.directory = directory
+ self.manifest = manifest
+ self.weightsFD = weightsFD
+ }
+
+ deinit { close(weightsFD) }
+
+ func mapRegion(executionPosition: Int,
+ device: MTLDevice) throws -> ResidentBuffer {
+ guard manifest.tensors.indices.contains(executionPosition) else {
+ throw VisionPackError.invalidMetadata(
+ "missing execution position \(executionPosition)")
+ }
+ let region = manifest.tensors[executionPosition]
+ guard region.size <= UInt64(device.maxBufferLength) else {
+ throw VisionPackError.regionExceedsDevice(
+ name: region.name, bytes: region.size,
+ maximum: UInt64(device.maxBufferLength))
+ }
+ return try ResidentBuffer(
+ fileURL: directoryURL.appendingPathComponent(region.file),
+ fileOffset: region.offset, residentSize: region.size,
+ device: device, fileDescriptor: weightsFD)
+ }
+
+ func mapRegion(tensorNames: [String],
+ device: MTLDevice) throws -> VisionMappedWeightRegion {
+ let byName = Dictionary(uniqueKeysWithValues: manifest.tensors.map { ($0.name, $0) })
+ let tensors = try tensorNames.map { name -> GTurboVisionTensorRegionV1 in
+ guard let tensor = byName[name] else {
+ throw VisionPackError.invalidMetadata("missing tensor \(name)")
+ }
+ return tensor
+ }
+ guard let start = tensors.map(\.offset).min(),
+ let end = tensors.map({ $0.offset + $0.size }).max(),
+ end > start else {
+ throw VisionPackError.invalidMetadata("empty mapped tensor group")
+ }
+ let length = end - start
+ guard length <= UInt64(device.maxBufferLength) else {
+ throw VisionPackError.regionExceedsDevice(
+ name: tensorNames.first ?? "group", bytes: length,
+ maximum: UInt64(device.maxBufferLength))
+ }
+ let resident = try ResidentBuffer(
+ fileURL: directoryURL.appendingPathComponent(GTurboVisionFormatV1.weightsFile),
+ fileOffset: start, residentSize: length,
+ device: device, fileDescriptor: weightsFD)
+ let offsets = Dictionary(uniqueKeysWithValues: tensors.map {
+ ($0.name, Int($0.offset - start))
+ })
+ return VisionMappedWeightRegion(resident: resident,
+ tensors: tensors,
+ offsets: offsets)
+ }
+
+ func tensorNames(withPrefix prefix: String) -> [String] {
+ manifest.tensors.lazy.filter { $0.name.hasPrefix(prefix) }.map(\.name)
+ }
+}
+
+private func canonicalVisionDirectoryPath(_ url: URL) -> String {
+ let standardized = url.standardizedFileURL
+ return standardized.deletingLastPathComponent()
+ .resolvingSymlinksInPath()
+ .appendingPathComponent(standardized.lastPathComponent, isDirectory: true)
+ .standardizedFileURL.path
+}
+
+struct VisionMappedWeightRegion {
+ let resident: ResidentBuffer
+ let tensors: [GTurboVisionTensorRegionV1]
+ let offsets: [String: Int]
+
+ var buffer: MTLBuffer { resident.buffer }
+
+ func offset(of name: String) throws -> Int {
+ guard let value = offsets[name] else {
+ throw VisionPackError.invalidMetadata("tensor \(name) is outside mapped region")
+ }
+ return value
+ }
+}
diff --git a/Sources/TurboFieldfare/Tokenization/Tokenizer.swift b/Sources/TurboFieldfare/Tokenization/Tokenizer.swift
index e0f51272..5d687db9 100644
--- a/Sources/TurboFieldfare/Tokenization/Tokenizer.swift
+++ b/Sources/TurboFieldfare/Tokenization/Tokenizer.swift
@@ -9,6 +9,7 @@ public enum GFTokenizerError: Error, CustomStringConvertible {
case missingTokenizerConfig
case unsupportedDecoder(actual: String)
case invalidTokenID(token: String, id: Int)
+ case specialTokenMismatch(token: String, expected: Int32, resolved: Int32)
public var description: String {
switch self {
@@ -23,6 +24,9 @@ public enum GFTokenizerError: Error, CustomStringConvertible {
+ "Sequence[Replace(▁→␣), ByteFallback, Fuse]; found: \(actual)"
case .invalidTokenID(let token, let id):
return "tokenizer declares out-of-range ID \(id) for token \(token)"
+ case .specialTokenMismatch(let token, let expected, let resolved):
+ return "tokenizer resolves \(token) to \(resolved), but the runtime "
+ + "expects \(expected); the tokenizer does not match this build"
}
}
}
@@ -215,6 +219,23 @@ public struct GFTokenizer: @unchecked Sendable {
self.toolResponseEndID = try Self.requireTokenID(tokenizer, "<tool_response|>")
self.channelStartID = try Self.requireTokenID(tokenizer, "<|channel>")
self.channelEndID = try Self.requireTokenID(tokenizer, "<channel|>")
+ // The image markers are compile-time constants on the renderer because
+ // prompt layout code references them without a tokenizer in hand, but
+ // they must still describe THIS vocabulary: a tokenizer revision that
+ // renumbers them would otherwise corrupt every image prompt silently.
+ // Resolve and compare here so a mismatched tokenizer fails at load,
+ // exactly like every other special token.
+ for (token, expected) in [
+ ("<|image>", MultimodalPromptRenderer.beginImageTokenID),
+ ("<|image|>", MultimodalPromptRenderer.imageTokenID),
+ ("<image|>", MultimodalPromptRenderer.endImageTokenID),
+ ] {
+ let resolved = try Self.requireTokenID(tokenizer, token)
+ guard resolved == expected else {
+ throw GFTokenizerError.specialTokenMismatch(
+ token: token, expected: expected, resolved: resolved)
+ }
+ }
self.stopTokenIDs = [self.eosID, self.endOfTurnID, self.toolResponseID]
self.vocabSize = 262_144
}
@@ -381,6 +402,99 @@ public struct GFTokenizer: @unchecked Sendable {
addBOS: false)
}
+ /// A user turn carrying images, encoded as a continuation onto an existing
+ /// KV prefix. Mirrors `encodeTextContinuation` exactly and then expands each
+ /// image marker the way `MultimodalPromptRenderer` does, so the result is
+ /// the same tokens a full render of that turn would produce. Token counts
+ /// come from image geometry, so no image has to be encoded to build this.
+ /// `openingConversation` builds the turn as the *first* turn of a
+ /// conversation instead of a continuation: the chat template's opening,
+ /// including `<bos>`, rather than a continuation's leading end-of-turn.
+ /// Without it a fresh conversation's first image turn started with a
+ /// dangling end-of-turn and no BOS, which this model is sensitive to.
+ public func encodeMultimodalUserContinuation(
+ textAndImages: [MultimodalContinuationPart],
+ imageTokenCounts: [Int],
+ openingConversation: Bool = false
+ ) throws -> MultimodalContinuationTokens {
+ var text = ""
+ var expected = 0
+ for part in textAndImages {
+ switch part {
+ case .text(let value):
+ guard !value.contains(MultimodalPromptRenderer.placeholder) else {
+ throw MultimodalPromptRendererError.reservedImageMarker
+ }
+ text += value
+ case .image:
+ text += MultimodalPromptRenderer.placeholder
+ expected += 1
+ }
+ }
+ guard expected == imageTokenCounts.count, expected > 0 else {
+ throw MultimodalPromptRendererError.placeholderMismatch
+ }
+ guard text.components(
+ separatedBy: MultimodalPromptRenderer.placeholder).count - 1 == expected else {
+ throw MultimodalPromptRendererError.reservedImageMarker
+ }
+ let content = text.trimmingCharacters(in: .whitespacesAndNewlines)
+ let template: [Int32]
+ if openingConversation {
+ // The same rendering the text path uses for an empty KV, so the
+ // first turn of a conversation is identical whether or not it
+ // carries an image.
+ template = encode(
+ try applyChatTemplate([Message(role: .user, content: content)]),
+ addBOS: false)
+ } else {
+ template = [endOfTurnID] + encode(
+ "\n\(Self.turnOpen)user\n\(content)\(Self.turnClose)\n"
+ + "\(Self.turnOpen)model\n<|channel>thought\n<channel|>",
+ addBOS: false)
+ }
+ // Count the placeholders the tokenizer actually produced before indexing
+ // anything by them. The per-part marker check above cannot see a marker
+ // split across two text parts, which concatenation would reassemble into
+ // a real image token and leave more placeholders than counts.
+ let placeholders = template.reduce(into: 0) {
+ if $1 == MultimodalPromptRenderer.imageTokenID { $0 += 1 }
+ }
+ guard placeholders == imageTokenCounts.count else {
+ throw MultimodalPromptRendererError.placeholderMismatch
+ }
+
+ var effective: [Int32] = []
+ var embedding: [Int32] = []
+ var ranges: [Range<Int>] = []
+ var index = 0
+ for token in template {
+ guard token == MultimodalPromptRenderer.imageTokenID else {
+ effective.append(token)
+ embedding.append(token)
+ continue
+ }
+ let count = imageTokenCounts[index]
+ effective.append(MultimodalPromptRenderer.beginImageTokenID)
+ embedding.append(MultimodalPromptRenderer.beginImageTokenID)
+ let lower = effective.count
+ effective.append(contentsOf: repeatElement(
+ MultimodalPromptRenderer.imageTokenID, count: count))
+ embedding.append(contentsOf: repeatElement(Int32(0), count: count))
+ ranges.append(lower..<effective.count)
+ effective.append(MultimodalPromptRenderer.endImageTokenID)
+ embedding.append(MultimodalPromptRenderer.endImageTokenID)
+ index += 1
+ }
+ guard index == imageTokenCounts.count else {
+ throw MultimodalPromptRendererError.placeholderMismatch
+ }
+ return MultimodalContinuationTokens(
+ effectiveTokenIDs: effective,
+ embeddingTokenIDs: embedding,
+ imageTokenRanges: ranges)
+ }
+
public func encodeToolResultContinuation(
cachedMessages: [Message],
assistant: Message,
diff --git a/Sources/TurboFieldfareApp/Core/Configuration/AppContextLengthOption.swift b/Sources/TurboFieldfareApp/Core/Configuration/AppContextLengthOption.swift
index f5afb237..f558f05e 100644
--- a/Sources/TurboFieldfareApp/Core/Configuration/AppContextLengthOption.swift
+++ b/Sources/TurboFieldfareApp/Core/Configuration/AppContextLengthOption.swift
@@ -22,9 +22,15 @@ public enum AppContextLengthOption: Int, CaseIterable, Identifiable, Sendable {
let slidingLayers = architecture.numLayers - fullLayers
let fp16Bytes = 2
let keyAndValue = 2
+ // The ring the runtime actually allocates: the window plus the widest
+ // prefill chunk it may see, which is the pooled image-token count, not
+ // the default text chunk. Using the smaller number understates every
+ // estimate by about 29.69 MiB.
let slidingRows = min(
tokens,
- architecture.slidingWindow + PrefillRuntimeConfig.defaultChunked.chunkTokens)
+ architecture.slidingWindow + max(
+ PrefillRuntimeConfig.defaultChunked.chunkTokens,
+ VisionConfig().maximumPooledTokens))
let slidingBytesPerRow = architecture.numKVHeads
* architecture.headDim * keyAndValue * fp16Bytes
let fullBytesPerRow = architecture.numFullKVHeads
@@ -35,11 +41,14 @@ public enum AppContextLengthOption: Int, CaseIterable, Identifiable, Sendable {
public var menuLabel: String {
switch self {
- case .fourK: "4K, Default"
- case .eightK: "8K, +85 MB"
- case .sixteenK: "16K, +250 MB"
- case .thirtyTwoK: "32K, +590 MB"
- case .sixtyFourK: "64K, +1.26 GB"
+ // Measured against the 8K default, not against 4K: moving the default
+ // without moving the baseline would have left every delta describing a
+ // size the user is no longer starting from.
+ case .fourK: "4K, -85 MB"
+ case .eightK: "8K, Default"
+ case .sixteenK: "16K, +170 MB"
+ case .thirtyTwoK: "32K, +500 MB"
+ case .sixtyFourK: "64K, +1.17 GB"
}
}
}
diff --git a/Sources/TurboFieldfareApp/Core/Configuration/AppRuntimeOptions.swift b/Sources/TurboFieldfareApp/Core/Configuration/AppRuntimeOptions.swift
index 5ff8e177..c713a4e2 100644
--- a/Sources/TurboFieldfareApp/Core/Configuration/AppRuntimeOptions.swift
+++ b/Sources/TurboFieldfareApp/Core/Configuration/AppRuntimeOptions.swift
@@ -9,7 +9,7 @@ public enum AppExpertCachePolicy: String, CaseIterable, Sendable, Identifiable {
public var label: String { rawValue.uppercased() }
}
-public enum AppRDAdvicePolicy: String, CaseIterable, Sendable, Identifiable {
+public enum AppRDAdvicePolicy: String, Codable, CaseIterable, Sendable, Identifiable {
case off
case `default`
case bounded
@@ -59,19 +59,22 @@ public struct AppRuntimeOptions: Equatable, Sendable {
public var prefillChunkTokens: Int
public var rdadvisePolicy: AppRDAdvicePolicy
public var modelVerification: AppModelVerification
+ public var visionResidencyPolicy: VisionResidencyPolicy
public init(expertCacheSlots: Int = 16,
expertCachePolicy: AppExpertCachePolicy = .lfu,
prefillEnabled: Bool = true,
prefillChunkTokens: Int = 128,
rdadvisePolicy: AppRDAdvicePolicy = .off,
- modelVerification: AppModelVerification = .fullSha256) {
+ modelVerification: AppModelVerification = .fullSha256,
+ visionResidencyPolicy: VisionResidencyPolicy = .onDemand) {
self.expertCacheSlots = expertCacheSlots
self.expertCachePolicy = expertCachePolicy
self.prefillEnabled = prefillEnabled
self.prefillChunkTokens = prefillChunkTokens
self.rdadvisePolicy = rdadvisePolicy
self.modelVerification = modelVerification
+ self.visionResidencyPolicy = visionResidencyPolicy
}
public func validate() throws {
@@ -83,6 +86,15 @@ public struct AppRuntimeOptions: Equatable, Sendable {
throw AppInferenceError.invalidRequest(
"prefill chunk size must be one of \(Self.allowedPrefillChunkTokens)")
}
+ // Refused here rather than inside the first prefill chunk, which is
+ // after the model load and, on an image turn, after every attachment
+ // has already been encoded on the GPU.
+ let minimumSlots = RuntimeConfiguration.minimumExpertCacheSlotsForChunkedPrefill
+ guard !prefillEnabled || expertCacheSlots >= minimumSlots else {
+ throw AppInferenceError.invalidRequest(
+ "Prefill needs at least \(minimumSlots) expert cache slots, and Slots is set to "
+ + "\(expertCacheSlots). Raise Slots to \(minimumSlots) or turn Prefill off.")
+ }
}
public var prefillConfig: PrefillRuntimeConfig {
@@ -124,6 +136,7 @@ public struct AppLoadedRuntimeKey: Equatable, Sendable {
public var expertCachePolicy: AppExpertCachePolicy
public var rdadvisePolicy: AppRDAdvicePolicy
public var modelVerification: AppModelVerification
+ public var visionResidencyPolicy: VisionResidencyPolicy
public var forceLogitsHead: Bool
public init(modelDirectory: URL,
@@ -136,6 +149,26 @@ public struct AppLoadedRuntimeKey: Equatable, Sendable {
self.expertCachePolicy = options.expertCachePolicy
self.rdadvisePolicy = options.rdadvisePolicy
self.modelVerification = options.modelVerification
+ self.visionResidencyPolicy = options.visionResidencyPolicy
self.forceLogitsHead = forceLogitsHead
}
+
+ /// The options this session was actually loaded with. A run has to be built
+ /// from these rather than from the current settings, or a pending change the
+ /// user has not reloaded for is refused by the loaded session.
+ ///
+ /// Prefill is passed in because it is deliberately not part of this key:
+ /// it is chosen per request and changing it must not make a loaded
+ /// session stale.
+ public func options(prefillEnabled: Bool,
+ prefillChunkTokens: Int) -> AppRuntimeOptions {
+ AppRuntimeOptions(
+ expertCacheSlots: expertCacheSlots,
+ expertCachePolicy: expertCachePolicy,
+ prefillEnabled: prefillEnabled,
+ prefillChunkTokens: prefillChunkTokens,
+ rdadvisePolicy: rdadvisePolicy,
+ modelVerification: modelVerification,
+ visionResidencyPolicy: visionResidencyPolicy)
+ }
}
diff --git a/Sources/TurboFieldfareApp/Core/Configuration/MacAppSettings.swift b/Sources/TurboFieldfareApp/Core/Configuration/MacAppSettings.swift
index 8122a1a7..dfeefaca 100644
--- a/Sources/TurboFieldfareApp/Core/Configuration/MacAppSettings.swift
+++ b/Sources/TurboFieldfareApp/Core/Configuration/MacAppSettings.swift
@@ -1,11 +1,12 @@
import Foundation
+import TurboFieldfare
struct MacAppSettings: Codable, Equatable, Sendable {
static let fileName = "mac-app-settings.json"
- static let currentVersion = 1
+ static let currentVersion = 2
var version: Int = currentVersion
- var contextTokens: Int = AppContextLengthOption.fourK.tokens
+ var contextTokens: Int = AppContextLengthOption.eightK.tokens
var expertCacheSlots: Int = 16
var temperature: Double = 0.2
var topKEnabled: Bool = true
@@ -16,6 +17,9 @@ struct MacAppSettings: Codable, Equatable, Sendable {
var newlineShortcut: AppNewlineShortcut = .return
var showPromptExamples: Bool = true
var sentPromptBehavior: AppSentPromptBehavior = .keep
+ var visionResidencyPolicy: VisionResidencyPolicy = .onDemand
+ var rdadvisePolicy: AppRDAdvicePolicy = .off
+ var loadModelOnLaunch: Bool = false
private enum CodingKeys: String, CodingKey {
case version
@@ -30,10 +34,13 @@ struct MacAppSettings: Codable, Equatable, Sendable {
case newlineShortcut
case showPromptExamples
case sentPromptBehavior
+ case visionResidencyPolicy
+ case rdadvisePolicy
+ case loadModelOnLaunch
}
init(version: Int = currentVersion,
- contextTokens: Int = AppContextLengthOption.fourK.tokens,
+ contextTokens: Int = AppContextLengthOption.eightK.tokens,
expertCacheSlots: Int = 16,
temperature: Double = 0.2,
topKEnabled: Bool = true,
@@ -43,7 +50,10 @@ struct MacAppSettings: Codable, Equatable, Sendable {
prefillEnabled: Bool = true,
newlineShortcut: AppNewlineShortcut = .return,
showPromptExamples: Bool = true,
- sentPromptBehavior: AppSentPromptBehavior = .keep) {
+ sentPromptBehavior: AppSentPromptBehavior = .keep,
+ visionResidencyPolicy: VisionResidencyPolicy = .onDemand,
+ rdadvisePolicy: AppRDAdvicePolicy = .off,
+ loadModelOnLaunch: Bool = false) {
self.version = version
self.contextTokens = contextTokens
self.expertCacheSlots = expertCacheSlots
@@ -56,6 +66,9 @@ struct MacAppSettings: Codable, Equatable, Sendable {
self.newlineShortcut = newlineShortcut
self.showPromptExamples = showPromptExamples
self.sentPromptBehavior = sentPromptBehavior
+ self.visionResidencyPolicy = visionResidencyPolicy
+ self.rdadvisePolicy = rdadvisePolicy
+ self.loadModelOnLaunch = loadModelOnLaunch
}
init(from decoder: Decoder) throws {
@@ -78,11 +91,19 @@ struct MacAppSettings: Codable, Equatable, Sendable {
sentPromptBehavior = try container.decodeIfPresent(
AppSentPromptBehavior.self,
forKey: .sentPromptBehavior) ?? .keep
+ visionResidencyPolicy = try container.decodeIfPresent(
+ VisionResidencyPolicy.self,
+ forKey: .visionResidencyPolicy) ?? .onDemand
+ rdadvisePolicy = try container.decodeIfPresent(
+ AppRDAdvicePolicy.self,
+ forKey: .rdadvisePolicy) ?? .off
+ loadModelOnLaunch = try container.decodeIfPresent(
+ Bool.self,
+ forKey: .loadModelOnLaunch) ?? false
}
func isValid() -> Bool {
- version == Self.currentVersion
- && AppContextLengthOption.allCases.contains { $0.tokens == contextTokens }
+ AppContextLengthOption.allCases.contains { $0.tokens == contextTokens }
&& AppRuntimeOptions.allowedSlotCounts.contains(expertCacheSlots)
&& temperature.isFinite && (0...2).contains(temperature)
&& (1...256).contains(topK)
@@ -90,6 +111,12 @@ struct MacAppSettings: Codable, Equatable, Sendable {
}
}
+/// Just enough of the file to route on, so a newer build's schema cannot throw
+/// before its version has been read.
+private struct VersionStamp: Decodable {
+ let version: Int
+}
+
enum MacAppSettingsFileStore {
static func fileURL(forModelDirectory modelDirectory: URL) -> URL {
modelDirectory.standardizedFileURL
@@ -103,8 +130,32 @@ enum MacAppSettingsFileStore {
if fileManager.fileExists(atPath: fileURL.path) {
do {
let data = try Data(contentsOf: fileURL)
- let settings = try JSONDecoder().decode(MacAppSettings.self, from: data)
+ // The version is read on its own, before the full decode, because
+ // nine keys decode with a hard `decode` and a newer build is
+ // entitled to have moved any of them. Decoding first threw on
+ // exactly the files this branch exists to protect, and the throw
+ // reached the `catch` below, which deletes the file - so an older
+ // build silently replaced a newer one's settings with its own
+ // defaults. A version gate that cannot survive a schema change
+ // gates nothing.
+ let stamp = try JSONDecoder().decode(VersionStamp.self, from: data)
+ // This build does not know what a later version means, so it runs
+ // on defaults and leaves the file exactly as its owner wrote it.
+ guard stamp.version <= MacAppSettings.currentVersion else {
+ return MacAppSettings()
+ }
+ var settings = try JSONDecoder().decode(MacAppSettings.self, from: data)
+ let needsMigration = settings.version < MacAppSettings.currentVersion
+ if needsMigration {
+ // Version only: every existing value is still a deliberate
+ // choice, and rewriting one here would silently discard it.
+ settings.version = MacAppSettings.currentVersion
+ }
guard settings.isValid() else { throw InvalidSettings() }
+ if needsMigration {
+ try? save(settings, forModelDirectory: modelDirectory,
+ fileManager: fileManager)
+ }
return settings
} catch {
try? fileManager.removeItem(at: fileURL)
diff --git a/Sources/TurboFieldfareApp/Core/Diagnostics/AppDiagnostics.swift b/Sources/TurboFieldfareApp/Core/Diagnostics/AppDiagnostics.swift
index 46ba35a3..4c615cf2 100644
--- a/Sources/TurboFieldfareApp/Core/Diagnostics/AppDiagnostics.swift
+++ b/Sources/TurboFieldfareApp/Core/Diagnostics/AppDiagnostics.swift
@@ -52,6 +52,7 @@ public struct AppDiagnostics: Equatable, Sendable {
public var decodeSeconds: Double
public var tokensPerSecond: Double
public var peakMemoryBytes: UInt64?
+ public var visionTowerMappedBytes: UInt64?
public var runtimeOptions: AppRuntimeOptions
public var prefill: PrefillExecutionDiagnostics?
public var runner: AppRunnerDiagnostics?
@@ -81,6 +82,7 @@ public struct AppDiagnostics: Equatable, Sendable {
decodeSeconds: Double,
tokensPerSecond: Double,
peakMemoryBytes: UInt64?,
+ visionTowerMappedBytes: UInt64? = nil,
runtimeOptions: AppRuntimeOptions,
prefill: PrefillExecutionDiagnostics? = nil,
runner: AppRunnerDiagnostics? = nil) {
@@ -92,6 +94,7 @@ public struct AppDiagnostics: Equatable, Sendable {
self.decodeSeconds = decodeSeconds
self.tokensPerSecond = tokensPerSecond
self.peakMemoryBytes = peakMemoryBytes
+ self.visionTowerMappedBytes = visionTowerMappedBytes
self.runtimeOptions = runtimeOptions
self.prefill = prefill
self.runner = runner
@@ -106,6 +109,7 @@ public struct AppTokenEvent: Equatable, Sendable {
public enum AppInferenceEvent: Equatable, Sendable {
case prefillProgress(done: Int, total: Int)
+ case memorySample
case token(AppTokenEvent)
case finished(AppDiagnostics)
case cancelled(AppDiagnostics)
diff --git a/Sources/TurboFieldfareApp/Core/Diagnostics/AppMemorySampler.swift b/Sources/TurboFieldfareApp/Core/Diagnostics/AppMemorySampler.swift
index 26230ea1..13b8eada 100644
--- a/Sources/TurboFieldfareApp/Core/Diagnostics/AppMemorySampler.swift
+++ b/Sources/TurboFieldfareApp/Core/Diagnostics/AppMemorySampler.swift
@@ -5,6 +5,8 @@ import Foundation
public final class AppMemorySampler: @unchecked Sendable {
private let lock = NSLock()
private var peak: UInt64 = 0
+ private var residentPeak: UInt64 = 0
+ private var occupiedPeak: UInt64 = 0
private let processFootprint: @Sendable () -> UInt64?
public init() {
@@ -18,6 +20,8 @@ public final class AppMemorySampler: @unchecked Sendable {
public func resetPeak() {
lock.lock()
peak = 0
+ residentPeak = 0
+ occupiedPeak = 0
lock.unlock()
}
@@ -29,6 +33,86 @@ public final class AppMemorySampler: @unchecked Sendable {
return current
}
+ /// Bytes this process has resident, including the file-backed pages of the
+ /// mapped weights. `phys_footprint` deliberately excludes those — they are
+ /// clean and the kernel can drop them — which is why a freshly loaded 26B
+ /// model reports about 160 MB. That is true and also the opposite of what
+ /// someone reads it as, so both numbers are reported.
+ public func residentSample() -> UInt64? {
+ guard let current = Self.readResidentSize() else { return nil }
+ lock.lock()
+ if current > residentPeak { residentPeak = current }
+ lock.unlock()
+ return current
+ }
+
+ /// Peak resident bytes since the last reset. Tracked separately from the
+ /// footprint peak because the two measure different things and showing one
+ /// beside the other's current value invites a false comparison.
+ public var peakResidentBytes: UInt64? {
+ lock.lock()
+ let value = residentPeak
+ lock.unlock()
+ return value == 0 ? nil : value
+ }
+
+ /// What the process is actually occupying: the bytes charged to it plus the
+ /// file-backed pages it has resident.
+ ///
+ /// Neither half alone answers the question. `phys_footprint` counts
+ /// anonymous, wired and compressed memory but excludes clean mapped pages,
+ /// so it cannot see the weights. `resident_size` counts mapped pages but
+ /// also re-counts the anonymous ones already in the footprint. Adding the
+ /// footprint to the *external* (file-backed) resident bytes counts each
+ /// page once: about 2 GB of runtime plus about 1 GB of image tower reads as
+ /// about 3 GB, which is what is really in RAM.
+ public func occupiedSample() -> UInt64? {
+ guard let info = Self.readVMInfo() else { return nil }
+ let total = UInt64(info.phys_footprint) + UInt64(info.external)
+ lock.lock()
+ if total > occupiedPeak { occupiedPeak = total }
+ lock.unlock()
+ return total
+ }
+
+ /// File-backed resident bytes on their own: the mapped weights and image
+ /// tower, which is the part the footprint can never show.
+ public func mappedResidentSample() -> UInt64? {
+ Self.readVMInfo().map { UInt64($0.external) }
+ }
+
+ public var peakOccupiedBytes: UInt64? {
+ lock.lock()
+ let value = occupiedPeak
+ lock.unlock()
+ return value == 0 ? nil : value
+ }
+
+ private static func readVMInfo() -> task_vm_info_data_t? {
+ var info = task_vm_info_data_t()
+ var count = mach_msg_type_number_t(
+ MemoryLayout<task_vm_info_data_t>.size / MemoryLayout<integer_t>.size)
+ let kr = withUnsafeMutablePointer(to: &info) {
+ $0.withMemoryRebound(to: integer_t.self, capacity: Int(count)) {
+ task_info(mach_task_self_, task_flavor_t(TASK_VM_INFO), $0, &count)
+ }
+ }
+ return kr == KERN_SUCCESS ? info : nil
+ }
+
+ private static func readResidentSize() -> UInt64? {
+ var info = task_vm_info_data_t()
+ var count = mach_msg_type_number_t(
+ MemoryLayout<task_vm_info_data_t>.size / MemoryLayout<integer_t>.size)
+ let kr = withUnsafeMutablePointer(to: &info) {
+ $0.withMemoryRebound(to: integer_t.self, capacity: Int(count)) {
+ task_info(mach_task_self_, task_flavor_t(TASK_VM_INFO), $0, &count)
+ }
+ }
+ guard kr == KERN_SUCCESS else { return nil }
+ return UInt64(info.resident_size)
+ }
+
private static func readProcessFootprint() -> UInt64? {
var info = task_vm_info_data_t()
var count = mach_msg_type_number_t(MemoryLayout<task_vm_info_data_t>.size / MemoryLayout<integer_t>.size)
diff --git a/Sources/TurboFieldfareApp/Core/Inference/AppGenerationRequest.swift b/Sources/TurboFieldfareApp/Core/Inference/AppGenerationRequest.swift
index 28f833ca..a10e4651 100644
--- a/Sources/TurboFieldfareApp/Core/Inference/AppGenerationRequest.swift
+++ b/Sources/TurboFieldfareApp/Core/Inference/AppGenerationRequest.swift
@@ -1,8 +1,10 @@
import Foundation
+import TurboFieldfare
public struct AppGenerationRequest: Equatable, Sendable {
public var modelDirectory: URL
public var prompt: String
+ public var imageAttachments: [AppImageAttachment]
public var maxNewTokens: Int
public var maxContextTokens: Int
public var temperature: Float
@@ -13,6 +15,7 @@ public struct AppGenerationRequest: Equatable, Sendable {
public init(modelDirectory: URL,
prompt: String,
+ imageAttachments: [AppImageAttachment] = [],
maxNewTokens: Int = 4_096,
maxContextTokens: Int = 4096,
temperature: Float = 0.2,
@@ -22,6 +25,7 @@ public struct AppGenerationRequest: Equatable, Sendable {
runtimeOptions: AppRuntimeOptions = AppRuntimeOptions()) {
self.modelDirectory = modelDirectory
self.prompt = prompt
+ self.imageAttachments = imageAttachments
self.maxNewTokens = maxNewTokens
self.maxContextTokens = maxContextTokens
self.temperature = temperature
@@ -37,8 +41,34 @@ public struct AppGenerationRequest: Equatable, Sendable {
public func validate(fileManager: FileManager = .default,
requireModelDirectory: Bool = true) throws {
- guard !prompt.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
- throw AppInferenceError.invalidRequest("Prompt cannot be empty.")
+ guard !prompt.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
+ || !imageAttachments.isEmpty else {
+ throw AppInferenceError.invalidRequest("Prompt or image cannot be empty.")
+ }
+ // The same context-derived rule the server uses. A fixed four here
+ // meant a request the API accepted was refused in the app.
+ guard Set(imageAttachments.map(\.id)).count == imageAttachments.count else {
+ throw AppInferenceError.invalidRequest("Images must be distinct.")
+ }
+ let capacity = VisionImageTokenBudget.capacity(
+ maxContext: maxContextTokens, reservedTextTokens: 0)
+ guard imageAttachments.count <= capacity else {
+ throw AppInferenceError.invalidRequest(
+ "\(imageAttachments.count) images need up to "
+ + "\(imageAttachments.count * VisionImageTokenBudget.maximumTokensPerImage) "
+ + "tokens, beyond the \(maxContextTokens)-token context.")
+ }
+ for attachment in imageAttachments {
+ guard attachment.fileURL.isFileURL,
+ attachment.encodedBytes >= 0,
+ attachment.encodedBytes <= VisionImageLimits().maximumEncodedBytes,
+ attachment.sha256.count == 64,
+ attachment.sha256.unicodeScalars.allSatisfy({
+ (48...57).contains($0.value) || (97...102).contains($0.value)
+ }) else {
+ throw AppInferenceError.invalidRequest(
+ "Invalid image attachment \(attachment.displayName).")
+ }
}
guard maxNewTokens > 0 else {
throw AppInferenceError.invalidRequest("Max response length must be greater than zero.")
diff --git a/Sources/TurboFieldfareApp/Core/Inference/AppImageAttachment.swift b/Sources/TurboFieldfareApp/Core/Inference/AppImageAttachment.swift
new file mode 100644
index 00000000..0296ff39
--- /dev/null
+++ b/Sources/TurboFieldfareApp/Core/Inference/AppImageAttachment.swift
@@ -0,0 +1,298 @@
+import Darwin
+import Foundation
+import TurboFieldfare
+
+public struct AppImageAttachment: Sendable, Equatable {
+ public let id: UUID
+ public let fileURL: URL
+ public let displayName: String
+ public let encodedBytes: Int
+ public let sha256: String
+
+ public init(id: UUID = UUID(), fileURL: URL, displayName: String,
+ encodedBytes: Int, sha256: String) {
+ self.id = id
+ self.fileURL = fileURL
+ self.displayName = displayName
+ self.encodedBytes = encodedBytes
+ self.sha256 = sha256
+ }
+}
+
+public struct AppImageAttachmentStore: Sendable {
+ public static let rootName = "TurboFieldfare-Attachments"
+
+ public static var root: URL {
+ FileManager.default.temporaryDirectory
+ .appendingPathComponent(rootName, isDirectory: true)
+ }
+
+ /// Each run stages under its own `pid-<n>` directory so a run that was
+ /// killed can be told apart from one that is still going. Without that,
+ /// every session left up to four full-size image copies behind forever.
+ public static func defaultDirectory() -> URL {
+ root.appendingPathComponent("pid-\(getpid())", isDirectory: true)
+ .appendingPathComponent(UUID().uuidString, isDirectory: true)
+ }
+
+ /// Deletes the staging directories of processes that are gone. A live
+ /// peer — a second copy of the app — keeps its own.
+ @discardableResult
+ public static func sweepAbandoned(in root: URL = AppImageAttachmentStore.root)
+ -> [String] {
+ guard let entries = try? FileManager.default.contentsOfDirectory(
+ at: root, includingPropertiesForKeys: nil) else { return [] }
+ var reclaimed: [String] = []
+ for entry in entries {
+ let name = entry.lastPathComponent
+ if name.hasPrefix("pid-"), let pid = pid_t(name.dropFirst(4)), pid > 0,
+ kill(pid, 0) == 0 || errno == EPERM {
+ continue
+ }
+ guard (try? FileManager.default.removeItem(at: entry)) != nil else { continue }
+ reclaimed.append(name)
+ }
+ return reclaimed
+ }
+
+ /// Whether a path names a file this app staged.
+ ///
+ /// The decode service receives attachment paths over a socket and opens
+ /// them, so it needs a rule that does not depend on which process staged
+ /// the file: the app and the service are separate processes with separate
+ /// stores, but both live under the same root. Symlinks are resolved first,
+ /// so a link planted inside the root cannot point out of it.
+ public static func contains(_ fileURL: URL) -> Bool {
+ guard fileURL.isFileURL else { return false }
+ let resolved = fileURL.standardizedFileURL.resolvingSymlinksInPath()
+ let fileComponents = resolved.pathComponents
+ return allowedRoots.contains { root in
+ let rootComponents = root.pathComponents
+ guard fileComponents.count > rootComponents.count else { return false }
+ return Array(fileComponents.prefix(rootComponents.count)) == rootComponents
+ }
+ }
+
+ /// The attachment roots this process will accept a path under.
+ ///
+ /// The app and the decode service are separate processes and resolve their
+ /// temporary directory independently, so the per-user Darwin temp
+ /// directory is included explicitly: a service launched without `TMPDIR`
+ /// must still recognise the app's staged files, and rejecting them all
+ /// would silently break every image.
+ private static var allowedRoots: [URL] {
+ var roots = [FileManager.default.temporaryDirectory]
+ if let userTemp = darwinUserTemporaryDirectory { roots.append(userTemp) }
+ return roots.map {
+ $0.appendingPathComponent(rootName, isDirectory: true)
+ .standardizedFileURL.resolvingSymlinksInPath()
+ }
+ }
+
+ private static var darwinUserTemporaryDirectory: URL? {
+ var buffer = [UInt8](repeating: 0, count: Int(PATH_MAX))
+ let length = buffer.withUnsafeMutableBytes {
+ confstr(_CS_DARWIN_USER_TEMP_DIR,
+ $0.baseAddress!.assumingMemoryBound(to: CChar.self), $0.count)
+ }
+ // confstr counts the terminating NUL.
+ guard length > 1, length <= buffer.count else { return nil }
+ let path = String(decoding: buffer[..<(length - 1)], as: UTF8.self)
+ return URL(fileURLWithPath: path, isDirectory: true)
+ }
+
+ public let directoryURL: URL
+
+ public init(directoryURL: URL = AppImageAttachmentStore.defaultDirectory()) {
+ self.directoryURL = directoryURL
+ }
+
+ /// A second reference to an already staged file, with an independent
+ /// lifetime.
+ ///
+ /// The transcript renders from the same files the composer holds, so
+ /// clearing or replacing the composer's attachments deleted the images a
+ /// finished answer was still showing. A hard link rather than a copy: the
+ /// files are sealed read-only and can be up to 64 MB each.
+ public func retain(_ attachment: AppImageAttachment) throws -> AppImageAttachment {
+ let directory = directoryURL.appendingPathComponent(
+ "retained", isDirectory: true)
+ try FileManager.default.createDirectory(
+ at: directory, withIntermediateDirectories: true)
+ let destination = directory.appendingPathComponent(UUID().uuidString)
+ guard link(attachment.fileURL.path, destination.path) == 0 else {
+ throw VisionImageError.invalidSource(
+ "could not retain \(attachment.displayName): errno \(errno)")
+ }
+ return AppImageAttachment(
+ id: attachment.id,
+ fileURL: destination,
+ displayName: attachment.displayName,
+ encodedBytes: attachment.encodedBytes,
+ sha256: attachment.sha256)
+ }
+
+ public func stage(_ sourceURL: URL) throws -> AppImageAttachment {
+ let accessed = sourceURL.startAccessingSecurityScopedResource()
+ defer { if accessed { sourceURL.stopAccessingSecurityScopedResource() } }
+
+ let source = sourceURL.standardizedFileURL
+ let sourceFD = source.path.withCString {
+ Darwin.open($0, O_RDONLY | O_NONBLOCK | O_CLOEXEC | O_NOFOLLOW)
+ }
+ guard sourceFD >= 0 else {
+ // The open is deliberately O_NOFOLLOW, so ELOOP here means the path
+ // was a symlink and was refused on purpose. Without errno that is
+ // indistinguishable from a missing file, a sandbox denial or a
+ // descriptor exhaustion, and none of them can be acted on.
+ throw VisionImageError.invalidSource(
+ "could not open \(source.lastPathComponent): errno \(errno)")
+ }
+ defer { Darwin.close(sourceFD) }
+ var sourceStatus = stat()
+ guard fstat(sourceFD, &sourceStatus) == 0 else {
+ throw VisionImageError.invalidSource(
+ "could not read \(source.lastPathComponent): errno \(errno)")
+ }
+ guard (sourceStatus.st_mode & S_IFMT) == S_IFREG,
+ sourceStatus.st_size >= 0,
+ let encodedBytes = Int(exactly: sourceStatus.st_size) else {
+ throw VisionImageError.invalidSource("a regular file is required")
+ }
+ let limit = VisionImageLimits().maximumEncodedBytes
+ guard encodedBytes <= limit else {
+ throw VisionImageError.sourceTooLarge(bytes: encodedBytes, limit: limit)
+ }
+
+ return try stage(
+ displayName: source.lastPathComponent,
+ encodedBytes: encodedBytes
+ ) { destinationFD in
+ var copied = 0
+ var buffer = [UInt8](repeating: 0, count: 256 * 1_024)
+ while copied < encodedBytes {
+ let readCount = buffer.withUnsafeMutableBytes {
+ Darwin.read(
+ sourceFD, $0.baseAddress!,
+ min($0.count, encodedBytes - copied))
+ }
+ if readCount < 0, errno == EINTR { continue }
+ // Only a zero-length read means the file shrank under us. A
+ // negative one is a read error — EIO, EACCES, a network volume
+ // going away — and saying the source changed sends the reader
+ // after the wrong thing.
+ if readCount < 0 {
+ throw VisionImageError.invalidSource(
+ "could not read \(source.lastPathComponent): errno \(errno)")
+ }
+ guard readCount > 0 else {
+ throw VisionImageError.invalidSource(
+ "source changed while copying")
+ }
+ try buffer.withUnsafeBytes {
+ try Self.writeAll(
+ UnsafeRawBufferPointer(
+ start: $0.baseAddress, count: readCount),
+ to: destinationFD)
+ }
+ copied += readCount
+ }
+ }
+ }
+
+ /// Stages bytes that never existed as a file — an image copied from another
+ /// app arrives on the pasteboard as data, with no URL to open.
+ public func stage(data: Data, displayName: String) throws -> AppImageAttachment {
+ let limit = VisionImageLimits().maximumEncodedBytes
+ guard !data.isEmpty else {
+ throw VisionImageError.invalidSource("the pasteboard image was empty")
+ }
+ guard data.count <= limit else {
+ throw VisionImageError.sourceTooLarge(bytes: data.count, limit: limit)
+ }
+ return try stage(displayName: displayName, encodedBytes: data.count) { fd in
+ try data.withUnsafeBytes { try Self.writeAll($0, to: fd) }
+ }
+ }
+
+ private func stage(
+ displayName: String,
+ encodedBytes: Int,
+ writeContents: (Int32) throws -> Void
+ ) throws -> AppImageAttachment {
+ try FileManager.default.createDirectory(
+ at: directoryURL, withIntermediateDirectories: true)
+ let id = UUID()
+ let destination = directoryURL.appendingPathComponent(id.uuidString)
+ let temporary = directoryURL.appendingPathComponent(".\(id.uuidString).partial")
+ let destinationFD = temporary.path.withCString {
+ Darwin.open($0, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, S_IRUSR | S_IWUSR)
+ }
+ guard destinationFD >= 0 else {
+ throw VisionImageError.invalidSource("could not create attachment storage")
+ }
+ var didClose = false
+ defer {
+ if !didClose { Darwin.close(destinationFD) }
+ try? FileManager.default.removeItem(at: temporary)
+ }
+ try writeContents(destinationFD)
+ guard Darwin.fsync(destinationFD) == 0 else {
+ throw VisionImageError.invalidSource("attachment sync failed")
+ }
+ // Before the guard, not after it: close() releases the descriptor even
+ // when it reports EINTR or EIO, so throwing first left the `defer`
+ // closing a number the kernel had already handed to something else —
+ // the decode-service socket or a mapped weight file, staged off the
+ // main actor while both are open.
+ didClose = true
+ guard Darwin.close(destinationFD) == 0 else {
+ throw VisionImageError.invalidSource("attachment close failed")
+ }
+ try FileManager.default.moveItem(at: temporary, to: destination)
+ guard chmod(destination.path, S_IRUSR) == 0 else {
+ try? FileManager.default.removeItem(at: destination)
+ throw VisionImageError.invalidSource("could not seal attachment")
+ }
+ let digest: String
+ do {
+ digest = try Sha256Verifier.hashFile(
+ at: destination, chunkBytes: 256 * 1_024)
+ } catch {
+ try? FileManager.default.removeItem(at: destination)
+ throw error
+ }
+ return AppImageAttachment(
+ id: id,
+ fileURL: destination,
+ displayName: displayName,
+ encodedBytes: encodedBytes,
+ sha256: digest)
+ }
+
+ private static func writeAll(
+ _ bytes: UnsafeRawBufferPointer,
+ to fileDescriptor: Int32
+ ) throws {
+ var written = 0
+ while written < bytes.count {
+ let count = Darwin.write(
+ fileDescriptor,
+ bytes.baseAddress!.advanced(by: written),
+ bytes.count - written)
+ if count < 0, errno == EINTR { continue }
+ guard count > 0 else {
+ throw VisionImageError.invalidSource("attachment copy failed")
+ }
+ written += count
+ }
+ }
+
+ public func remove(_ attachment: AppImageAttachment) {
+ try? FileManager.default.removeItem(at: attachment.fileURL)
+ }
+
+ public func removeAll() {
+ try? FileManager.default.removeItem(at: directoryURL)
+ }
+}
diff --git a/Sources/TurboFieldfareApp/Core/Inference/AppInferenceClient.swift b/Sources/TurboFieldfareApp/Core/Inference/AppInferenceClient.swift
index 5b1b856a..eb3bbb01 100644
--- a/Sources/TurboFieldfareApp/Core/Inference/AppInferenceClient.swift
+++ b/Sources/TurboFieldfareApp/Core/Inference/AppInferenceClient.swift
@@ -17,6 +17,18 @@ public protocol AppModelLifecycleClient: AnyObject, AppInferenceClient {
public protocol AppInferenceMemoryReporting: AnyObject {
var currentInferenceMemoryBytes: UInt64? { get }
+ /// Resident bytes, which include the mapped weights the footprint omits.
+ /// Defaulted so a reporter that cannot answer simply does not.
+ var currentInferenceResidentBytes: UInt64? { get }
+ /// Bytes of image tower the inference process holds mapped, or nil when it
+ /// has no vision runtime. The only figure that separates the two image
+ /// residency policies: both charge the process the same few MB.
+ var currentInferenceTowerBytes: UInt64? { get }
+}
+
+extension AppInferenceMemoryReporting {
+ public var currentInferenceResidentBytes: UInt64? { nil }
+ public var currentInferenceTowerBytes: UInt64? { nil }
}
public protocol AppInferenceTranscriptReporting: AnyObject {
diff --git a/Sources/TurboFieldfareApp/Core/Inference/DecodeServiceInferenceClient.swift b/Sources/TurboFieldfareApp/Core/Inference/DecodeServiceInferenceClient.swift
index 8e05fa23..bcc4bc0e 100644
--- a/Sources/TurboFieldfareApp/Core/Inference/DecodeServiceInferenceClient.swift
+++ b/Sources/TurboFieldfareApp/Core/Inference/DecodeServiceInferenceClient.swift
@@ -17,14 +17,20 @@ public final class DecodeServiceInferenceClient: AppModelLifecycleClient,
private let connection = Mutex(Connection())
private let serviceURL: URL
private let inferenceMemory = Mutex<UInt64?>(nil)
+ private let inferenceTowerMemory = Mutex<UInt64?>(nil)
public let generationTranscriptMailbox = GenerationTranscriptMailbox()
public var currentInferenceMemoryBytes: UInt64? {
inferenceMemory.withLock { $0 }
}
+ public var currentInferenceTowerBytes: UInt64? {
+ inferenceTowerMemory.withLock { $0 }
+ }
+
public init(serviceURL: URL? = nil) {
self.serviceURL = serviceURL ?? Self.defaultServiceURL()
+ DecodeUnixSocket.ignoreSIGPIPEProcessWide()
}
public func ensureLoaded(modelDirectory: URL, maxContextTokens: Int,
@@ -52,6 +58,7 @@ public final class DecodeServiceInferenceClient: AppModelLifecycleClient,
"decode service returned \(event.kind.rawValue) for a load request")
}
inferenceMemory.withLock { $0 = event.currentMemoryBytes }
+ inferenceTowerMemory.withLock { $0 = event.visionTowerMappedBytes }
connection.withLock { $0.loadedDirectory = modelDirectory.standardizedFileURL }
onState(.ready(modelDirectory: modelDirectory, loadSeconds: 0))
}
@@ -65,6 +72,7 @@ public final class DecodeServiceInferenceClient: AppModelLifecycleClient,
event.kind == .unloaded else { return }
connection.withLock { $0.loadedDirectory = nil }
inferenceMemory.withLock { $0 = nil }
+ inferenceTowerMemory.withLock { $0 = nil }
}
public func generate(_ request: AppGenerationRequest)
@@ -79,9 +87,20 @@ public final class DecodeServiceInferenceClient: AppModelLifecycleClient,
let generationID = UUID()
generationTranscriptMailbox.reset()
let command = DecodeGenerationRequest(
- prompt: request.prompt, maxNewTokens: request.maxNewTokens,
+ prompt: request.prompt,
+ imageAttachments: request.imageAttachments.map {
+ DecodeImageAttachment(
+ id: $0.id,
+ path: $0.fileURL.path,
+ displayName: $0.displayName,
+ encodedBytes: $0.encodedBytes,
+ sha256: $0.sha256)
+ },
+ maxNewTokens: request.maxNewTokens,
maxContextTokens: request.maxContextTokens,
temperature: request.temperature,
+ topK: request.topK,
+ topP: request.topP,
repetitionPenalty: request.repetitionPenalty,
runtimeOptions: Self.decodeRuntimeOptions(request.runtimeOptions),
generationID: generationID)
@@ -93,9 +112,23 @@ public final class DecodeServiceInferenceClient: AppModelLifecycleClient,
var hasYieldedVisibleText = false
while true {
let event = try await handles.responses.next(matching: generationID)
- inferenceMemory.withLock { $0 = event.currentMemoryBytes }
+ // Only when the event carries a figure: an event
+ // without one says nothing about memory, and clearing
+ // the last reading made the display flicker to empty.
+ if let bytes = event.currentMemoryBytes {
+ inferenceMemory.withLock { $0 = bytes }
+ }
+ if let tower = event.visionTowerMappedBytes {
+ inferenceTowerMemory.withLock { $0 = tower }
+ }
guard event.generationID == generationID else { continue }
+ if event.kind == .memory {
+ // The stored reading is not observed by the UI, so
+ // yield an event that causes it to redraw.
+ continuation.yield(.memorySample)
+ continue
+ }
if event.kind == .prefill || event.kind == .snapshot {
guard event.sequence == expectedSequence else {
throw AppInferenceError.unknown(
@@ -229,7 +262,10 @@ public final class DecodeServiceInferenceClient: AppModelLifecycleClient,
throw AppInferenceError.modelLoadFailed(message)
}
- // Demand the job without restarting a RunAtLoad winner; the socket is authoritative.
+ // Demand the job without restarting a RunAtLoad winner; the socket is
+ // authoritative. `bootstrap` alone does not always leave the job
+ // running, and the failure then looked like a socket timeout with no
+ // indication that launchd was the cause.
var kickstartError: String?
do {
let starter = Process()
@@ -275,10 +311,16 @@ public final class DecodeServiceInferenceClient: AppModelLifecycleClient,
kickstartError: kickstartError))
}
+ /// `kickstart` demands the job; it deliberately omits `-k`, which would
+ /// restart a job that a RunAtLoad bootstrap already won. The socket is what
+ /// decides readiness, so restarting a healthy service would only lose it.
static func kickstartArguments(uid: uid_t, label: String) -> [String] {
["kickstart", "gui/\(uid)/\(label)"]
}
+ /// The socket timeout stays the primary diagnostic, because that is what the
+ /// caller actually observed; a launchctl failure is appended when there was
+ /// one, since it usually explains the timeout.
static func socketFailureMessage(socketError: String?, kickstartError: String?)
-> String {
let kickstartDetail = kickstartError.map {
@@ -312,6 +354,7 @@ public final class DecodeServiceInferenceClient: AppModelLifecycleClient,
decodeSeconds: event.decodeSeconds,
tokensPerSecond: event.tokensPerSecond,
peakMemoryBytes: event.peakMemoryBytes,
+ visionTowerMappedBytes: event.visionTowerMappedBytes,
runtimeOptions: options,
prefill: prefillDiagnostics(event.prefill, options: options),
runner: event.runner.map(runnerDiagnostics))
@@ -355,7 +398,8 @@ public final class DecodeServiceInferenceClient: AppModelLifecycleClient,
prefillEnabled: options.prefillEnabled,
prefillChunkTokens: options.prefillChunkTokens,
rdadvisePolicy: options.rdadvisePolicy.rawValue,
- modelVerification: options.modelVerification.rawValue)
+ modelVerification: options.modelVerification.rawValue,
+ visionResidencyPolicy: options.visionResidencyPolicy.rawValue)
}
private static func removeLaunchJob(label: String) {
diff --git a/Sources/TurboFieldfareApp/Core/Inference/RealInferenceClient.swift b/Sources/TurboFieldfareApp/Core/Inference/RealInferenceClient.swift
index 851a8eba..ac6147c6 100644
--- a/Sources/TurboFieldfareApp/Core/Inference/RealInferenceClient.swift
+++ b/Sources/TurboFieldfareApp/Core/Inference/RealInferenceClient.swift
@@ -57,6 +57,11 @@ final class GenerationTaskRegistry: Sendable {
/// load lifecycle so the resident weights stay warm across generations.
public final class RealInferenceClient: AppModelLifecycleClient, @unchecked Sendable {
private let session: RealInferenceSession
+ /// Bytes of image tower held mapped, readable without awaiting the session.
+ public var currentVisionTowerBytes: UInt64? {
+ session.towerBytes.withLock { $0 }
+ }
+
private let memorySampler: AppMemorySampler
private let generationTasks = GenerationTaskRegistry()
@@ -156,6 +161,22 @@ actor RealInferenceSession {
private var tokenizerDirectoryCache = TokenizerDirectoryCache()
private var runner: RealForwardRunner?
private var scratch: RawCompletionScratch?
+ private var model: Model?
+
+ /// Bytes of image tower held mapped right now, published outside the actor
+ /// so a reader does not have to await it mid-decode.
+ nonisolated let towerBytes = Mutex<UInt64?>(nil)
+
+ private var visionRuntime: VisionRuntime? {
+ didSet { publishTowerBytes() }
+ }
+ private var visionRuntimeError: Error?
+
+ /// Called after anything that maps or releases tower regions.
+ private func publishTowerBytes() {
+ let value = visionRuntime.map { UInt64($0.retainedWeightBytes) }
+ towerBytes.withLock { $0 = value }
+ }
func ensureLoaded(key: SessionLoadKey,
onState: @Sendable (AppModelLoadState) -> Void) async throws {
@@ -163,7 +184,10 @@ actor RealInferenceSession {
runner = nil
scratch = nil
+ model = nil
loadedKey = nil
+ visionRuntime = nil
+ visionRuntimeError = nil
let start = Date()
do {
@@ -212,9 +236,34 @@ actor RealInferenceSession {
vocab: loadedModel.config.vocabSize)
try Task.checkCancellation()
+ let loadedVisionRuntime: VisionRuntime?
+ let loadedVisionRuntimeError: Error?
+ do {
+ let runtime = try VisionRuntime.open(
+ textModelURL: key.directory,
+ context: context)
+ // Keep Ready maps the tower during the load rather than on the
+ // first image, so the wait is where the user asked for it.
+ if key.options.visionResidencyPolicy == .keepReady {
+ onState(.loading(.mappingImageTower))
+ try runtime.prewarmWeightRegions()
+ }
+ loadedVisionRuntime = runtime
+ loadedVisionRuntimeError = nil
+ } catch {
+ // A missing or invalid pack only means images are unavailable;
+ // the reason travels to the first image turn.
+ loadedVisionRuntime = nil
+ loadedVisionRuntimeError = error
+ }
+ try Task.checkCancellation()
+
runner = loadedRunner
scratch = loadedScratch
+ model = loadedModel
loadedKey = key
+ visionRuntime = loadedVisionRuntime
+ visionRuntimeError = loadedVisionRuntimeError
onState(.ready(modelDirectory: key.directory,
loadSeconds: Date().timeIntervalSince(start)))
} catch is CancellationError {
@@ -253,6 +302,9 @@ actor RealInferenceSession {
}
func unload() {
+ visionRuntime = nil
+ visionRuntimeError = nil
+ model = nil
runner = nil
scratch = nil
tokenizer = nil
@@ -263,7 +315,14 @@ actor RealInferenceSession {
func run(request: AppGenerationRequest,
memorySampler: AppMemorySampler,
continuation: AsyncThrowingStream<AppInferenceEvent, Error>.Continuation) async {
- let prefillConfig = request.runtimeOptions.prefillConfig
+ var prefillConfig = request.runtimeOptions.prefillConfig
+ // Image spans only run under chunked prefill, and the app's prefill toggle
+ // can select `.off`. Coerce rather than fail after the encodes: whether
+ // images work is not a performance preference.
+ if !request.imageAttachments.isEmpty,
+ let coerced = prefillConfig.coercedForImagePrompt() {
+ prefillConfig = coerced
+ }
let progress = ProgressState()
do {
try request.validate()
@@ -283,10 +342,50 @@ actor RealInferenceSession {
throw AppInferenceError.modelLoadFailed("session lost its loaded state")
}
- let renderedPrompt = try tokenizer.applyChatTemplate([
- GFTokenizer.Message(role: .user, content: request.prompt)
- ])
- let promptIds = tokenizer.encode(renderedPrompt, addBOS: false)
+ let promptIds: [Int32]
+ let multimodalInput: MultimodalPrefillInput?
+ if request.imageAttachments.isEmpty {
+ let renderedPrompt = try tokenizer.applyChatTemplate([
+ GFTokenizer.Message(role: .user, content: request.prompt)
+ ])
+ promptIds = tokenizer.encode(renderedPrompt, addBOS: false)
+ multimodalInput = nil
+ } else {
+ guard let visionRuntime, let model else {
+ throw AppInferenceError.invalidRequest(
+ "Image support is unavailable: "
+ + (visionRuntimeError.map(String.init(describing:))
+ ?? "the image companion pack is not installed"))
+ }
+ var features: [UUID: VisionFeatures] = [:]
+ features.reserveCapacity(request.imageAttachments.count)
+ for attachment in request.imageAttachments {
+ try Task.checkCancellation()
+ // The file may have changed between selection and send.
+ let actualDigest = try Sha256Verifier.hashFile(
+ at: attachment.fileURL, chunkBytes: 256 * 1_024)
+ guard actualDigest == attachment.sha256 else {
+ throw AppInferenceError.invalidRequest(
+ "Image \(attachment.displayName) changed after selection.")
+ }
+ defer { publishTowerBytes() }
+ features[attachment.id] = try visionRuntime.encodeImage(
+ at: attachment.fileURL,
+ languageModel: model,
+ residencyPolicy: request.runtimeOptions.visionResidencyPolicy,
+ checkCancellation: { try Task.checkCancellation() })
+ }
+ var content = request.imageAttachments.map {
+ MultimodalContentPart.image(id: $0.id)
+ }
+ if !request.prompt.isEmpty { content.append(.text(request.prompt)) }
+ let input = try MultimodalPromptRenderer.render(
+ messages: [MultimodalMessage(role: .user, content: content)],
+ featuresByID: features,
+ tokenizer: tokenizer)
+ promptIds = input.effectiveTokenIDs
+ multimodalInput = input
+ }
progress.promptTokenCount = promptIds.count
guard promptIds.count < runner.maxContext else {
throw AppInferenceError.contextOverflow(prompt: promptIds.count,
@@ -306,6 +405,7 @@ actor RealInferenceSession {
let result = try await runRawCompletion(
producer: runner, tokenizer: tokenizer, promptIds: promptIds,
+ multimodalInput: multimodalInput,
config: config, context: ctx, scratch: scratch,
prefillConfig: prefillConfig) { event in
switch event {
@@ -418,6 +518,7 @@ actor RealInferenceSession {
decodeSeconds: decodeSeconds,
tokensPerSecond: decodeSeconds > 0 ? Double(generated) / decodeSeconds : 0,
peakMemoryBytes: memorySampler.peakBytes,
+ visionTowerMappedBytes: visionRuntime.map { UInt64($0.retainedWeightBytes) },
runtimeOptions: request.runtimeOptions,
prefill: prefill,
runner: runnerDiagnostics(progress: progress, generated: generated))
@@ -452,6 +553,7 @@ actor RealInferenceSession {
case .endOfTurn: return .endOfTurn
case .maxTokens: return .maxTokens
case .stopString: return .stopString
+ case .cancelled: return .cancelled
case .toolCalls: return .toolCalls
}
}
diff --git a/Sources/TurboFieldfareApp/Core/Installation/AppModelInstallDescriptor.swift b/Sources/TurboFieldfareApp/Core/Installation/AppModelInstallDescriptor.swift
index 7c5fe854..26e00f41 100644
--- a/Sources/TurboFieldfareApp/Core/Installation/AppModelInstallDescriptor.swift
+++ b/Sources/TurboFieldfareApp/Core/Installation/AppModelInstallDescriptor.swift
@@ -42,6 +42,16 @@ public struct AppModelInstallDescriptor: Equatable, Sendable {
installedBytes: 14_291_921_884,
rangeStagingBytes: UInt64(RemoteChunkPolicy.defaultBytes),
reserveBytes: 1_073_741_824)
+
+ public static let visionCompanion = AppModelInstallDescriptor(
+ displayName: "Gemma 4 Image Support",
+ repoID: "mlx-community/gemma-4-26b-a4b-it-4bit",
+ revision: "0d77464eeb233a2da68ebf9d7dc4edaac7db956d",
+ sourceIndexSHA256: "bf198c9f5ea6462addca1966e5dd669c407537a876e82cf06db9084c5c850b13",
+ approximateDownloadBytes: 1_539_478_890,
+ installedBytes: 1_144_373_248 + 4_194_304,
+ rangeStagingBytes: UInt64(RemoteChunkPolicy.defaultBytes),
+ reserveBytes: 1_073_741_824)
}
public struct AppModelInstallRequirement: Equatable, Sendable {
diff --git a/Sources/TurboFieldfareApp/Core/Installation/AppModelInstallState.swift b/Sources/TurboFieldfareApp/Core/Installation/AppModelInstallState.swift
index 35755de2..6f78f196 100644
--- a/Sources/TurboFieldfareApp/Core/Installation/AppModelInstallState.swift
+++ b/Sources/TurboFieldfareApp/Core/Installation/AppModelInstallState.swift
@@ -14,9 +14,11 @@ public enum AppModelInstallState: Equatable, Sendable {
)
case hashingOutput(String)
case finalizing
+ case activating
case cancelling
case discarding
case cancelled
+ case readyToActivate(URL)
case recoverable(String)
case installed(modelDirectory: URL)
case failed(String)
@@ -24,19 +26,24 @@ public enum AppModelInstallState: Equatable, Sendable {
public var isInstalling: Bool {
switch self {
case .checking, .downloadingMetadata, .planning, .reservingOutput,
- .copyingPayload, .hashingOutput, .finalizing, .cancelling, .discarding:
+ .copyingPayload, .hashingOutput, .finalizing, .activating,
+ .cancelling, .discarding:
return true
- case .idle, .cancelled, .recoverable, .installed, .failed:
+ case .idle, .cancelled, .readyToActivate, .recoverable, .installed, .failed:
return false
}
}
public var canCancel: Bool {
switch self {
+ // `.activating` is cancellable because the only long phase in it is the
+ // hash of the companion weights, which happens before anything is
+ // renamed: abandoning it leaves the prepared pack exactly as it was.
case .checking, .downloadingMetadata, .planning, .reservingOutput,
- .copyingPayload, .hashingOutput, .finalizing:
+ .copyingPayload, .hashingOutput, .finalizing, .activating:
return true
- case .idle, .cancelling, .discarding, .cancelled, .recoverable, .installed, .failed:
+ case .idle, .cancelling, .discarding, .cancelled, .readyToActivate,
+ .recoverable, .installed, .failed:
return false
}
}
@@ -54,5 +61,6 @@ public enum AppModelInstallEvent: Equatable, Sendable {
)
case hashingOutput(String)
case finalizing
+ case readyToActivate(URL)
case installed(URL)
}
diff --git a/Sources/TurboFieldfareApp/Core/Installation/AppVisionPackInstallationProbe.swift b/Sources/TurboFieldfareApp/Core/Installation/AppVisionPackInstallationProbe.swift
new file mode 100644
index 00000000..def389c6
--- /dev/null
+++ b/Sources/TurboFieldfareApp/Core/Installation/AppVisionPackInstallationProbe.swift
@@ -0,0 +1,44 @@
+import Foundation
+import TurboFieldfare
+import TurboFieldfareRepackCore
+
+public enum AppVisionPackInstallationStatus: Equatable, Sendable {
+ case missing
+ case partial(String)
+ case complete
+ /// This model layout cannot host a companion pack at all — the directory is
+ /// not named `*.gturbo`, so there is no path to put one at.
+ ///
+ /// Distinct from `.partial`, which means a pack is there and damaged and
+ /// offers Repair. Reporting this as `.partial` printed a raw
+ /// `invalidTextModelPath(...)` under "Needs repair" and offered to download
+ /// a pack that could never be located.
+ case unsupportedLayout
+}
+
+public enum AppVisionPackInstallationProbe {
+ public static func status(at textModelDirectory: URL) -> AppVisionPackInstallationStatus {
+ let textModelDirectory = textModelDirectory.standardizedFileURL
+ let companion: URL
+ do {
+ companion = try VisionPackLocation.companionURL(forTextModel: textModelDirectory)
+ } catch {
+ // The only failure here is a directory name that cannot carry a
+ // companion, which is a property of the layout rather than of any
+ // pack on disk.
+ return .unsupportedLayout
+ }
+ guard FileManager.default.fileExists(atPath: companion.path) else {
+ return .missing
+ }
+ do {
+ _ = try VisionPackVerifier.verify(
+ directory: companion,
+ textModelDirectory: textModelDirectory,
+ verifyWeights: false)
+ return .complete
+ } catch {
+ return .partial("\(error)")
+ }
+ }
+}
diff --git a/Sources/TurboFieldfareApp/Core/Installation/AppVisionPackInstallerClient.swift b/Sources/TurboFieldfareApp/Core/Installation/AppVisionPackInstallerClient.swift
new file mode 100644
index 00000000..48e3dfc7
--- /dev/null
+++ b/Sources/TurboFieldfareApp/Core/Installation/AppVisionPackInstallerClient.swift
@@ -0,0 +1,15 @@
+import Foundation
+
+public protocol AppVisionPackInstallerClient: Sendable {
+ var descriptor: AppModelInstallDescriptor { get }
+ func checkInstallRequirement(textModelDirectory: URL) throws -> AppModelInstallRequirement
+ func install(textModelDirectory: URL) -> AsyncThrowingStream<AppModelInstallEvent, Error>
+ func preparedInstallIsValid(textModelDirectory: URL) -> Bool
+ func activatePreparedInstall(
+ textModelDirectory: URL,
+ onVerifyProgress: (@Sendable (Double) -> Void)?
+ ) async throws -> URL
+ func discardPartialInstall(textModelDirectory: URL) async throws
+ func removeInstalled(textModelDirectory: URL) async throws
+ func cancel()
+}
diff --git a/Sources/TurboFieldfareApp/Core/Installation/RepackVisionPackInstallerClient.swift b/Sources/TurboFieldfareApp/Core/Installation/RepackVisionPackInstallerClient.swift
new file mode 100644
index 00000000..963cdd5d
--- /dev/null
+++ b/Sources/TurboFieldfareApp/Core/Installation/RepackVisionPackInstallerClient.swift
@@ -0,0 +1,216 @@
+import Foundation
+import Synchronization
+import TurboFieldfare
+import TurboFieldfareRepackCore
+
+public final class RepackVisionPackInstallerClient: AppVisionPackInstallerClient, Sendable {
+ typealias InstallRunner = @Sendable (
+ URL,
+ @escaping @Sendable (ModelInstallProgress) -> Void
+ ) async throws -> URL
+ typealias MutationRunner = @Sendable (URL) async throws -> Void
+
+ private struct ActiveInstall: Sendable {
+ let id: UUID
+ let task: Task<Void, Never>
+ }
+
+ private final class InstallTaskState: Sendable {
+ let value = Mutex<ActiveInstall?>(nil)
+ }
+
+ public let descriptor: AppModelInstallDescriptor
+ private let runInstall: InstallRunner
+ private let runDiscard: MutationRunner
+ private let runRemove: MutationRunner
+ private let taskState = InstallTaskState()
+
+ public init(descriptor: AppModelInstallDescriptor = .visionCompanion) {
+ self.descriptor = descriptor
+ self.runInstall = { textModelDirectory, progress in
+ let output = try VisionPackLocation.companionURL(
+ forTextModel: textModelDirectory)
+ let paths = try RemoteInstallPaths(outputDirectory: output.path)
+ let resume = FileManager.default.fileExists(atPath: paths.checkpointFile)
+ let options = RemoteVisionPackInstallOptions(
+ repoID: descriptor.repoID,
+ revision: descriptor.revision,
+ textModelDirectory: textModelDirectory.path,
+ outputDirectory: output.path,
+ token: ProcessInfo.processInfo.environment["HF_TOKEN"],
+ minFreeReserveBytes: descriptor.reserveBytes,
+ overwrite: true,
+ resume: resume)
+ let result = try await RemoteVisionPackInstaller(options: options)
+ .prepare(progress: progress)
+ return URL(fileURLWithPath: result.outputDirectory).standardizedFileURL
+ }
+ self.runDiscard = { textModelDirectory in
+ let output = try VisionPackLocation.companionURL(
+ forTextModel: textModelDirectory)
+ try RemoteVisionPackInstaller.discardPartial(
+ outputDirectory: output.path)
+ }
+ self.runRemove = { textModelDirectory in
+ let output = try VisionPackLocation.companionURL(
+ forTextModel: textModelDirectory)
+ try RemoteVisionPackInstaller.removeInstalled(
+ outputDirectory: output.path)
+ }
+ }
+
+ init(
+ descriptor: AppModelInstallDescriptor = .visionCompanion,
+ runInstall: @escaping InstallRunner,
+ runDiscard: @escaping MutationRunner = { _ in },
+ runRemove: @escaping MutationRunner = { _ in }
+ ) {
+ self.descriptor = descriptor
+ self.runInstall = runInstall
+ self.runDiscard = runDiscard
+ self.runRemove = runRemove
+ }
+
+ public func checkInstallRequirement(
+ textModelDirectory: URL
+ ) throws -> AppModelInstallRequirement {
+ let output = try VisionPackLocation.companionURL(
+ forTextModel: textModelDirectory)
+ let saved = try RemoteVisionPackInstaller.inspectPersistentInstall(
+ outputDirectory: output.path,
+ repoID: descriptor.repoID,
+ requestedRevision: descriptor.revision)
+ let reused = try saved?.validatedDestinationBytes(
+ maximum: descriptor.installedBytes,
+ path: RemoteInstallPaths(outputDirectory: output.path).checkpointFile) ?? 0
+ let remaining = descriptor.installedBytes > reused
+ ? descriptor.installedBytes - reused
+ : 0
+ let requested = remaining.addingReportingOverflow(descriptor.rangeStagingBytes)
+ guard !requested.overflow else {
+ throw RepackError.configurationInvalid(
+ detail: "vision install requirement overflows UInt64")
+ }
+ let requirement = try DiskSpaceChecker.assess(
+ path: output.path,
+ bytes: requested.partialValue,
+ reserveBytes: descriptor.reserveBytes)
+ return AppModelInstallRequirement(
+ probePath: requirement.path,
+ requiredBytes: requirement.requiredBytes,
+ availableBytes: requirement.availableBytes)
+ }
+
+ public func install(
+ textModelDirectory: URL
+ ) -> AsyncThrowingStream<AppModelInstallEvent, Error> {
+ AsyncThrowingStream { continuation in
+ let id = UUID()
+ let task = Task { [runInstall] in
+ do {
+ continuation.yield(.checking)
+ let directory = try await runInstall(textModelDirectory) { progress in
+ continuation.yield(RepackModelInstallerClient.event(for: progress))
+ }
+ try Task.checkCancellation()
+ continuation.yield(.readyToActivate(directory))
+ continuation.finish()
+ } catch is CancellationError {
+ continuation.finish(throwing: CancellationError())
+ } catch {
+ continuation.finish(throwing: error)
+ }
+ }
+ let previous = taskState.value.withLock { active in
+ let previous = active?.task
+ active = ActiveInstall(id: id, task: task)
+ return previous
+ }
+ previous?.cancel()
+ continuation.onTermination = { [taskState] _ in
+ let task = taskState.value.withLock { active -> Task<Void, Never>? in
+ guard active?.id == id else { return nil }
+ defer { active = nil }
+ return active?.task
+ }
+ task?.cancel()
+ }
+ }
+ }
+
+ public func cancel() {
+ let task = taskState.value.withLock { active -> Task<Void, Never>? in
+ defer { active = nil }
+ return active?.task
+ }
+ task?.cancel()
+ }
+
+ public func discardPartialInstall(textModelDirectory: URL) async throws {
+ try await mutate(textModelDirectory, using: runDiscard)
+ }
+
+ public func preparedInstallIsValid(textModelDirectory: URL) -> Bool {
+ guard let output = try? VisionPackLocation.companionURL(
+ forTextModel: textModelDirectory) else { return false }
+ return RemoteVisionPackInstaller.preparedInstallIsValid(
+ outputDirectory: output.path,
+ textModelDirectory: textModelDirectory.path)
+ }
+
+ public func activatePreparedInstall(
+ textModelDirectory: URL,
+ onVerifyProgress: (@Sendable (Double) -> Void)? = nil
+ ) async throws -> URL {
+ let textModelDirectory = textModelDirectory.standardizedFileURL
+ let output = try VisionPackLocation.companionURL(
+ forTextModel: textModelDirectory)
+ try await runCancellableDetached { [descriptor] in
+ try RemoteVisionPackInstaller.activatePrepared(
+ outputDirectory: output.path,
+ textModelDirectory: textModelDirectory.path,
+ repoID: descriptor.repoID,
+ requestedRevision: descriptor.revision,
+ onVerifyProgress: { hashed, total in
+ // Cancellation rides the progress callback: verification is
+ // the only phase that can be abandoned safely, and it is the
+ // only one that takes minutes.
+ try Task.checkCancellation()
+ guard let onVerifyProgress, total > 0 else { return }
+ onVerifyProgress(min(max(Double(hashed) / Double(total), 0), 1))
+ })
+ }
+ return output.standardizedFileURL
+ }
+
+ public func removeInstalled(textModelDirectory: URL) async throws {
+ try await mutate(textModelDirectory, using: runRemove)
+ }
+
+ /// Runs blocking work off the calling task, with cancellation forwarded.
+ ///
+ /// `Task.detached` inherits nothing, cancellation included, so a detached
+ /// body that cooperatively checks `Task.isCancelled` is checking a flag
+ /// nobody ever sets: cancelling the caller left the vision pack's
+ /// multi-minute verification hash running to completion and activating the
+ /// pack anyway, while the UI sat on "Cancelling" with every model action
+ /// disabled. Extracted so the forwarding itself can be tested; inline, the
+ /// only way to exercise it was a real 1.14 GB pack.
+ func runCancellableDetached<T: Sendable>(
+ priority: TaskPriority = .utility,
+ _ body: @escaping @Sendable () throws -> T
+ ) async throws -> T {
+ let work = Task.detached(priority: priority, operation: body)
+ return try await withTaskCancellationHandler {
+ try await work.value
+ } onCancel: {
+ work.cancel()
+ }
+ }
+
+ private func mutate(_ directory: URL, using runner: @escaping MutationRunner) async throws {
+ try await Task.detached(priority: .utility) {
+ try await runner(directory.standardizedFileURL)
+ }.value
+ }
+}
diff --git a/Sources/TurboFieldfareApp/Core/Installation/VisionSectionVisibility.swift b/Sources/TurboFieldfareApp/Core/Installation/VisionSectionVisibility.swift
new file mode 100644
index 00000000..47a6ff74
--- /dev/null
+++ b/Sources/TurboFieldfareApp/Core/Installation/VisionSectionVisibility.swift
@@ -0,0 +1,34 @@
+import Foundation
+
+/// Whether the inspector shows its Image Support section.
+///
+/// This lived as a private computed property on the inspector view, where the
+/// only way to check it was to launch the app and look. It decides four distinct
+/// situations, so it is worth being able to test all four.
+public enum VisionSectionVisibility {
+ /// Shown while the section has something to say, hidden once it does not.
+ ///
+ /// An installed text model is deliberately *not* required. Requiring one hid
+ /// image support behind a 14.62 GB download, so the screen where someone
+ /// decides whether this app does what they need never mentioned that it
+ /// handles images at all. The section still collapses once the pack is
+ /// installed and healthy, so it costs space only while it is actionable.
+ public static func shows(
+ visionRuntimeEnabled: Bool,
+ visionRuntimeSupported: Bool = true,
+ isModelInstalled: Bool,
+ isVisionPackInstalled: Bool,
+ isCompanionOperationInProgress: Bool,
+ installState: AppModelInstallState
+ ) -> Bool {
+ guard visionRuntimeEnabled else { return false }
+ if !visionRuntimeSupported { return true }
+ if !isModelInstalled { return true }
+ if !isVisionPackInstalled { return true }
+ if isCompanionOperationInProgress { return true }
+ switch installState {
+ case .failed, .recoverable: return true
+ default: return false
+ }
+ }
+}
diff --git a/Sources/TurboFieldfareApp/Core/State/AppModel.swift b/Sources/TurboFieldfareApp/Core/State/AppModel.swift
index 2770f771..df4cd815 100644
--- a/Sources/TurboFieldfareApp/Core/State/AppModel.swift
+++ b/Sources/TurboFieldfareApp/Core/State/AppModel.swift
@@ -1,5 +1,8 @@
import Foundation
+import Synchronization
+import TurboFieldfare
import TurboFieldfareRepackCore
+import TurboFieldfare
import Observation
@MainActor
@@ -12,7 +15,20 @@ public final class AppModel {
public var modelPathText: String
public var promptText: String = ""
+ public private(set) var imageAttachments: [AppImageAttachment] = []
+ public private(set) var imageAttachmentError: String?
+ /// A count, not a flag. The picker and a drop can both be staging at once,
+ /// and whichever finished first cleared a shared Bool — reopening `canRun`
+ /// while the other was still copying, so Generate ran against a partial set
+ /// and the remaining images were appended after the run had snapshotted its
+ /// own, where `removeImage` and `clearImages` are no-ops.
+ private var addingImagesCount = 0
+ public var isAddingImages: Bool { addingImagesCount > 0 }
+ /// Set by the Model menu's Remove Image Support item; the window presents
+ /// the confirmation.
+ public var isConfirmingVisionPackRemoval = false
public private(set) var outputPromptText: String = ""
+ public private(set) var outputImageAttachments: [AppImageAttachment] = []
public var outputText: String = ""
public var runState: RunState = .idle
public var runtimeOptions = AppRuntimeOptions()
@@ -26,13 +42,29 @@ public final class AppModel {
public private(set) var newlineShortcut: AppNewlineShortcut = .return
public private(set) var showPromptExamples: Bool = true
public private(set) var sentPromptBehavior: AppSentPromptBehavior = .keep
+ public private(set) var loadModelOnLaunch: Bool = false
+ /// Whether launching the app should load the model straight away. Off by
+ /// default, because loading takes minutes and holds gigabytes.
public var diagnostics: AppDiagnostics?
public var error: AppInferenceError?
public var installState: AppModelInstallState = .idle
public private(set) var installETAPresentation: DownloadETAPresentation = .hidden
public private(set) var installETAText: String?
+ /// The companion download is 1.5 GB and deserves the same answer to "how
+ /// long is this going to take" as the model download. Kept separate because
+ /// both can be in flight in principle and an estimator holds per-download
+ /// rate state.
+ public private(set) var visionInstallETAPresentation: DownloadETAPresentation = .hidden
+ public private(set) var visionInstallETAText: String?
public private(set) var installReadiness: AppModelInstallReadiness = .checking
public private(set) var installationStatus: AppModelInstallationStatus
+ public var visionInstallState: AppModelInstallState = .idle
+ /// How far activation's hash of the companion weights has got, 0 to 1.
+ /// Activation reads about 1.5 GB, which was a bare spinner with no way to
+ /// tell a slow verify from a stuck one.
+ public private(set) var visionActivationProgress: Double?
+ public private(set) var visionInstallReadiness: AppModelInstallReadiness = .checking
+ public private(set) var visionInstallationStatus: AppVisionPackInstallationStatus
public var loadState: AppModelLoadState = .notLoaded
public private(set) var loadedRuntimeKey: AppLoadedRuntimeKey?
@@ -42,17 +74,42 @@ public final class AppModel {
public private(set) var livePrefillDone: Int = 0
public private(set) var livePrefillTotal: Int = 0
public private(set) var liveMemoryBytes: UInt64?
+ /// Resident bytes of the inference process. The footprint above is what
+ /// the system counts against the process; this is what it actually holds,
+ /// including the mapped weights the footprint omits. A 26B model reports
+ /// about 160 MB of footprint right after loading, which is true and reads
+ /// as nonsense without this beside it.
+ public private(set) var liveResidentBytes: UInt64?
+ /// Tower weights the inference process is holding mapped, reported
+ /// separately because no per-process counter attributes them.
+ public private(set) var visionTowerMappedBytes: UInt64?
public private(set) var isCancellationPending: Bool = false
+ /// Increments when a generation starts. The transcript watches it to put
+ /// the newest turn on screen: with several images attached, the prompt and
+ /// its thumbnails are tall enough to push the answer out of view, so
+ /// scrolling only when the reader was already at the bottom left them
+ /// looking at their own attachments while the model worked.
+ public private(set) var runIdentity: Int = 0
private let client: any AppInferenceClient
private let installer: any AppModelInstallerClient
+ private let visionInstaller: any AppVisionPackInstallerClient
private var runTask: Task<Void, Never>?
private var loadTask: Task<Void, Never>?
private var installTask: Task<Void, Never>?
+ private var visionInstallTask: Task<Void, Never>?
private var unloadTask: Task<Void, Never>?
private var loadGeneration: UInt64 = 0
+ /// The highest load-phase sequence already applied. Each `onState` callback
+ /// hops to the main actor in its own task, and ordering between separately
+ /// created tasks is not guaranteed, so `.ready` could be applied before the
+ /// `.loading(.preparingRunner)` that preceded it and leave the UI showing a
+ /// phase the runtime had already left.
+ private var appliedLoadSequence: UInt64 = 0
private var unloadGeneration: UInt64 = 0
private var installGeneration: UInt64 = 0
+ private var visionInstallGeneration: UInt64 = 0
+ private var visionInstallCancellationRequested = false
private var pendingExplicitLoadRuntimeKey: AppLoadedRuntimeKey?
private var activeRunRuntimeKey: AppLoadedRuntimeKey?
private var hasHandledTerminalEvent = false
@@ -61,11 +118,21 @@ public final class AppModel {
private let installETAClock: SuspendingClock
private let installETAOrigin: SuspendingClock.Instant
private var installETAEstimator = DownloadETAEstimator()
+ private var visionInstallETAEstimator = DownloadETAEstimator()
+ private let attachmentStore: AppImageAttachmentStore
+ public let isVisionRuntimeSupported: Bool
+
+ public static var currentDeviceSupportsVisionRuntime: Bool {
+ VisionRuntime.isSupportedOnDefaultDevice
+ }
public init(modelDirectory: URL? = nil,
client: any AppInferenceClient = RealInferenceClient(),
installer: any AppModelInstallerClient = RepackModelInstallerClient(),
+ visionInstaller: any AppVisionPackInstallerClient = RepackVisionPackInstallerClient(),
memorySampler: AppMemorySampler = AppMemorySampler(),
+ attachmentStore: AppImageAttachmentStore = AppImageAttachmentStore(),
+ visionRuntimeSupported: Bool = true,
settingsPersistenceEnabled: Bool = false) {
let directory = (modelDirectory ?? AppModelLocation.defaultURL()).standardizedFileURL
let installETAClock = SuspendingClock()
@@ -73,9 +140,17 @@ public final class AppModel {
? MacAppSettingsFileStore.loadOrCreate(forModelDirectory: directory)
: MacAppSettings()
self.modelPathText = directory.path
+ // The app always releases the image tower after each image. Keeping it
+ // resident saves a few hundred milliseconds on a run of images and
+ // holds about 1 GB of page cache to do it — a trade worth exposing to
+ // a CLI or server operator, not to someone using the app, where it was
+ // one more setting whose effect no figure on screen could show.
+ // `keepReady` remains available through AppRuntimeOptions for those.
self.runtimeOptions = AppRuntimeOptions(
expertCacheSlots: settings.expertCacheSlots,
- prefillEnabled: settings.prefillEnabled)
+ prefillEnabled: settings.prefillEnabled,
+ rdadvisePolicy: settings.rdadvisePolicy,
+ visionResidencyPolicy: .onDemand)
self.maxContextTokens = settings.contextTokens
self.temperature = settings.temperature
self.topKEnabled = settings.topKEnabled
@@ -85,14 +160,23 @@ public final class AppModel {
self.newlineShortcut = settings.newlineShortcut
self.showPromptExamples = settings.showPromptExamples
self.sentPromptBehavior = settings.sentPromptBehavior
+ self.loadModelOnLaunch = settings.loadModelOnLaunch
self.installationStatus = AppModelInstallationProbe.status(at: directory)
+ self.visionInstallationStatus = AppVisionPackInstallationProbe.status(at: directory)
self.client = client
self.installer = installer
+ self.visionInstaller = visionInstaller
self.memorySampler = memorySampler
+ self.attachmentStore = attachmentStore
+ self.isVisionRuntimeSupported = visionRuntimeSupported
self.settingsPersistenceEnabled = settingsPersistenceEnabled
self.installETAClock = installETAClock
self.installETAOrigin = installETAClock.now
+ // Staged images of runs that were killed before they could clean up;
+ // nothing else ever removes them.
+ AppImageAttachmentStore.sweepAbandoned()
refreshInstallReadiness()
+ refreshVisionInstallReadiness()
}
public var isRunning: Bool { runState == .running }
@@ -105,7 +189,8 @@ public final class AppModel {
}
public var canLoadModel: Bool {
- isModelInstalled && !isRunning && (loadState == .notLoaded || loadState.isFailed)
+ isModelInstalled && !isRunning && !isVisionCompanionOperationInProgress
+ && (loadState == .notLoaded || loadState.isFailed)
}
public var canCancelLoad: Bool {
@@ -114,11 +199,13 @@ public final class AppModel {
}
public var canReloadModel: Bool {
- isModelInstalled && !isRunning && loadState.isReady && hasStaleLoadedRuntime
+ isModelInstalled && !isRunning && !isVisionCompanionOperationInProgress
+ && loadState.isReady && hasStaleLoadedRuntime
}
public var canUnloadModel: Bool {
- isModelInstalled && !isRunning && loadState.isReady
+ isModelInstalled && !isRunning && !isVisionCompanionOperationInProgress
+ && loadState.isReady
}
public var isModelInstalled: Bool { installationStatus == .complete }
@@ -136,17 +223,96 @@ public final class AppModel {
public var canInstallModel: Bool {
guard case .ready = installReadiness else { return false }
return !isRunning && !loadState.isLoading && !isInstallingModel
+ && !isVisionCompanionOperationInProgress
&& requiresModelInstallation
}
public var canCancelInstall: Bool { installState.canCancel }
+ public var isVisionPackInstalled: Bool { visionInstallationStatus == .complete }
+
+ public var isInstallingVisionPack: Bool { visionInstallState.isInstalling }
+
+ public var visionInstallDescriptor: AppModelInstallDescriptor {
+ visionInstaller.descriptor
+ }
+
+ /// Every companion Download, Resume, Verify, Activate, Repair, and Remove
+ /// operation is one app-blocking state: model actions stay disabled until it
+ /// reaches a resting state, so a companion transaction never overlaps a
+ /// loaded session or another companion operation.
+ public var isVisionCompanionOperationInProgress: Bool {
+ visionInstallState.isInstalling
+ }
+
+ /// A companion operation may only begin against an unloaded model session
+ /// with no other transfer in flight; the draft, transcript, and attachments
+ /// are untouched by the gate.
+ public var canBeginVisionCompanionOperation: Bool {
+ !isRunning && !loadState.isLoading && !loadState.isReady
+ && !isInstallingModel && !isVisionCompanionOperationInProgress
+ }
+
+ public var canInstallVisionPack: Bool {
+ guard isVisionRuntimeSupported else { return false }
+ // A layout with nowhere to put a companion cannot be repaired by
+ // downloading one, so do not offer to.
+ guard visionInstallationStatus != .unsupportedLayout else { return false }
+ guard isModelInstalled, !isVisionPackInstalled,
+ case .ready = visionInstallReadiness else { return false }
+ if case .readyToActivate = visionInstallState { return false }
+ return canBeginVisionCompanionOperation
+ }
+
+ public var canActivateVisionPack: Bool {
+ guard isVisionRuntimeSupported else { return false }
+ guard case .readyToActivate = visionInstallState else { return false }
+ return canBeginVisionCompanionOperation
+ }
+
+ public var canCancelVisionInstall: Bool { visionInstallState.canCancel }
+
+ public var visionInstallProgressFraction: Double? {
+ // Activation hashes about 1.5 GB, so it gets a bar of its own rather
+ // than an indeterminate spinner for minutes.
+ if case .activating = visionInstallState { return visionActivationProgress }
+ guard case .copyingPayload(let reused, let downloaded, let total) = visionInstallState,
+ total > 0 else { return nil }
+ let addition = reused.addingReportingOverflow(downloaded)
+ let done = addition.overflow ? UInt64.max : addition.partialValue
+ return min(max(Double(done) / Double(total), 0), 1)
+ }
+
+ public var visionInstallPhaseLabel: String {
+ switch visionInstallState {
+ case .idle: return isVisionPackInstalled ? "Installed" : "Not installed"
+ case .checking: return "Checking image support"
+ case .downloadingMetadata: return "Downloading metadata"
+ case .planning: return "Planning image support"
+ case .reservingOutput: return "Reserving storage"
+ case .copyingPayload: return "Downloading image support"
+ case .hashingOutput(let file): return "Verifying \(file)"
+ case .finalizing: return "Finalizing download"
+ case .activating:
+ guard let fraction = visionActivationProgress else {
+ return "Activating image support"
+ }
+ return "Verifying image support \(Int(fraction * 100))%"
+ case .cancelling: return "Cancelling"
+ case .discarding: return "Cleaning up"
+ case .cancelled: return "Download paused"
+ case .readyToActivate: return "Ready to activate"
+ case .recoverable: return "Saved download needs attention"
+ case .installed: return "Installed"
+ case .failed: return "Installation failed"
+ }
+ }
+
public var installDownloadedBytes: UInt64? {
guard case .copyingPayload(let reused, let downloaded, let total) = installState else {
return nil
}
- let addition = reused.addingReportingOverflow(downloaded)
- return min(addition.overflow ? UInt64.max : addition.partialValue, total)
+ return min(reused.addingReportingOverflow(downloaded).partialValue, total)
}
public var installTotalBytes: UInt64? {
@@ -190,9 +356,15 @@ public final class AppModel {
case .copyingPayload: return "Downloading model"
case .hashingOutput(let file): return "Verifying \(file)"
case .finalizing: return "Finalizing installation"
+ case .activating:
+ guard let fraction = visionActivationProgress else {
+ return "Activating image support"
+ }
+ return "Verifying image support \(Int(fraction * 100))%"
case .cancelling: return "Cancelling"
case .discarding: return "Discarding download"
case .cancelled: return "Download paused"
+ case .readyToActivate: return "Ready to activate"
case .recoverable: return "Saved download needs attention"
case .installed: return "Model installed"
case .failed: return "Installation failed"
@@ -200,15 +372,20 @@ public final class AppModel {
}
public var canRun: Bool {
- !isRunning && isModelAvailable && !loadState.isLoading
+ // Staging copies the files a request will carry. Starting a run while
+ // it is in flight sent a request without those images and then landed
+ // them on the next message instead.
+ !isRunning && !isAddingImages && isModelAvailable && !loadState.isLoading
+ && !isVisionCompanionOperationInProgress
&& !hasStaleLoadedRuntime
- && !promptText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
+ && (!promptText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
+ || !imageAttachments.isEmpty)
}
public var canCancel: Bool { isRunning && !isCancellationPending }
public var hasOutputTranscript: Bool {
- !outputPromptText.isEmpty || !outputText.isEmpty
+ !outputPromptText.isEmpty || !outputImageAttachments.isEmpty || !outputText.isEmpty
}
public var outputResponsePlainText: String {
@@ -245,14 +422,22 @@ public final class AppModel {
generationPhase: phase,
livePrefillDone: livePrefillDone,
livePrefillTotal: livePrefillTotal,
- lastStopReason: diagnostics?.stopReason))
+ lastStopReason: diagnostics?.stopReason,
+ isVisionCompanionOperationInProgress: isVisionCompanionOperationInProgress))
}
public var currentProcessMemoryBytes: UInt64? {
guard loadState.isReady || isRunning else { return nil }
- if let reporter = client as? any AppInferenceMemoryReporting,
- let bytes = reporter.currentInferenceMemoryBytes {
- return bytes
+ // `liveMemoryBytes` first because it is a tracked property: reading the
+ // reporter alone told the truth but was invisible to observation, so
+ // the figure only refreshed when something else — a generated token —
+ // happened to redraw the view. Through prefill, nothing did.
+ if let liveMemoryBytes { return liveMemoryBytes }
+ // When inference runs in another process, its memory is the only
+ // memory worth showing. Falling back to this app's own sampler put the
+ // UI's footprint in a row labelled as the model's.
+ if let reporter = client as? any AppInferenceMemoryReporting {
+ return reporter.currentInferenceMemoryBytes
}
return memorySampler.sample()
}
@@ -278,6 +463,7 @@ public final class AppModel {
guard path != modelPathText else { return }
modelPathText = path
+ clearImages()
applyPersistedSettings(
forModelDirectory: URL(fileURLWithPath: path, isDirectory: true))
loadGeneration &+= 1
@@ -287,8 +473,14 @@ public final class AppModel {
installTask?.cancel()
installer.cancel()
installTask = nil
+ visionInstallGeneration &+= 1
+ visionInstallCancellationRequested = false
+ visionInstallTask?.cancel()
+ visionInstaller.cancel()
+ visionInstallTask = nil
resetInstallETA()
installState = .idle
+ visionInstallState = .idle
pendingExplicitLoadRuntimeKey = nil
activeRunRuntimeKey = nil
loadedRuntimeKey = nil
@@ -297,7 +489,10 @@ public final class AppModel {
error = nil
phase = .idle
installationStatus = AppModelInstallationProbe.status(at: URL(fileURLWithPath: path))
+ visionInstallationStatus = AppVisionPackInstallationProbe.status(
+ at: URL(fileURLWithPath: path))
refreshInstallReadiness()
+ refreshVisionInstallReadiness()
if let lifecycle = client as? AppModelLifecycleClient {
unloadGeneration &+= 1
@@ -344,6 +539,212 @@ public final class AppModel {
persistSettings()
}
+ public func setLoadModelOnLaunch(_ enabled: Bool) {
+ guard loadModelOnLaunch != enabled else { return }
+ loadModelOnLaunch = enabled
+ persistSettings()
+ }
+
+ /// Starts the launch load if it is switched on and the model can be loaded.
+ /// Called once, when the window first appears; a model that is missing,
+ /// already loading, or busy with a companion operation is left alone.
+ public func loadModelAtLaunchIfEnabled() {
+ guard loadModelOnLaunch, canLoadModel else { return }
+ loadModel()
+ }
+
+ /// Whether an image can be attached at all.
+ ///
+ /// The runtime flag only says this build *can* use images; the companion
+ /// pack is what makes it possible for this model. Gating on the flag alone
+ /// offered an Add-images button with no tower behind it, and the failure
+ /// only surfaced when the user pressed Generate.
+ public var isImageInputAvailable: Bool {
+ isVisionRuntimeSupported && isVisionPackInstalled
+ }
+
+ /// Image support is part of this build. Hardware support and companion-pack
+ /// availability are separate so the inspector can explain either absence.
+ public var visionRuntimeEnabled: Bool { true }
+
+ /// Room left for the prompt when working out how many images fit. The
+ /// runtime still rejects a combination that does not fit, so this only has
+ /// to be a defensible reserve rather than an exact prompt measurement.
+ static let reservedPromptTokens = 1_024
+
+ /// How many images this conversation can hold, derived from the context
+ /// exactly as the server derives its budget. It used to be a fixed four,
+ /// which meant the same set of images was accepted over the API and refused
+ /// in the app.
+ public var maximumImageAttachments: Int {
+ // The context a run will actually use, which is the loaded session's
+ // until it is reloaded. Capping on the pending setting instead let the
+ // composer accept images the request then refused.
+ max(1, VisionImageTokenBudget.capacity(
+ maxContext: effectiveMaxContextTokens,
+ reservedTextTokens: Self.reservedPromptTokens))
+ }
+
+ /// The context a generation would run with right now.
+ public var effectiveMaxContextTokens: Int {
+ (loadedRuntimeKey ?? currentRuntimeKey).maxContextTokens
+ }
+
+ /// `discardingSourceDirectory` is the temp directory a file-promise drop
+ /// wrote into. It is ours, it holds nothing but those copies, and staging
+ /// takes its own copy — so it must not outlive the staging that consumed
+ /// it, which is exactly how it leaked.
+ public func addImages(_ urls: [URL], discardingSourceDirectory: URL? = nil) {
+ // Every early return has to discard the promise directory itself. The
+ // staging task's `defer` below owns it only once that task exists, so a
+ // return above it strands the full-size copies with nothing left to
+ // delete them: the attachment sweep only covers the staging root.
+ func discardSource() {
+ if let discardingSourceDirectory {
+ try? FileManager.default.removeItem(at: discardingSourceDirectory)
+ }
+ }
+ guard isImageInputAvailable, !urls.isEmpty else {
+ discardSource()
+ return
+ }
+ guard !isRunning else {
+ // A promise drop admitted before the run started can be delivered
+ // after it. Returning silently made the images look as though they
+ // had simply vanished.
+ imageAttachmentError =
+ "Wait for the current run to finish before attaching images."
+ discardSource()
+ return
+ }
+ let capacity = maximumImageAttachments
+ let available = max(0, capacity - imageAttachments.count)
+ guard available > 0 else {
+ imageAttachmentError = Self.imageCapacityMessage(
+ capacity: capacity, context: effectiveMaxContextTokens)
+ discardSource()
+ return
+ }
+ addingImagesCount += 1
+ imageAttachmentError = nil
+ // Dropping the rest silently left the user believing every image they
+ // chose was attached.
+ let selected = Array(urls.prefix(available))
+ if selected.count < urls.count {
+ imageAttachmentError = Self.imageCapacityMessage(
+ capacity: capacity, context: effectiveMaxContextTokens)
+ }
+ let store = attachmentStore
+ Task.detached(priority: .userInitiated) { [weak self] in
+ var staged: [AppImageAttachment] = []
+ defer {
+ if let discardingSourceDirectory {
+ try? FileManager.default.removeItem(at: discardingSourceDirectory)
+ }
+ }
+ do {
+ for url in selected {
+ staged.append(try store.stage(url))
+ }
+ await self?.finishAddingImages(staged)
+ } catch {
+ // The batch is all-or-nothing, so the copies made before the
+ // failure are referenced by nothing and would never be deleted.
+ for attachment in staged { store.remove(attachment) }
+ await self?.finishAddingImages(error: error)
+ }
+ }
+ }
+
+ /// Attaches image bytes that have no file behind them: an image copied out
+ /// of another app arrives on the pasteboard as data, and a drag from an app
+ /// that has not written the file yet arrives as a promise.
+ public func addImageData(_ data: Data, displayName: String) {
+ guard isImageInputAvailable, !isRunning else { return }
+ let capacity = maximumImageAttachments
+ guard imageAttachments.count < capacity else {
+ imageAttachmentError = Self.imageCapacityMessage(
+ capacity: capacity, context: effectiveMaxContextTokens)
+ return
+ }
+ addingImagesCount += 1
+ imageAttachmentError = nil
+ let store = attachmentStore
+ Task.detached(priority: .userInitiated) { [weak self] in
+ do {
+ let staged = try store.stage(data: data, displayName: displayName)
+ await self?.finishAddingImages([staged])
+ } catch {
+ await self?.finishAddingImages(error: error)
+ }
+ }
+ }
+
+ static func imageCapacityMessage(capacity: Int, context: Int) -> String {
+ "At most \(capacity) image\(capacity == 1 ? "" : "s") fit in the "
+ + "\(context / 1_024)K context this session is running with. Raise "
+ + "Context in Memory and reload the model to send more."
+ }
+
+ public func reportImageAttachmentError(_ error: Error) {
+ imageAttachmentError = String(describing: error)
+ }
+
+ public func reportImageAttachmentError(_ message: String) {
+ imageAttachmentError = message
+ }
+
+ public func removeImage(id: UUID) {
+ guard !isRunning,
+ let index = imageAttachments.firstIndex(where: { $0.id == id }) else { return }
+ let attachment = imageAttachments.remove(at: index)
+ attachmentStore.remove(attachment)
+ imageAttachmentError = nil
+ }
+
+ public func clearImages() {
+ guard !isRunning else { return }
+ for attachment in imageAttachments { attachmentStore.remove(attachment) }
+ imageAttachments.removeAll()
+ imageAttachmentError = nil
+ }
+
+ private func finishAddingImages(_ staged: [AppImageAttachment]) {
+ // Two adds can be in flight at once — the picker and a drop — and each
+ // sized itself against the count it saw at admission, so the second to
+ // land can push past the cap. Re-check against the real count here and
+ // delete what does not fit, rather than leaving staged copies that
+ // nothing references.
+ defer { addingImagesCount = max(0, addingImagesCount - 1) }
+ // The counter keeps `canRun` closed until every batch lands, so a run
+ // should not be able to start underneath one. If it ever does, the run
+ // has already snapshotted its images: appending here would attach them
+ // to the *next* message with no way to take them off, which is worse
+ // than saying so. `addImages` refuses a mid-run drop the same way.
+ guard !isRunning else {
+ for attachment in staged { attachmentStore.remove(attachment) }
+ imageAttachmentError =
+ "Wait for the current run to finish before attaching images."
+ return
+ }
+ let capacity = maximumImageAttachments
+ let available = max(0, capacity - imageAttachments.count)
+ let accepted = staged.prefix(available)
+ for attachment in staged.dropFirst(accepted.count) {
+ attachmentStore.remove(attachment)
+ }
+ imageAttachments.append(contentsOf: accepted)
+ if accepted.count < staged.count {
+ imageAttachmentError = Self.imageCapacityMessage(
+ capacity: capacity, context: effectiveMaxContextTokens)
+ }
+ }
+
+ private func finishAddingImages(error: Error) {
+ addingImagesCount = max(0, addingImagesCount - 1)
+ imageAttachmentError = String(describing: error)
+ }
+
public func reloadModel() {
guard canReloadModel else { return }
beginLoad()
@@ -356,18 +757,27 @@ public final class AppModel {
}
let directory = URL(fileURLWithPath: modelPathText)
let maxContext = maxContextTokens
- let options = runtimeOptions
let forceLogitsHead = currentForceLogitsHead
let runtimeKey = AppLoadedRuntimeKey(modelDirectory: directory,
maxContextTokens: maxContext,
- options: options,
+ options: runtimeOptions,
forceLogitsHead: forceLogitsHead)
+ // The session is loaded with the same normalized options a run sends.
+ // Loading with the raw settings instead meant a control that is off but
+ // still carries a non-default value — RDADVISE off with its policy left
+ // on `bounded` — produced a loaded session no run could match, and the
+ // staleness check compares two normalized keys, so nothing ever offered
+ // the reload that would have cleared it.
+ let options = runtimeKey.options(prefillEnabled: runtimeOptions.prefillEnabled,
+ prefillChunkTokens: runtimeOptions.prefillChunkTokens)
let pendingUnload = unloadTask
loadGeneration &+= 1
let generation = loadGeneration
pendingExplicitLoadRuntimeKey = runtimeKey
error = nil
+ appliedLoadSequence = 0
loadState = .loading(.validatingDirectory)
+ let emitted = Mutex<UInt64>(0)
loadTask = Task.detached { [weak self, lifecycle, pendingUnload] in
do {
await pendingUnload?.value
@@ -376,8 +786,15 @@ public final class AppModel {
maxContextTokens: maxContext,
options: options,
forceLogitsHead: forceLogitsHead) { [weak self] state in
+ // Stamped where the phase is emitted, in order; checked
+ // where it is applied, which is not.
+ let sequence = emitted.withLock { value -> UInt64 in
+ value += 1
+ return value
+ }
Task { @MainActor in
- self?.applyLoadState(state, generation: generation)
+ self?.applyLoadState(state, generation: generation,
+ sequence: sequence)
}
}
} catch is CancellationError {
@@ -492,6 +909,185 @@ public final class AppModel {
}
}
+ public var hasPartialVisionPackDownload: Bool {
+ guard let output = try? VisionPackLocation.companionURL(
+ forTextModel: URL(fileURLWithPath: modelPathText, isDirectory: true)),
+ let paths = try? RemoteInstallPaths(outputDirectory: output.path) else {
+ return false
+ }
+ return FileManager.default.fileExists(atPath: paths.partialDirectory)
+ || FileManager.default.fileExists(atPath: paths.checkpointFile)
+ }
+
+ public var canDiscardVisionPackDownload: Bool {
+ hasPartialVisionPackDownload && canBeginVisionCompanionOperation
+ }
+
+ public var canRemoveVisionPack: Bool {
+ hasVisionPackDirectory && canBeginVisionCompanionOperation
+ }
+
+ public var hasVisionPackDirectory: Bool {
+ guard let output = try? VisionPackLocation.companionURL(
+ forTextModel: URL(fileURLWithPath: modelPathText, isDirectory: true)) else {
+ return false
+ }
+ var isDirectory: ObjCBool = false
+ return FileManager.default.fileExists(
+ atPath: output.path,
+ isDirectory: &isDirectory) && isDirectory.boolValue
+ }
+
+ public func installVisionPack() {
+ guard canInstallVisionPack else { return }
+ visionInstallCancellationRequested = false
+ visionInstallTask?.cancel()
+ visionInstaller.cancel()
+ let textModelDirectory = URL(
+ fileURLWithPath: modelPathText,
+ isDirectory: true).standardizedFileURL
+ visionInstallGeneration &+= 1
+ let generation = visionInstallGeneration
+ visionInstallState = .checking
+ visionInstallTask = Task { [weak self, visionInstaller] in
+ do {
+ for try await event in visionInstaller.install(
+ textModelDirectory: textModelDirectory) {
+ guard let self else { return }
+ self.applyVisionInstallEvent(event, generation: generation)
+ }
+ self?.finishVisionInstallStream(generation: generation)
+ } catch is CancellationError {
+ self?.finishVisionInstallCancellation(generation: generation)
+ } catch {
+ self?.finishVisionInstallFailure(error, generation: generation)
+ }
+ }
+ }
+
+ public func cancelVisionInstall() {
+ guard canCancelVisionInstall else { return }
+ visionInstallCancellationRequested = true
+ visionInstallState = .cancelling
+ visionInstaller.cancel()
+ // A cancel raised before the stream registers its own task would find no
+ // active install; cancelling the consumer terminates the stream, which
+ // routes through the same cooperative drain-to-checkpoint path.
+ visionInstallTask?.cancel()
+ }
+
+ public func activateVisionPack() {
+ guard canActivateVisionPack else { return }
+ let directory = URL(fileURLWithPath: modelPathText, isDirectory: true)
+ .standardizedFileURL
+ visionInstallCancellationRequested = false
+ visionInstallGeneration &+= 1
+ let generation = visionInstallGeneration
+ resetVisionInstallETA()
+ visionInstallState = .activating
+ visionActivationProgress = 0
+ visionInstallTask = Task { [weak self, visionInstaller] in
+ do {
+ let output = try await visionInstaller.activatePreparedInstall(
+ textModelDirectory: directory,
+ onVerifyProgress: { [weak self] fraction in
+ Task { @MainActor in
+ guard let self,
+ generation == self.visionInstallGeneration,
+ case .activating = self.visionInstallState else { return }
+ // Each hop is its own task, and tasks are not
+ // ordered against each other, so a late one must
+ // not walk the bar backwards.
+ guard fraction >= (self.visionActivationProgress ?? 0)
+ else { return }
+ self.visionActivationProgress = fraction
+ }
+ })
+ // Applied first: a progress hop still in flight is dropped
+ // once the state is no longer `.activating`, so clearing before
+ // this could be undone by a late update.
+ self?.applyVisionInstallEvent(
+ .installed(output), generation: generation)
+ self?.visionActivationProgress = nil
+ } catch is CancellationError {
+ // Cancellation can only land during verification, before
+ // anything is renamed, so the prepared pack is untouched and
+ // still activatable.
+ self?.finishVisionActivationCancelled(generation: generation)
+ self?.visionActivationProgress = nil
+ } catch {
+ self?.finishVisionInstallFailure(
+ error, generation: generation, phase: .activation)
+ self?.visionActivationProgress = nil
+ }
+ }
+ }
+
+ private func finishVisionActivationCancelled(generation: UInt64) {
+ guard generation == visionInstallGeneration else { return }
+ resetVisionInstallETA()
+ visionInstallTask = nil
+ visionInstallCancellationRequested = false
+ visionInstallState = .idle
+ refreshVisionInstallReadiness()
+ }
+
+ public func discardVisionPackDownload() {
+ guard canDiscardVisionPackDownload else { return }
+ let directory = URL(fileURLWithPath: modelPathText, isDirectory: true)
+ .standardizedFileURL
+ visionInstallCancellationRequested = false
+ visionInstallGeneration &+= 1
+ let generation = visionInstallGeneration
+ visionInstallState = .discarding
+ visionInstallTask = Task { [weak self, visionInstaller] in
+ do {
+ try await visionInstaller.discardPartialInstall(
+ textModelDirectory: directory)
+ guard let self, generation == self.visionInstallGeneration else { return }
+ self.visionInstallTask = nil
+ self.visionInstallState = .idle
+ self.refreshVisionInstallReadiness()
+ } catch {
+ self?.finishVisionInstallFailure(error, generation: generation)
+ }
+ }
+ }
+
+ /// Drives the confirmation the Model menu puts in front of `removeVisionPack`.
+ ///
+ /// The Inspector hides its own Remove button once the pack is installed, so
+ /// the menu item is the only reachable way to delete 1.14 GB — and it called
+ /// straight through, with the dialog sitting on an unreachable branch.
+ public func requestVisionPackRemoval() {
+ guard canRemoveVisionPack else { return }
+ isConfirmingVisionPackRemoval = true
+ }
+
+ public func removeVisionPack() {
+ isConfirmingVisionPackRemoval = false
+ guard canRemoveVisionPack else { return }
+ let directory = URL(fileURLWithPath: modelPathText, isDirectory: true)
+ .standardizedFileURL
+ visionInstallCancellationRequested = false
+ visionInstallGeneration &+= 1
+ let generation = visionInstallGeneration
+ visionInstallState = .discarding
+ visionInstallTask = Task { [weak self, visionInstaller] in
+ do {
+ try await visionInstaller.removeInstalled(
+ textModelDirectory: directory)
+ guard let self, generation == self.visionInstallGeneration else { return }
+ self.visionInstallTask = nil
+ self.visionInstallState = .idle
+ self.visionInstallationStatus = .missing
+ self.refreshVisionInstallReadiness()
+ } catch {
+ self?.finishVisionInstallFailure(error, generation: generation)
+ }
+ }
+ }
+
public func refreshInstallReadiness() {
refreshInstallReadiness(
at: URL(fileURLWithPath: modelPathText, isDirectory: true).standardizedFileURL)
@@ -502,6 +1098,7 @@ public final class AppModel {
.standardizedFileURL
modelPathText = directory.path
refreshInstallReadiness(at: directory)
+ refreshVisionInstallReadiness(at: directory)
}
private func refreshInstallReadiness(at outputDirectory: URL) {
@@ -521,6 +1118,213 @@ public final class AppModel {
}
}
+ public func refreshVisionInstallReadiness() {
+ refreshVisionInstallReadiness(
+ at: URL(fileURLWithPath: modelPathText, isDirectory: true)
+ .standardizedFileURL)
+ }
+
+ private func refreshVisionInstallReadiness(at textModelDirectory: URL) {
+ visionInstallationStatus = AppVisionPackInstallationProbe.status(
+ at: textModelDirectory)
+ // Removing the companion leaves any attached image unsendable, and the
+ // composer would keep offering it with nothing able to encode it.
+ // Only once the dust has settled: the probe verifies the pack on disk,
+ // and a companion operation renames that directory underneath it, so
+ // refreshing mid-operation can briefly report no image support. Acting
+ // on that would delete images the user had staged.
+ if !isImageInputAvailable, !isVisionCompanionOperationInProgress,
+ !imageAttachments.isEmpty {
+ for attachment in imageAttachments { attachmentStore.remove(attachment) }
+ imageAttachments.removeAll()
+ // Say so. Clearing the error alongside the images removed them and
+ // the only explanation for their absence in one step, so the
+ // composer just quietly emptied itself.
+ imageAttachmentError =
+ "Image support is unavailable, so the attached images were removed."
+ }
+ guard isModelInstalled else {
+ visionInstallReadiness = .failed("Install the text model first")
+ return
+ }
+ guard !isVisionPackInstalled else { return }
+ if visionInstaller.preparedInstallIsValid(
+ textModelDirectory: textModelDirectory) {
+ let output = try? VisionPackLocation.companionURL(
+ forTextModel: textModelDirectory)
+ // A pack that failed to activate must not be re-offered for
+ // activation: `preparedInstallIsValid` does not hash the weights,
+ // so a corrupt pack still looks ready and the user would loop
+ // between Activate and the same failure.
+ let reportedBroken: Bool
+ switch visionInstallState {
+ case .recoverable, .failed: reportedBroken = true
+ default: reportedBroken = false
+ }
+ if let output, !isInstallingVisionPack, !reportedBroken {
+ visionInstallState = .readyToActivate(output)
+ }
+ }
+ visionInstallReadiness = .checking
+ do {
+ let requirement = try visionInstaller.checkInstallRequirement(
+ textModelDirectory: textModelDirectory)
+ visionInstallReadiness = requirement.canInstall
+ ? .ready(requirement)
+ : .insufficientSpace(requirement)
+ } catch {
+ visionInstallReadiness = .failed("\(error)")
+ }
+ }
+
+ private func applyVisionInstallEvent(
+ _ event: AppModelInstallEvent,
+ generation: UInt64
+ ) {
+ guard generation == visionInstallGeneration else { return }
+ if visionInstallCancellationRequested {
+ switch event {
+ case .readyToActivate, .installed:
+ // Work that finished before the cancel landed is reported as it
+ // actually ended, not as a pause.
+ visionInstallCancellationRequested = false
+ default:
+ return
+ }
+ }
+ switch event {
+ case .checking:
+ resetVisionInstallETA()
+ visionInstallState = .checking
+ case .downloadingMetadata:
+ resetVisionInstallETA()
+ visionInstallState = .downloadingMetadata
+ case .planning:
+ resetVisionInstallETA()
+ visionInstallState = .planning
+ case .reservingOutput:
+ resetVisionInstallETA()
+ visionInstallState = .reservingOutput
+ case .copyingPayload(let reused, let downloaded, let total):
+ visionInstallState = .copyingPayload(
+ reusedBytes: reused,
+ downloadedThisRunBytes: downloaded,
+ totalBytes: total)
+ updateVisionInstallETA(
+ reusedBytes: reused,
+ downloadedThisRunBytes: downloaded,
+ totalBytes: total)
+ case .hashingOutput(let file):
+ resetVisionInstallETA()
+ visionInstallState = .hashingOutput(file)
+ case .finalizing:
+ resetVisionInstallETA()
+ visionInstallState = .finalizing
+ case .readyToActivate(let directory):
+ resetVisionInstallETA()
+ visionInstallState = .readyToActivate(directory)
+ visionInstallTask = nil
+ case .installed:
+ resetVisionInstallETA()
+ let textModelDirectory = URL(
+ fileURLWithPath: modelPathText,
+ isDirectory: true).standardizedFileURL
+ visionInstallationStatus = AppVisionPackInstallationProbe.status(
+ at: textModelDirectory)
+ guard isVisionPackInstalled else {
+ finishVisionInstallFailure(
+ RepackError.configurationInvalid(
+ detail: "completed vision install failed verification"),
+ generation: generation)
+ return
+ }
+ visionInstallState = .installed(modelDirectory: textModelDirectory)
+ visionInstallTask = nil
+ }
+ }
+
+ private func finishVisionInstallStream(generation: UInt64) {
+ guard generation == visionInstallGeneration,
+ visionInstallTask != nil else { return }
+ if visionInstallCancellationRequested || visionInstallState == .cancelling {
+ finishVisionInstallCancellation(generation: generation)
+ } else if !isVisionPackInstalled {
+ finishVisionInstallFailure(
+ RepackError.configurationInvalid(
+ detail: "vision installer ended before completion"),
+ generation: generation)
+ }
+ }
+
+ private func finishVisionInstallCancellation(generation: UInt64) {
+ guard generation == visionInstallGeneration else { return }
+ resetVisionInstallETA()
+ visionInstallCancellationRequested = false
+ visionInstallTask = nil
+ visionInstallState = .cancelled
+ refreshVisionInstallReadiness()
+ }
+
+ /// Which phase failed. Only a download failure may leave a prepared pack
+ /// that is worth activating; a verification failure must never send the
+ /// user back to Activate, or the same corrupt pack is offered forever.
+ enum VisionFailurePhase { case download, activation }
+
+ func finishVisionInstallFailure(
+ _ error: Error, generation: UInt64,
+ phase: VisionFailurePhase = .download
+ ) {
+ guard generation == visionInstallGeneration else { return }
+ // An error raised because the user cancelled is a pause with saved
+ // progress, not an installation failure.
+ guard !visionInstallCancellationRequested else {
+ finishVisionInstallCancellation(generation: generation)
+ return
+ }
+ resetVisionInstallETA()
+ visionInstallTask = nil
+ let hasSavedDownload = hasPartialVisionPackDownload
+ let textModelDirectory = URL(
+ fileURLWithPath: modelPathText,
+ isDirectory: true).standardizedFileURL
+ // A download that finished and verifies is activatable whatever went
+ // wrong afterwards. Reporting it as "needs attention" hid the Activate
+ // button behind a Resume that only repeats work already done. The one
+ // failure that must not come back here is verification itself, or the
+ // same corrupt pack is offered forever — but a lock held by another
+ // process is contention, not corruption.
+ let isContention: Bool
+ if let repackError = error as? RepackError, case .installBusy = repackError {
+ isContention = true
+ } else {
+ isContention = false
+ }
+ if phase == .download || isContention, hasSavedDownload,
+ let output = try? VisionPackLocation.companionURL(
+ forTextModel: textModelDirectory),
+ visionInstaller.preparedInstallIsValid(
+ textModelDirectory: textModelDirectory) {
+ visionInstallState = .readyToActivate(output)
+ refreshVisionInstallReadiness(at: textModelDirectory)
+ return
+ }
+ visionInstallState = hasSavedDownload
+ ? .recoverable("\(error)")
+ : .failed("\(error)")
+ if let repackError = error as? RepackError,
+ case .diskSpaceInsufficient(let path, let required, let available) = repackError {
+ visionInstallReadiness = .insufficientSpace(AppModelInstallRequirement(
+ probePath: path,
+ requiredBytes: required,
+ availableBytes: available))
+ } else {
+ refreshVisionInstallReadiness()
+ if hasSavedDownload {
+ visionInstallState = .recoverable("\(error)")
+ }
+ }
+ }
+
private func applyInstallEvent(_ event: AppModelInstallEvent, generation: UInt64) {
guard generation == installGeneration else { return }
switch event {
@@ -551,6 +1355,11 @@ public final class AppModel {
case .finalizing:
resetInstallETA()
installState = .finalizing
+ case .readyToActivate:
+ finishInstallFailure(
+ RepackError.configurationInvalid(
+ detail: "text installer returned a vision-only activation event"),
+ generation: generation)
case .installed(let directory):
resetInstallETA()
let directory = directory.standardizedFileURL
@@ -567,6 +1376,7 @@ public final class AppModel {
installTask = nil
modelPathText = directory.path
loadState = .notLoaded
+ refreshVisionInstallReadiness(at: directory)
}
}
@@ -615,6 +1425,27 @@ public final class AppModel {
installETAText = nil
}
+ private func updateVisionInstallETA(
+ reusedBytes: UInt64,
+ downloadedThisRunBytes: UInt64,
+ totalBytes: UInt64
+ ) {
+ let observation = DownloadETAObservation(
+ reusedBytes: reusedBytes,
+ downloadedThisRunBytes: downloadedThisRunBytes,
+ totalBytes: totalBytes)
+ let presentation = visionInstallETAEstimator.update(
+ observation, timestamp: installETATimestamp)
+ visionInstallETAPresentation = presentation
+ visionInstallETAText = DownloadETAFormatter.string(for: presentation)
+ }
+
+ private func resetVisionInstallETA() {
+ visionInstallETAEstimator.reset()
+ visionInstallETAPresentation = .hidden
+ visionInstallETAText = nil
+ }
+
private func setInstallETAPresentation(
_ presentation: DownloadETAPresentation
) {
@@ -628,7 +1459,13 @@ public final class AppModel {
forModelDirectory: modelDirectory)
runtimeOptions = AppRuntimeOptions(
expertCacheSlots: settings.expertCacheSlots,
- prefillEnabled: settings.prefillEnabled)
+ prefillEnabled: settings.prefillEnabled,
+ rdadvisePolicy: settings.rdadvisePolicy,
+ // Pinned for the same reason as `init`: the app always releases the
+ // image tower. Reading the persisted value here would let a
+ // `keepReady` written by an older build resurrect ~1 GB of resident
+ // tower on a machine with no control that shows or clears it.
+ visionResidencyPolicy: .onDemand)
maxContextTokens = settings.contextTokens
temperature = settings.temperature
topKEnabled = settings.topKEnabled
@@ -638,6 +1475,7 @@ public final class AppModel {
newlineShortcut = settings.newlineShortcut
showPromptExamples = settings.showPromptExamples
sentPromptBehavior = settings.sentPromptBehavior
+ loadModelOnLaunch = settings.loadModelOnLaunch
}
private func persistSettings() {
@@ -653,7 +1491,10 @@ public final class AppModel {
prefillEnabled: runtimeOptions.prefillEnabled,
newlineShortcut: newlineShortcut,
showPromptExamples: showPromptExamples,
- sentPromptBehavior: sentPromptBehavior)
+ sentPromptBehavior: sentPromptBehavior,
+ visionResidencyPolicy: runtimeOptions.visionResidencyPolicy,
+ rdadvisePolicy: runtimeOptions.rdadvisePolicy,
+ loadModelOnLaunch: loadModelOnLaunch)
let modelDirectory = URL(fileURLWithPath: modelPathText, isDirectory: true)
try? MacAppSettingsFileStore.save(
settings,
@@ -684,14 +1525,33 @@ public final class AppModel {
applyLoadState(state, generation: loadGeneration)
}
- private func applyLoadState(_ state: AppModelLoadState, generation: UInt64) {
+ /// `sequence` orders the phases a load emits. It is 0 for states this model
+ /// raises itself, which bypass the ordering check.
+ func applyLoadState(_ state: AppModelLoadState, generation: UInt64,
+ sequence: UInt64 = 0) {
guard generation == loadGeneration else { return }
+ if sequence > 0 {
+ guard sequence > appliedLoadSequence else { return }
+ appliedLoadSequence = sequence
+ }
if case .ready(let directory, _) = state,
directory.standardizedFileURL.path
!= URL(fileURLWithPath: modelPathText).standardizedFileURL.path {
return
}
loadState = state
+ // An outcome closes the load. Phases emitted before it but delivered
+ // after it must not reopen one that has already finished: `.failed` is
+ // raised here at sequence 0, so it never advanced the counter, and a
+ // late `.loading` hop could put the UI back into a load with no task
+ // left to cancel and no way to start another. `beginLoad` resets the
+ // counter, so the seal lasts exactly one load.
+ switch state {
+ case .notLoaded, .ready, .failed:
+ appliedLoadSequence = .max
+ case .loading, .cancelling, .unloading:
+ break
+ }
switch state {
case .notLoaded:
loadedRuntimeKey = nil
@@ -702,6 +1562,9 @@ public final class AppModel {
?? activeRunRuntimeKey
?? currentRuntimeKey
pendingExplicitLoadRuntimeKey = nil
+ // The freshly loaded model's footprint, so the figure is right
+ // before the first generation rather than after it.
+ sampleLiveMemory()
_ = seconds
case .failed(let loadError):
pendingExplicitLoadRuntimeKey = nil
@@ -709,9 +1572,61 @@ public final class AppModel {
}
}
+ /// Releases the transcript's own references to the images it was showing.
+ /// They are separate files from the composer's, so nothing else frees them.
+ private func releaseTranscriptImages() {
+ for attachment in outputImageAttachments { attachmentStore.remove(attachment) }
+ outputImageAttachments = []
+ }
+
+ /// Deletes every file this session staged. Called when the app is quitting,
+ /// which is the only moment they are all certainly unwanted.
+ public func releaseAllAttachments() {
+ releaseTranscriptImages()
+ for attachment in imageAttachments { attachmentStore.remove(attachment) }
+ imageAttachments.removeAll()
+ attachmentStore.removeAll()
+ }
+
+ /// Memory comes from the process doing the work: the decode service when
+ /// there is one, this process otherwise.
+ private func sampleLiveMemory() {
+ if let reporter = client as? any AppInferenceMemoryReporting {
+ if let bytes = reporter.currentInferenceMemoryBytes {
+ liveMemoryBytes = bytes
+ }
+ if let resident = reporter.currentInferenceResidentBytes {
+ liveResidentBytes = resident
+ }
+ // Refreshed on every sample, so the tower figure tracks a run
+ // instead of appearing only in its final diagnostics.
+ if let tower = reporter.currentInferenceTowerBytes {
+ visionTowerMappedBytes = tower
+ }
+ } else {
+ liveMemoryBytes = memorySampler.sample()
+ // The occupied figure, not the footprint again: this row is the one
+ // that includes the mapped weights, and feeding it the footprint
+ // made both numbers report the same thing.
+ liveResidentBytes = memorySampler.occupiedSample()
+ }
+ }
+
+ /// Resident bytes for display, on the same terms as
+ /// `currentProcessMemoryBytes`.
+ public var currentProcessResidentBytes: UInt64? {
+ guard loadState.isReady || isRunning else { return nil }
+ if let liveResidentBytes { return liveResidentBytes }
+ if let reporter = client as? any AppInferenceMemoryReporting {
+ return reporter.currentInferenceResidentBytes
+ }
+ return memorySampler.occupiedSample()
+ }
+
public func clearOutput() {
guard !isRunning else { return }
outputPromptText = ""
+ releaseTranscriptImages()
outputText = ""
generationTranscriptMailbox?.reset()
diagnostics = nil
@@ -720,7 +1635,7 @@ public final class AppModel {
public func run() {
guard canRun else { return }
- let request: AppGenerationRequest
+ var request: AppGenerationRequest
do {
request = try makeRequest()
} catch let appError as AppInferenceError {
@@ -731,10 +1646,34 @@ public final class AppModel {
self.error = appError
return
}
+
+ // The run reads the transcript's own hard links rather than the
+ // composer's files, so clearing the composer below cannot delete an
+ // image this request has not opened yet. One set of files, one owner.
+ // A failed retain leaves no reference that is guaranteed to outlive
+ // the composer, so the run is refused instead of started against files
+ // that are about to be removed.
+ var retained: [AppImageAttachment] = []
+ do {
+ for attachment in request.imageAttachments {
+ retained.append(try attachmentStore.retain(attachment))
+ }
+ } catch {
+ for attachment in retained { attachmentStore.remove(attachment) }
+ imageAttachmentError = String(describing: error)
+ self.error = .invalidRequest(
+ "Could not prepare the attached images for this run: \(error)")
+ return
+ }
+ request.imageAttachments = retained
+
persistSettings()
generationTranscriptMailbox?.reset()
+ runIdentity &+= 1
outputPromptText = request.prompt
+ releaseTranscriptImages()
+ outputImageAttachments = retained
outputText = ""
diagnostics = nil
error = nil
@@ -749,11 +1688,19 @@ public final class AppModel {
liveElapsedDecodeSeconds = 0
livePrefillDone = 0
livePrefillTotal = 0
- liveMemoryBytes = nil
+ sampleLiveMemory()
phase = .prefill
runState = .running
if sentPromptBehavior == .clear {
promptText = ""
+ // Images used to survive a cleared prompt, so the next Run silently
+ // re-attached them to a completely different message. Dropping them
+ // is safe because the request above was repointed at the retained
+ // links: removing these files cannot pull the ground out from under
+ // a run that has not opened its images yet.
+ for attachment in imageAttachments { attachmentStore.remove(attachment) }
+ imageAttachments.removeAll()
+ imageAttachmentError = nil
}
runTask = Task.detached { [weak self, client, request] in
@@ -777,39 +1724,50 @@ public final class AppModel {
}
public func makeRequest() throws -> AppGenerationRequest {
+ // A run executes against the session that is actually loaded. Sending
+ // the current settings instead meant that changing Context, Slots or
+ // image residency and pressing Generate — without reloading first —
+ // was refused outright with "generation runtime options do not match
+ // the loaded session". The settings still apply on reload, which is
+ // what the Memory section promises; they simply no longer break the
+ // run in the meantime.
+ let effective = loadedRuntimeKey ?? currentRuntimeKey
let request = AppGenerationRequest(
modelDirectory: URL(fileURLWithPath: modelPathText),
prompt: promptText,
- maxNewTokens: maxNewTokensOverride ?? maxContextTokens,
- maxContextTokens: maxContextTokens,
+ imageAttachments: imageAttachments,
+ maxNewTokens: maxNewTokensOverride ?? effective.maxContextTokens,
+ maxContextTokens: effective.maxContextTokens,
temperature: Float(temperature),
topK: topKEnabled ? topK : nil,
topP: topKEnabled && topPEnabled ? Float(topP) : nil,
repetitionPenalty: 1.0,
- runtimeOptions: runtimeOptions)
+ runtimeOptions: effective.options(
+ prefillEnabled: runtimeOptions.prefillEnabled,
+ prefillChunkTokens: runtimeOptions.prefillChunkTokens))
try request.validate(requireModelDirectory: true)
return request
}
func apply(_ event: AppInferenceEvent) {
switch event {
+ case .memorySample:
+ sampleLiveMemory()
case .prefillProgress(let done, let total):
phase = .prefill
livePrefillDone = done
livePrefillTotal = total
+ sampleLiveMemory()
case .token(let token):
phase = .decode
liveTokenCount = token.index + 1
liveElapsedDecodeSeconds = token.elapsedDecodeSeconds
- if let reporter = client as? any AppInferenceMemoryReporting {
- liveMemoryBytes = reporter.currentInferenceMemoryBytes
- } else {
- liveMemoryBytes = memorySampler.sample()
- }
+ sampleLiveMemory()
if !token.textDelta.isEmpty {
outputText += token.textDelta
}
case .finished(let diagnostics):
+ visionTowerMappedBytes = diagnostics.visionTowerMappedBytes
finishSuccessfully(diagnostics)
case .cancelled(let diagnostics):
finishCancelled(diagnostics)
diff --git a/Sources/TurboFieldfareApp/Core/State/AppModelLoadState.swift b/Sources/TurboFieldfareApp/Core/State/AppModelLoadState.swift
index e3da1037..7db2fbb3 100644
--- a/Sources/TurboFieldfareApp/Core/State/AppModelLoadState.swift
+++ b/Sources/TurboFieldfareApp/Core/State/AppModelLoadState.swift
@@ -5,6 +5,9 @@ public enum AppModelLoadPhase: Equatable, Sendable {
case tokenizer
case verifyingWeights
case preparingRunner
+ /// Keep Ready maps the whole image tower during the load rather than on the
+ /// first image, so the load has a phase for it.
+ case mappingImageTower
public var label: String {
switch self {
@@ -12,6 +15,7 @@ public enum AppModelLoadPhase: Equatable, Sendable {
case .tokenizer: return "Loading tokenizer"
case .verifyingWeights: return "Verifying weights"
case .preparingRunner: return "Preparing runner"
+ case .mappingImageTower: return "Mapping image tower"
}
}
}
diff --git a/Sources/TurboFieldfareApp/Core/State/AppPresentationState.swift b/Sources/TurboFieldfareApp/Core/State/AppPresentationState.swift
index 34ca18a2..d23e6ddc 100644
--- a/Sources/TurboFieldfareApp/Core/State/AppPresentationState.swift
+++ b/Sources/TurboFieldfareApp/Core/State/AppPresentationState.swift
@@ -30,6 +30,11 @@ public struct AppPresentationSnapshot: Equatable, Sendable {
public var livePrefillDone: Int
public var livePrefillTotal: Int
public var lastStopReason: AppStopReason?
+ /// `canLoadModel` and its siblings refuse while a companion operation runs,
+ /// so the snapshot has to carry it: without it this resolved to
+ /// "Installed · Not loaded" with a `.load` action, and the banner rendered a
+ /// fully enabled button that did nothing for the whole transfer.
+ public var isVisionCompanionOperationInProgress: Bool
public init(requiresInstallation: Bool,
installState: AppModelInstallState,
@@ -41,7 +46,8 @@ public struct AppPresentationSnapshot: Equatable, Sendable {
generationPhase: AppGenerationPhase,
livePrefillDone: Int = 0,
livePrefillTotal: Int = 0,
- lastStopReason: AppStopReason? = nil) {
+ lastStopReason: AppStopReason? = nil,
+ isVisionCompanionOperationInProgress: Bool = false) {
self.requiresInstallation = requiresInstallation
self.installState = installState
self.installReadiness = installReadiness
@@ -53,6 +59,7 @@ public struct AppPresentationSnapshot: Equatable, Sendable {
self.livePrefillDone = livePrefillDone
self.livePrefillTotal = livePrefillTotal
self.lastStopReason = lastStopReason
+ self.isVisionCompanionOperationInProgress = isVisionCompanionOperationInProgress
}
}
@@ -134,6 +141,13 @@ public struct AppPresentationState: Equatable, Sendable {
return Self(label: "Model required")
}
+ // Every model action is refused for the duration, so offering one here
+ // would be offering a button that does nothing.
+ if snapshot.isVisionCompanionOperationInProgress {
+ return Self(label: "Preparing image support",
+ severity: .active, showsActivity: true)
+ }
+
switch snapshot.loadState {
case .loading(let phase):
return Self(label: phase.label, severity: .active, showsActivity: true,
@@ -192,9 +206,10 @@ public struct AppPresentationState: Equatable, Sendable {
case .copyingPayload: return "Downloading model"
case .hashingOutput(let file): return "Verifying \(file)"
case .finalizing: return "Finalizing installation"
+ case .activating: return "Activating image support"
case .cancelling: return "Cancelling installation"
case .discarding: return "Discarding download"
- case .idle, .cancelled, .recoverable, .installed, .failed:
+ case .idle, .cancelled, .readyToActivate, .recoverable, .installed, .failed:
return "Model required"
}
}
diff --git a/Sources/TurboFieldfareApp/Mac/App/TurboFieldfareMacApp.swift b/Sources/TurboFieldfareApp/Mac/App/TurboFieldfareMacApp.swift
index d562fe2e..f7f7c86d 100644
--- a/Sources/TurboFieldfareApp/Mac/App/TurboFieldfareMacApp.swift
+++ b/Sources/TurboFieldfareApp/Mac/App/TurboFieldfareMacApp.swift
@@ -7,6 +7,13 @@ import SwiftUI
// executable (no .app bundle): Dock icon, click-to-activate, full main menu
// with Quit (Cmd+Q).
private final class ForegroundAppDelegate: NSObject, NSApplicationDelegate {
+ /// Set by the scene so quitting can release this session's staged images.
+ @MainActor static var model: AppModel?
+
+ func applicationWillTerminate(_ notification: Notification) {
+ MainActor.assumeIsolated { Self.model?.releaseAllAttachments() }
+ }
+
func applicationDidFinishLaunching(_ notification: Notification) {
NSApp.setActivationPolicy(.regular)
if let icon = MacAppIcon.load() {
@@ -27,15 +34,38 @@ struct TurboFieldfareMacApp: App {
@State private var model: AppModel
init() {
- _model = State(initialValue: AppModel(
+ let model = AppModel(
client: DecodeServiceInferenceClient(),
- settingsPersistenceEnabled: true))
+ visionRuntimeSupported: AppModel.currentDeviceSupportsVisionRuntime,
+ settingsPersistenceEnabled: true)
+ _model = State(initialValue: model)
+ MainActor.assumeIsolated { ForegroundAppDelegate.model = model }
}
var body: some Scene {
Window("TurboFieldfare", id: "main") {
RootView(model: model)
.frame(minWidth: 1040, minHeight: 560)
+ // Once, when the window first appears: the setting is read
+ // from disk in init, and loadModelAtLaunchIfEnabled ignores a
+ // model that is missing or already busy.
+ .task { model.loadModelAtLaunchIfEnabled() }
+ // On the window, not in the Inspector: the menu item works
+ // whether or not the Inspector is open.
+ .confirmationDialog(
+ "Remove downloaded image support?",
+ isPresented: Bindable(model).isConfirmingVisionPackRemoval,
+ titleVisibility: .visible
+ ) {
+ Button("Remove Image Support", role: .destructive) {
+ model.removeVisionPack()
+ }
+ Button("Cancel", role: .cancel) {}
+ } message: {
+ Text("Text generation will continue to work. "
+ + "Getting image support back means downloading the "
+ + "pack again.")
+ }
}
.windowStyle(.hiddenTitleBar)
.defaultSize(width: 1040, height: 720)
@@ -66,6 +96,13 @@ struct TurboFieldfareMacApp: App {
Divider()
Button("Reveal Model in Finder", action: revealModel)
.disabled(modelRevealTarget == .unavailable)
+ // The Inspector shows image support only while there is
+ // something to decide, so reclaiming the pack lives here:
+ // rare, deliberate, and destructive. Which is why it asks
+ // first — this is the only reachable way to delete the pack,
+ // and it used to call straight through.
+ Button("Remove Image Support", action: model.requestVisionPackRemoval)
+ .disabled(!model.canRemoveVisionPack)
}
CommandMenu("Settings") {
Picker("Send Message With", selection: newlineShortcutBinding) {
@@ -82,6 +119,10 @@ struct TurboFieldfareMacApp: App {
Text(behavior.settingsLabel).tag(behavior)
}
}
+ Picker("Load Model At Launch", selection: loadModelOnLaunchBinding) {
+ Text("Off").tag(false)
+ Text("On").tag(true)
+ }
}
}
}
@@ -119,6 +160,14 @@ struct TurboFieldfareMacApp: App {
}
}
+ private var loadModelOnLaunchBinding: Binding<Bool> {
+ Binding {
+ model.loadModelOnLaunch
+ } set: { enabled in
+ model.setLoadModelOnLaunch(enabled)
+ }
+ }
+
private var sentPromptBehaviorBinding: Binding<AppSentPromptBehavior> {
Binding {
model.sentPromptBehavior
diff --git a/Sources/TurboFieldfareApp/Mac/Components/InfoPopoverButton.swift b/Sources/TurboFieldfareApp/Mac/Components/InfoPopoverButton.swift
new file mode 100644
index 00000000..923e4974
--- /dev/null
+++ b/Sources/TurboFieldfareApp/Mac/Components/InfoPopoverButton.swift
@@ -0,0 +1,33 @@
+import SwiftUI
+
+/// An `info.circle` that both hovers and clicks: the tooltip alone was
+/// invisible, so the explanation it carried never reached the people who read
+/// the figure next to it as a bug.
+struct InfoPopoverButton: View {
+ let subject: String
+ let text: String
+ var arrowEdge: Edge = .trailing
+ @State private var isShowingPopover = false
+
+ var body: some View {
+ Button {
+ isShowingPopover.toggle()
+ } label: {
+ Image(systemName: "info.circle")
+ .font(.caption2)
+ .foregroundStyle(.tertiary)
+ .frame(width: 16, height: 16)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ .help(text)
+ .popover(isPresented: $isShowingPopover, arrowEdge: arrowEdge) {
+ Text(text)
+ .font(.callout)
+ .frame(width: 280, alignment: .leading)
+ .padding()
+ }
+ .accessibilityLabel("\(subject) information")
+ .accessibilityHint(text)
+ }
+}
diff --git a/Sources/TurboFieldfareApp/Mac/Diagnostics/InspectorView.swift b/Sources/TurboFieldfareApp/Mac/Diagnostics/InspectorView.swift
index c38ea226..10a26d6c 100644
--- a/Sources/TurboFieldfareApp/Mac/Diagnostics/InspectorView.swift
+++ b/Sources/TurboFieldfareApp/Mac/Diagnostics/InspectorView.swift
@@ -1,5 +1,6 @@
import AppKit
import TurboFieldfareAppCore
+import TurboFieldfareMacPresentation
import SwiftUI
struct InspectorView: View {
@@ -8,6 +9,13 @@ struct InspectorView: View {
var body: some View {
Form {
modelSection
+ // Second, beside Model: image support is an install concern, not a
+ // diagnostic. Last put it under the runner diagnostics and below the
+ // fold, where the one screen that must mention it - the empty state
+ // before any model exists - could not.
+ if showsVisionSection {
+ visionSection
+ }
memorySection
generationSection
runtimeSection
@@ -18,6 +26,182 @@ struct InspectorView: View {
.background(Color(nsColor: .windowBackgroundColor))
}
+ /// Shown while it has something to say, hidden once it does not. Unlike
+ /// root this does not require an installed text model: the empty state is
+ /// exactly where someone decides whether this app does what they need, and
+ /// hiding image support until after a 14.62 GB download meant nobody found
+ /// out it existed. It still collapses once the pack is installed and healthy.
+ private var showsVisionSection: Bool {
+ VisionSectionVisibility.shows(
+ visionRuntimeEnabled: model.visionRuntimeEnabled,
+ visionRuntimeSupported: model.isVisionRuntimeSupported,
+ isModelInstalled: model.isModelInstalled,
+ isVisionPackInstalled: model.isVisionPackInstalled,
+ isCompanionOperationInProgress: model.isVisionCompanionOperationInProgress,
+ installState: model.visionInstallState)
+ }
+
+ private var visionSection: some View {
+ Section("Image Support") {
+ LabeledContent("State") {
+ Text(visionStatusLabel)
+ .font(.caption)
+ .foregroundStyle(visionStatusColor)
+ }
+ if model.isVisionRuntimeSupported && !model.isVisionPackInstalled {
+ LabeledContent("Download") {
+ Text(MetricFormat.storage(
+ model.visionInstallDescriptor.approximateDownloadBytes))
+ .font(.caption.monospacedDigit())
+ .foregroundStyle(.secondary)
+ }
+ }
+ if let fraction = model.visionInstallProgressFraction {
+ ProgressView(value: fraction)
+ .accessibilityValue(visionAccessibleProgress(fraction: fraction))
+ HStack(alignment: .firstTextBaseline) {
+ Text(MetricFormat.percent(fraction * 100))
+ Spacer(minLength: 8)
+ if let eta = model.visionInstallETAText {
+ Text(eta)
+ }
+ }
+ .font(.caption.monospacedDigit())
+ .foregroundStyle(.secondary)
+ } else if model.isInstallingVisionPack {
+ ProgressView()
+ .controlSize(.small)
+ if let eta = model.visionInstallETAText {
+ Text(eta)
+ .font(.caption.monospacedDigit())
+ .foregroundStyle(.secondary)
+ }
+ }
+ if !model.isVisionRuntimeSupported {
+ Text("Image support requires an M2 or newer Mac. "
+ + "Text generation remains available on this Mac.")
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ } else if case .failed(let message) = model.visionInstallState {
+ Text(message)
+ .font(.caption)
+ .foregroundStyle(.red)
+ } else if case .recoverable(let message) = model.visionInstallState {
+ Text(message)
+ .font(.caption)
+ .foregroundStyle(.orange)
+ } else if case .partial(let message) = model.visionInstallationStatus,
+ !model.isInstallingVisionPack {
+ Text(message)
+ .font(.caption)
+ .foregroundStyle(.orange)
+ } else if case .unsupportedLayout = model.visionInstallationStatus {
+ Text("Image support needs a model directory named "
+ + "“<name>.gturbo”, which is where the companion pack lives.")
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ } else if case .failed(let message) = model.visionInstallReadiness,
+ !model.isInstallingVisionPack {
+ Text(message)
+ .font(.caption)
+ .foregroundStyle(.orange)
+ } else if case .insufficientSpace(let requirement) = model.visionInstallReadiness,
+ !model.isInstallingVisionPack {
+ Text("Free \(MetricFormat.storage(requirement.shortfallBytes)) more storage.")
+ .font(.caption)
+ .foregroundStyle(.orange)
+ } else if model.isVisionCompanionOperationInProgress {
+ Text("Model actions stay unavailable until this finishes. "
+ + "Your prompt, images, and transcript are kept.")
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ } else if !model.isVisionPackInstalled && model.loadState.isReady {
+ Text("Unload the model before preparing image support.")
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ } else if model.isVisionPackInstalled && model.loadState.isReady {
+ Text("Unload the model before removing image support.")
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ }
+
+ HStack {
+ if model.isInstallingVisionPack {
+ Button("Cancel", action: model.cancelVisionInstall)
+ .disabled(!model.canCancelVisionInstall)
+ } else if case .readyToActivate = model.visionInstallState {
+ Button("Discard", role: .destructive) {
+ model.discardVisionPackDownload()
+ }
+ .disabled(!model.canDiscardVisionPackDownload)
+ if model.isVisionRuntimeSupported {
+ Button("Activate", action: model.activateVisionPack)
+ .buttonStyle(.borderedProminent)
+ .disabled(!model.canActivateVisionPack)
+ }
+ } else if model.isVisionPackInstalled {
+ Button("Remove", role: .destructive) {
+ model.requestVisionPackRemoval()
+ }
+ .disabled(!model.canRemoveVisionPack)
+ } else {
+ if model.hasVisionPackDirectory {
+ Button("Remove", role: .destructive) {
+ model.requestVisionPackRemoval()
+ }
+ .disabled(!model.canRemoveVisionPack)
+ }
+ if model.hasPartialVisionPackDownload {
+ Button("Discard", role: .destructive) {
+ model.discardVisionPackDownload()
+ }
+ .disabled(!model.canDiscardVisionPackDownload)
+ }
+ if model.isVisionRuntimeSupported {
+ Button(visionInstallButtonLabel) {
+ model.installVisionPack()
+ }
+ .buttonStyle(.borderedProminent)
+ .disabled(!model.canInstallVisionPack)
+ }
+ }
+ }
+ }
+ }
+
+ private var visionInstallButtonLabel: String {
+ if model.hasPartialVisionPackDownload { return "Resume" }
+ if model.hasVisionPackDirectory { return "Repair" }
+ return "Download"
+ }
+
+ private func visionAccessibleProgress(fraction: Double) -> String {
+ let percent = MetricFormat.percent(fraction * 100)
+ guard let eta = model.visionInstallETAText else { return percent }
+ return "\(percent), \(eta)"
+ }
+
+ private var visionStatusLabel: String {
+ guard model.isVisionRuntimeSupported else { return "Requires M2 or newer" }
+ if model.visionInstallState != .idle {
+ return model.visionInstallPhaseLabel
+ }
+ switch model.visionInstallationStatus {
+ case .missing: return "Not installed"
+ case .partial: return "Needs repair"
+ case .complete: return "Installed"
+ case .unsupportedLayout: return "Not available for this model"
+ }
+ }
+
+ private var visionStatusColor: Color {
+ guard model.isVisionRuntimeSupported else { return .secondary }
+ switch model.visionInstallationStatus {
+ case .partial: return .orange
+ case .missing, .complete, .unsupportedLayout: return .secondary
+ }
+ }
+
private var modelSection: some View {
Section("Model") {
LabeledContent("Path") {
@@ -67,7 +251,8 @@ struct InspectorView: View {
}
}
}
- .disabled(model.isRunning || model.isInstallingModel)
+ .disabled(model.isRunning || model.isInstallingModel
+ || model.isVisionCompanionOperationInProgress)
}
private var memorySection: some View {
@@ -92,11 +277,12 @@ struct InspectorView: View {
.labelsHidden()
.fixedSize()
}
- Text("More slots can improve decode speed by keeping more experts in memory, but they also use more RAM. Changes are compared with 4K context and 16 slots and apply after reloading the model.")
+ Text("More slots can improve decode speed by keeping more experts in memory, but they also use more RAM. Changes are compared with 8K context and 16 slots and apply after reloading the model.")
.font(.caption)
.foregroundStyle(.secondary)
}
- .disabled(model.isRunning || model.loadState.isLoading)
+ .disabled(model.isRunning || model.loadState.isLoading
+ || model.isVisionCompanionOperationInProgress)
}
private var generationSection: some View {
@@ -136,7 +322,8 @@ struct InspectorView: View {
}
}
}
- .disabled(model.isRunning || model.loadState.isLoading)
+ .disabled(model.isRunning || model.loadState.isLoading
+ || model.isVisionCompanionOperationInProgress)
}
private var runtimeSection: some View {
@@ -161,7 +348,8 @@ struct InspectorView: View {
.foregroundStyle(.secondary)
}
}
- .disabled(model.isRunning || model.loadState.isLoading)
+ .disabled(model.isRunning || model.loadState.isLoading
+ || model.isVisionCompanionOperationInProgress)
}
}
diff --git a/Sources/TurboFieldfareApp/Mac/Diagnostics/RunnerDiagnosticsSection.swift b/Sources/TurboFieldfareApp/Mac/Diagnostics/RunnerDiagnosticsSection.swift
index a824fd6c..5dc7e56c 100644
--- a/Sources/TurboFieldfareApp/Mac/Diagnostics/RunnerDiagnosticsSection.swift
+++ b/Sources/TurboFieldfareApp/Mac/Diagnostics/RunnerDiagnosticsSection.swift
@@ -1,4 +1,5 @@
import TurboFieldfareAppCore
+import TurboFieldfareMacPresentation
import SwiftUI
struct RunnerDiagnosticsSection: View {
@@ -25,7 +26,14 @@ struct RunnerDiagnosticsSection: View {
DiagnosticRow("Request TTFT", MetricFormat.seconds(diagnostics.requestStartTimeToFirstTokenSeconds))
DiagnosticRow("Decode duration", MetricFormat.seconds(diagnostics.decodeSeconds))
DiagnosticRow("Decode rate", "\(MetricFormat.rate(diagnostics.tokensPerSecond)) tok/s")
- DiagnosticRow("Peak memory", MetricFormat.memory(diagnostics.peakMemoryBytes))
+ DiagnosticRow("Peak charged",
+ MetricFormat.memory(diagnostics.peakMemoryBytes),
+ help: MemoryFootprintExplanation.exclusionNote)
+ if let mapped = diagnostics.visionTowerMappedBytes, mapped > 0 {
+ // Page cache, not process memory: holding all of it moves
+ // the figures above by about 5 MB.
+ DiagnosticRow("Image tower mapped", MetricFormat.memory(mapped))
+ }
DiagnosticRow("I/O / token",
MetricFormat.milliseconds(diagnostics.runner?.ioMillisecondsPerToken))
@@ -130,7 +138,6 @@ private struct DiagnosticRow: View {
let value: String
let multiline: Bool
let help: String?
- @State private var isShowingHelp = false
init(_ label: String,
_ value: String,
@@ -156,25 +163,7 @@ private struct DiagnosticRow: View {
HStack(spacing: 4) {
Text(label)
if let help {
- Button {
- isShowingHelp.toggle()
- } label: {
- Image(systemName: "info.circle")
- .font(.caption2)
- .foregroundStyle(.tertiary)
- .frame(width: 16, height: 16)
- .contentShape(Rectangle())
- }
- .buttonStyle(.plain)
- .help(help)
- .popover(isPresented: $isShowingHelp, arrowEdge: .trailing) {
- Text(help)
- .font(.callout)
- .frame(width: 280, alignment: .leading)
- .padding()
- }
- .accessibilityLabel("\(label) information")
- .accessibilityHint(help)
+ InfoPopoverButton(subject: label, text: help)
}
}
}
diff --git a/Sources/TurboFieldfareApp/Mac/Diagnostics/StatusHUDView.swift b/Sources/TurboFieldfareApp/Mac/Diagnostics/StatusHUDView.swift
index 2d8c8e3c..dfc65a31 100644
--- a/Sources/TurboFieldfareApp/Mac/Diagnostics/StatusHUDView.swift
+++ b/Sources/TurboFieldfareApp/Mac/Diagnostics/StatusHUDView.swift
@@ -21,7 +21,11 @@ struct StatusHUDView: View {
if showsMetrics {
HUDMetricView(value: rateText, label: "tok/s", animated: !model.isRunning)
HUDMetricView(value: tokensText, label: "tokens", animated: !model.isRunning)
- HUDMetricView(value: memoryText, label: "memory", animated: !model.isRunning)
+ HStack(spacing: 2) {
+ HUDMetricView(value: memoryText, label: "memory", animated: !model.isRunning)
+ .help(memoryHelp)
+ InfoPopoverButton(subject: "Memory", text: memoryHelp, arrowEdge: .bottom)
+ }
}
}
.frame(height: 30)
@@ -49,10 +53,20 @@ struct StatusHUDView: View {
return "\u{2014}"
}
+ /// `phys_footprint`: what this process is charged. Measured, not assumed —
+ /// the model and image tower weights are memory-mapped and read by the GPU,
+ /// and no per-process counter attributes them: 1,144 MB of tower retained
+ /// moves the footprint by 5 MB. Those bytes are page cache, owned by the
+ /// kernel and reclaimable, so the popover explains them in words and the
+ /// diagnostics section carries their measured row.
private var memoryText: String {
MetricFormat.memory(model.currentProcessMemoryBytes)
}
+ private var memoryHelp: String {
+ MemoryFootprintExplanation.text(chargedBytes: model.currentProcessMemoryBytes)
+ }
+
private var showsMetrics: Bool {
model.loadState.isReady || model.isRunning || model.diagnostics != nil
}
diff --git a/Sources/TurboFieldfareApp/Mac/Generation/OutputPaneView.swift b/Sources/TurboFieldfareApp/Mac/Generation/OutputPaneView.swift
index 5307de51..60bd37a5 100644
--- a/Sources/TurboFieldfareApp/Mac/Generation/OutputPaneView.swift
+++ b/Sources/TurboFieldfareApp/Mac/Generation/OutputPaneView.swift
@@ -1,4 +1,5 @@
import AppKit
+import TurboFieldfare
import TurboFieldfareAppCore
import TurboFieldfareMacPresentation
import SwiftUI
@@ -61,11 +62,13 @@ struct OutputPaneView: View {
private var transcript: some View {
IncrementalTranscriptView(
prompt: model.outputPromptText,
+ images: model.outputImageAttachments,
output: model.outputText,
mailbox: model.generationTranscriptMailbox,
isTerminal: !model.isRunning,
showsPrefillPlaceholder: model.isRunning
- && model.outputResponsePlainText.isEmpty)
+ && model.outputResponsePlainText.isEmpty,
+ runIdentity: model.runIdentity)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.overlay(alignment: .topTrailing) {
if !model.isRunning && !model.outputResponsePlainText.isEmpty {
@@ -182,6 +185,97 @@ struct OutputPaneView: View {
}
}
+struct SubmittedImageThumbnail: View {
+ let attachment: AppImageAttachment
+ let maximumSize: CGSize
+ @State private var image: NSImage?
+
+ init(
+ attachment: AppImageAttachment,
+ maximumSize: CGSize = CGSize(width: 48, height: 48)
+ ) {
+ self.attachment = attachment
+ self.maximumSize = maximumSize
+ }
+
+ var body: some View {
+ Group {
+ if let image {
+ // Filled and cropped to a tile, not fitted inside one. Fitting
+ // gave every attachment a different height — a screenshot came
+ // out a third the height of a portrait photo — so a row of them
+ // was ragged, and the remove badge, pinned to the tile, floated
+ // clear of the short ones.
+ Image(nsImage: image)
+ .resizable()
+ .scaledToFill()
+ .frame(width: maximumSize.width, height: maximumSize.height)
+ .clipped()
+ } else {
+ Image(systemName: "photo")
+ .foregroundStyle(.tertiary)
+ .frame(width: maximumSize.width, height: maximumSize.height)
+ }
+ }
+ .frame(width: maximumSize.width, height: maximumSize.height)
+ .background(.quaternary)
+ .clipShape(RoundedRectangle(cornerRadius: 8))
+ .overlay {
+ RoundedRectangle(cornerRadius: 8)
+ .stroke(.separator.opacity(0.5), lineWidth: 0.5)
+ }
+ .accessibilityLabel("Attached image \(attachment.displayName)")
+ .task(id: "\(attachment.id)-\(maximumSize.width)x\(maximumSize.height)") {
+ let url = attachment.fileURL
+ let key = attachment.sha256
+ let pixels = Int(ceil(max(maximumSize.width, maximumSize.height) * 2))
+ // This closure runs on the main actor, and a source near the decode
+ // budget takes long enough that decoding here stalled the window.
+ // The decode is done off the main thread and left in the cache; the
+ // read below is then a lookup.
+ await Task.detached(priority: .userInitiated) {
+ _ = Self.loadThumbnail(
+ at: url, maximumPixelSize: pixels, cacheKey: key)
+ }.value
+ image = Self.loadThumbnail(
+ at: url, maximumPixelSize: pixels, cacheKey: key)
+ }
+ }
+
+ /// The transcript lays images out inline, where cropping would hide part of
+ /// what was sent, so that path fits rather than fills.
+ static func fittedSize(_ source: CGSize, within maximumSize: CGSize) -> CGSize {
+ TranscriptImageTile.fittedSize(source, within: maximumSize)
+ }
+
+ /// Every attached-image decode in the app goes through here, so the decode
+ /// budget cannot be applied to one caller and forgotten on the next. Nil
+ /// means refused or unreadable; both callers draw their placeholder for it.
+ nonisolated static func loadThumbnail(
+ at url: URL,
+ maximumPixelSize: Int,
+ cacheKey: String? = nil
+ ) -> NSImage? {
+ TranscriptImageLoader.thumbnail(
+ at: url,
+ maximumPixelSize: maximumPixelSize,
+ budget: decodeBudget,
+ cacheKey: cacheKey)
+ }
+
+ /// The single point where the app binds the runtime's limits, so the two
+ /// cannot drift apart: see `VisionImageLimits` in
+ /// Runtime/Vision/Preprocessing/ImageMetadataReader.swift.
+ nonisolated private static let decodeBudget: TranscriptImageLoader.Budget = {
+ let limits = VisionImageLimits()
+ return TranscriptImageLoader.Budget(
+ maximumSourcePixels: limits.maximumSourcePixels,
+ maximumSourceDimension: limits.maximumSourceDimension,
+ maximumDecodedBytes: limits.maximumDecodedBytes,
+ allowedTypeIdentifiers: limits.allowedTypeIdentifiers)
+ }()
+}
+
private struct EmptyPlaceholderIcon: View {
let systemName: String
@@ -257,10 +351,12 @@ private struct LoadingModelText: View {
private struct IncrementalTranscriptView: NSViewRepresentable {
var prompt: String
+ var images: [AppImageAttachment] = []
var output: String
var mailbox: GenerationTranscriptMailbox?
var isTerminal: Bool
var showsPrefillPlaceholder: Bool
+ var runIdentity: Int
@MainActor
final class Coordinator: NSObject {
@@ -268,8 +364,36 @@ private struct IncrementalTranscriptView: NSViewRepresentable {
weak var textView: NSTextView?
var mailbox: GenerationTranscriptMailbox?
var prompt = ""
+ var promptPrefix = NSAttributedString()
+ var promptPrefixIdentifier = ""
+
+ /// The identifier the document controller is told about — empty until
+ /// the prefix it names actually exists.
+ ///
+ /// `synchronize` records the new identifier and clears the prefix before
+ /// starting the async image build, so telling the controller the final
+ /// identifier up front made every term of its rebuild test false when
+ /// the built prefix arrived: same prompt, same identifier, same response.
+ /// The strip was dropped for the rest of the run, and a coordinator
+ /// recreated against a finished transcript never drew images at all.
+ ///
+ /// `apply` reads this itself rather than taking it as an argument. It
+ /// used to be passed in, and one of the three call sites passed the raw
+ /// identifier instead — the same defect again, in the code written to
+ /// prevent it. A caller that cannot name the identifier cannot get it
+ /// wrong.
+ var appliedPromptPrefixIdentifier: String {
+ promptPrefix.length == 0 ? "" : promptPrefixIdentifier
+ }
var isTerminal = false
var showsPrefillPlaceholder = false
+ var runIdentity = 0
+ /// Holds the view at the bottom from the moment a run starts until its
+ /// answer begins. One scroll is not enough: image thumbnails finish
+ /// loading after it and push the content back down, which is exactly
+ /// the case this exists for. The decision itself lives in
+ /// `TranscriptScrollFollow`, where it can be tested.
+ var follow = TranscriptScrollFollow()
var timer: Timer?
var prefillAnimationTimer: Timer?
let documentController = InstructionTranscriptDocumentController()
@@ -278,6 +402,18 @@ private struct IncrementalTranscriptView: NSViewRepresentable {
self.scrollView = scrollView
self.textView = textView
guard timer == nil else { return }
+ // Auto-follow yields the instant the reader scrolls. Without this,
+ // holding the view at the bottom through prefill fought anyone
+ // trying to look back at what they had sent.
+ scrollView.contentView.postsBoundsChangedNotifications = true
+ NotificationCenter.default.addObserver(
+ self, selector: #selector(readerTookOver),
+ name: NSScrollView.willStartLiveScrollNotification,
+ object: scrollView)
+ NotificationCenter.default.addObserver(
+ self, selector: #selector(readerTookOver),
+ name: NSScrollView.didLiveScrollNotification,
+ object: scrollView)
let timer = Timer(timeInterval: 0.1, target: self,
selector: #selector(drainMailbox),
userInfo: nil, repeats: true)
@@ -288,13 +424,27 @@ private struct IncrementalTranscriptView: NSViewRepresentable {
func synchronize(
prompt: String,
+ images: [AppImageAttachment],
output: String,
mailbox: GenerationTranscriptMailbox?,
isTerminal: Bool,
- showsPrefillPlaceholder: Bool
+ showsPrefillPlaceholder: Bool,
+ runIdentity: Int
) {
+ // A new run always goes to the bottom, whatever the reader was
+ // looking at: it is the thing they just asked for.
+ let startedNewRun = runIdentity != self.runIdentity
+ self.runIdentity = runIdentity
self.mailbox = mailbox
self.prompt = prompt
+ let prefixIdentifier = images.map {
+ "\($0.id.uuidString):\($0.sha256)"
+ }.joined(separator: ",")
+ if prefixIdentifier != promptPrefixIdentifier {
+ promptPrefixIdentifier = prefixIdentifier
+ promptPrefix = NSAttributedString()
+ buildPromptPrefix(images, identifier: prefixIdentifier)
+ }
self.isTerminal = isTerminal
self.showsPrefillPlaceholder = showsPrefillPlaceholder
let response = mailbox?.drain().completeText ?? output
@@ -302,10 +452,51 @@ private struct IncrementalTranscriptView: NSViewRepresentable {
prompt: prompt,
response: response,
isTerminal: isTerminal,
- showsPrefillPlaceholder: showsPrefillPlaceholder)
+ showsPrefillPlaceholder: showsPrefillPlaceholder,
+ promptPrefix: promptPrefix)
+ if startedNewRun { follow.beginRun() }
+ // Once the answer has text, or the run is over, the reader is in
+ // charge again; the usual follow-the-bottom rule takes over from a
+ // view that is already at the bottom.
+ if !response.isEmpty || isTerminal { follow.end() }
+ if startedNewRun || shouldFollowNow() { scrollToBottom() }
+ }
+
+ func scrollToBottom() {
+ guard let textView else { return }
+ if let textContainer = textView.textContainer {
+ textView.layoutManager?.ensureLayout(for: textContainer)
+ }
+ textView.scrollToEndOfDocument(nil)
+ recordScrollPosition()
+ }
+
+ private func recordScrollPosition() {
+ guard let scrollView else { return }
+ follow.recordScroll(
+ origin: scrollView.contentView.bounds.origin.y,
+ documentHeight: scrollView.documentView?.bounds.height ?? 0)
+ }
+
+ private func shouldFollowNow() -> Bool {
+ guard let scrollView else { return false }
+ return follow.shouldScrollToBottom(
+ origin: scrollView.contentView.bounds.origin.y,
+ documentHeight: scrollView.documentView?.bounds.height ?? 0)
}
@objc private func drainMailbox() {
+ // Keep the newest turn in view while its images lay out, even
+ // between synchronize calls — but never against the reader.
+ //
+ // "Not at the bottom any more" is NOT the test for that. Images lay
+ // out after the scroll and grow the document, which leaves the view
+ // above the bottom through no act of the reader's; treating that as
+ // a reader scroll ended the follow on exactly the turns that needed
+ // it, and a prompt with several images stayed scrolled off the top.
+ // A reader moving the view changes the scroll origin while the
+ // document height stays put, so that is what ends it.
+ if shouldFollowNow() { scrollToBottom() }
guard let mailbox else { return }
let snapshot = mailbox.drain()
guard !snapshot.pendingText.isEmpty
@@ -315,7 +506,8 @@ private struct IncrementalTranscriptView: NSViewRepresentable {
apply(prompt: prompt,
response: snapshot.completeText,
isTerminal: isTerminal,
- showsPrefillPlaceholder: showsPrefillPlaceholder)
+ showsPrefillPlaceholder: showsPrefillPlaceholder,
+ promptPrefix: promptPrefix)
}
@objc private func animatePrefillPlaceholderIfNeeded() {
@@ -339,10 +531,18 @@ private struct IncrementalTranscriptView: NSViewRepresentable {
} else {
textView.selectedRanges = restored.map(NSValue.init(range:))
}
- if wasAtBottom { textView.scrollToEndOfDocument(nil) }
+ if wasAtBottom {
+ textView.scrollToEndOfDocument(nil)
+ recordScrollPosition()
+ }
+ }
+
+ @objc private func readerTookOver() {
+ follow.end()
}
func invalidate() {
+ NotificationCenter.default.removeObserver(self)
timer?.invalidate()
timer = nil
stopPrefillAnimationTimer()
@@ -375,7 +575,8 @@ private struct IncrementalTranscriptView: NSViewRepresentable {
prompt: String,
response: String,
isTerminal: Bool,
- showsPrefillPlaceholder: Bool
+ showsPrefillPlaceholder: Bool,
+ promptPrefix: NSAttributedString
) {
guard let scrollView, let textView, let storage = textView.textStorage else { return }
let wasAtBottom = isAtBottom(scrollView)
@@ -387,7 +588,9 @@ private struct IncrementalTranscriptView: NSViewRepresentable {
prompt: prompt,
response: response,
isTerminal: isTerminal,
- showsPrefillPlaceholder: showsPrefillPlaceholder)
+ showsPrefillPlaceholder: showsPrefillPlaceholder,
+ promptPrefix: promptPrefix,
+ promptPrefixIdentifier: appliedPromptPrefixIdentifier)
storage.endEditing()
updatePrefillAnimationTimer()
@@ -408,6 +611,9 @@ private struct IncrementalTranscriptView: NSViewRepresentable {
textView.layoutManager?.ensureLayout(for: textContainer)
}
textView.scrollToEndOfDocument(nil)
+ // Every programmatic scroll updates the baseline, or the next
+ // comparison reads our own move as the reader's.
+ recordScrollPosition()
}
}
@@ -416,6 +622,91 @@ private struct IncrementalTranscriptView: NSViewRepresentable {
let visible = scrollView.contentView.bounds
return visible.maxY >= document.bounds.maxY - 24
}
+
+ /// Decoding the submitted images ran inside `updateNSView`'s render
+ /// pass, so several photos near the decode budget stalled the window at
+ /// the moment Run was pressed. Only the decode moves off the main
+ /// thread — it lands in the loader's cache, and the attributed string is
+ /// then assembled from cached copies, which is cheap and stays here
+ /// where AppKit's drawing belongs. A prefix the transcript has since
+ /// stopped wanting is dropped rather than applied. Images arriving after
+ /// the first paint is the case `follow` already exists for.
+ private func buildPromptPrefix(
+ _ images: [AppImageAttachment], identifier: String
+ ) {
+ guard !images.isEmpty else { return }
+ Task { [weak self] in
+ await Task.detached(priority: .userInitiated) {
+ for attachment in images {
+ _ = SubmittedImageThumbnail.loadThumbnail(
+ at: attachment.fileURL,
+ maximumPixelSize: 720,
+ cacheKey: attachment.sha256)
+ }
+ }.value
+ guard let self, self.promptPrefixIdentifier == identifier else { return }
+ let prefix = Self.makePromptPrefix(images)
+ self.promptPrefix = prefix
+ self.apply(
+ prompt: self.prompt,
+ response: self.documentController.response,
+ isTerminal: self.isTerminal,
+ showsPrefillPlaceholder: self.showsPrefillPlaceholder,
+ promptPrefix: prefix)
+ if self.shouldFollowNow() { self.scrollToBottom() }
+ }
+ }
+
+ private static func makePromptPrefix(
+ _ images: [AppImageAttachment]
+ ) -> NSAttributedString {
+ let result = NSMutableAttributedString()
+ for attachment in images {
+ // A refused or unreadable image is dropped from the transcript,
+ // which is the same degradation the composer's placeholder tile
+ // gives. The separator therefore keys off what has actually
+ // been written, not off the attachment's index: keyed off the
+ // index, a first image the decode budget refused left the line
+ // starting with a bare gap.
+ guard let image = SubmittedImageThumbnail.loadThumbnail(
+ at: attachment.fileURL,
+ maximumPixelSize: 720,
+ cacheKey: attachment.sha256) else { continue }
+ image.size = SubmittedImageThumbnail.fittedSize(
+ image.size,
+ within: CGSize(width: 360, height: 240))
+ let textAttachment = NSTextAttachment()
+ textAttachment.attachmentCell = NSTextAttachmentCell(
+ imageCell: Self.rounded(image))
+ if result.length > 0 {
+ result.append(NSAttributedString(string: " "))
+ }
+ result.append(NSAttributedString(attachment: textAttachment))
+ }
+ return result
+ }
+
+ /// The transcript draws its images as text attachments, which cannot be
+ /// clipped by the view the way the composer's thumbnails are, so the
+ /// corners have to be drawn into the image itself.
+ private static func rounded(_ image: NSImage) -> NSImage {
+ let size = image.size
+ guard size.width > 1, size.height > 1 else { return image }
+ // Proportional rather than fixed, so a small thumbnail and a large
+ // one look like the same shape; capped so wide images do not turn
+ // into lozenges.
+ let radius = min(12, min(size.width, size.height) * 0.08)
+ let rounded = NSImage(size: size)
+ rounded.lockFocus()
+ defer { rounded.unlockFocus() }
+ NSGraphicsContext.current?.imageInterpolation = .high
+ let bounds = NSRect(origin: .zero, size: size)
+ let path = NSBezierPath(roundedRect: bounds,
+ xRadius: radius, yRadius: radius)
+ path.addClip()
+ image.draw(in: bounds, from: .zero, operation: .sourceOver, fraction: 1)
+ return rounded
+ }
}
func makeCoordinator() -> Coordinator { Coordinator() }
@@ -449,10 +740,12 @@ private struct IncrementalTranscriptView: NSViewRepresentable {
context.coordinator.attach(scrollView: scrollView, textView: textView)
context.coordinator.synchronize(
prompt: prompt,
+ images: images,
output: output,
mailbox: mailbox,
isTerminal: isTerminal,
- showsPrefillPlaceholder: showsPrefillPlaceholder)
+ showsPrefillPlaceholder: showsPrefillPlaceholder,
+ runIdentity: runIdentity)
}
static func dismantleNSView(_ nsView: NSScrollView, coordinator: Coordinator) {
@@ -472,7 +765,8 @@ private struct TranscriptPreview: View {
output: response,
mailbox: nil,
isTerminal: isTerminal,
- showsPrefillPlaceholder: showsPrefillPlaceholder)
+ showsPrefillPlaceholder: showsPrefillPlaceholder,
+ runIdentity: 0)
.padding(24)
.frame(width: 720, height: 420)
}
diff --git a/Sources/TurboFieldfareApp/Mac/Generation/PromptComposerView.swift b/Sources/TurboFieldfareApp/Mac/Generation/PromptComposerView.swift
index 942e9c14..2f6e406c 100644
--- a/Sources/TurboFieldfareApp/Mac/Generation/PromptComposerView.swift
+++ b/Sources/TurboFieldfareApp/Mac/Generation/PromptComposerView.swift
@@ -1,18 +1,35 @@
import AppKit
+import TurboFieldfare
import TurboFieldfareAppCore
import TurboFieldfareMacPresentation
import SwiftUI
+import UniformTypeIdentifiers
struct PromptComposerView: View {
@Bindable var model: AppModel
@FocusState private var promptFocused: Bool
@State private var showingPromptTips = false
+ @State private var showingImagePicker = false
+ @State private var isImageDropTargeted = false
var body: some View {
VStack(alignment: .leading, spacing: 8) {
+ if !model.imageAttachments.isEmpty || model.imageAttachmentError != nil {
+ attachmentStrip
+ }
editor
footer
}
+ .fileImporter(
+ isPresented: $showingImagePicker,
+ allowedContentTypes: VisionImageLimits().allowedContentTypes,
+ allowsMultipleSelection: true
+ ) { result in
+ switch result {
+ case .success(let urls): model.addImages(urls)
+ case .failure(let error): model.reportImageAttachmentError(error)
+ }
+ }
.padding(14)
.background {
RoundedRectangle(cornerRadius: 22)
@@ -25,27 +42,32 @@ struct PromptComposerView: View {
}
private var editor: some View {
- TextEditor(text: $model.promptText)
+ PromptTextEditor(
+ text: $model.promptText,
+ isFocused: Binding(
+ get: { promptFocused },
+ set: { promptFocused = $0 }),
+ newlineShortcut: model.newlineShortcut,
+ canRun: model.canRun,
+ canAcceptImages: model.isImageInputAvailable
+ && !model.isRunning
+ && !model.isAddingImages,
+ onSubmit: model.run,
+ onImagesDropped: { model.addImages($0) },
+ onImageDataPasted: model.addImageData,
+ onPromisedImagesReceived: { urls, directory in
+ model.addImages(urls, discardingSourceDirectory: directory)
+ },
+ onPromisedImagesFailed: {
+ model.reportImageAttachmentError(
+ "That drag did not deliver a file TurboFieldfare could read.")
+ },
+ onUnsupportedImagePaste: {
+ model.reportImageAttachmentError(
+ "That clipboard content is not an image TurboFieldfare can read.")
+ },
+ onDropTargeted: { isImageDropTargeted = $0 })
.accessibilityLabel("Prompt")
- .font(.body)
- .scrollContentBackground(.hidden)
- .focused($promptFocused)
- .onKeyPress(.return, phases: [.down, .repeat]) { keyPress in
- switch PromptSubmissionPolicy.decision(
- newlineShortcut: model.newlineShortcut,
- modifiers: keyPress.modifiers,
- canRun: model.canRun,
- hasMarkedText: promptHasMarkedText,
- isRepeat: keyPress.phase.contains(.repeat)) {
- case .submit:
- model.run()
- return .handled
- case .consume:
- return .handled
- case .deferToEditor:
- return .ignored
- }
- }
.frame(height: editorHeight)
.overlay(alignment: .topLeading) {
if model.promptText.isEmpty {
@@ -58,18 +80,35 @@ struct PromptComposerView: View {
.allowsHitTesting(false)
}
}
- }
-
- private var promptHasMarkedText: Bool {
- (NSApp.keyWindow?.firstResponder as? NSTextView)?.hasMarkedText() == true
+ .overlay {
+ if isImageDropTargeted {
+ RoundedRectangle(cornerRadius: 8)
+ .stroke(.tint, lineWidth: 2)
+ .allowsHitTesting(false)
+ }
+ }
}
private var editorHeight: CGFloat {
- model.promptText.isEmpty ? 46 : 84
+ model.promptText.isEmpty && model.showPromptExamples ? 46 : 84
}
private var footer: some View {
HStack(spacing: 10) {
+ if model.isImageInputAvailable {
+ Button {
+ showingImagePicker = true
+ } label: {
+ Label("Add images", systemImage: "photo.badge.plus")
+ .labelStyle(.iconOnly)
+ .frame(width: 28, height: 28)
+ }
+ .buttonStyle(.borderless)
+ .disabled(model.isRunning || model.isAddingImages
+ || model.imageAttachments.count
+ >= model.maximumImageAttachments)
+ .help("Add images")
+ }
promptTips
Spacer()
clearAction
@@ -77,6 +116,40 @@ struct PromptComposerView: View {
}
}
+ private var attachmentStrip: some View {
+ VStack(alignment: .leading, spacing: 6) {
+ ScrollView(.horizontal) {
+ // Top-aligned so the tiles share one edge; they are all the
+ // same size now, but alignment left to chance is how the row
+ // drifted out of line in the first place.
+ HStack(alignment: .top, spacing: 8) {
+ ForEach(model.imageAttachments, id: \.id) { attachment in
+ SubmittedImageThumbnail(attachment: attachment)
+ .overlay(alignment: .topTrailing) {
+ Button {
+ model.removeImage(id: attachment.id)
+ } label: {
+ Image(systemName: "xmark.circle.fill")
+ }
+ .buttonStyle(.plain)
+ .background(.regularMaterial, in: Circle())
+ .offset(x: 5, y: -5)
+ .accessibilityLabel("Remove \(attachment.displayName)")
+ }
+ .padding(.top, 5)
+ .padding(.trailing, 5)
+ }
+ }
+ }
+ .frame(height: 58)
+ if let error = model.imageAttachmentError {
+ Text(error)
+ .font(.caption)
+ .foregroundStyle(.red)
+ }
+ }
+ }
+
private var promptTips: some View {
Button {
showingPromptTips.toggle()
@@ -129,30 +202,380 @@ struct PromptComposerView: View {
@ViewBuilder
private var clearAction: some View {
- if !model.isRunning && model.hasOutputTranscript {
+ if !model.isRunning
+ && (!model.promptText.isEmpty || !model.imageAttachments.isEmpty) {
Button {
- model.clearOutput()
+ model.promptText = ""
+ model.clearImages()
+ promptFocused = true
} label: {
- Label("Clear output", systemImage: "trash")
+ Label("Clear input", systemImage: "xmark.circle.fill")
.labelStyle(.iconOnly)
+ .symbolRenderingMode(.hierarchical)
.frame(width: 28, height: 28)
.contentShape(Circle())
}
.buttonStyle(.borderless)
- .help("Clear output")
- } else if !model.isRunning && !model.promptText.isEmpty {
+ .help("Clear text and images")
+ } else if !model.isRunning && model.hasOutputTranscript {
Button {
- model.promptText = ""
- promptFocused = true
+ model.clearOutput()
} label: {
- Label("Clear prompt", systemImage: "xmark.circle.fill")
+ Label("Clear output", systemImage: "trash")
.labelStyle(.iconOnly)
- .symbolRenderingMode(.hierarchical)
.frame(width: 28, height: 28)
.contentShape(Circle())
}
.buttonStyle(.borderless)
- .help("Clear prompt")
+ .help("Clear output")
+ }
+ }
+}
+
+private struct PromptTextEditor: NSViewRepresentable {
+ @Binding var text: String
+ let isFocused: Binding<Bool>
+ let newlineShortcut: AppNewlineShortcut
+ let canRun: Bool
+ let canAcceptImages: Bool
+ let onSubmit: () -> Void
+ let onImagesDropped: ([URL]) -> Void
+ let onImageDataPasted: (Data, String) -> Void
+ let onPromisedImagesReceived: ([URL], URL) -> Void
+ let onPromisedImagesFailed: () -> Void
+ let onUnsupportedImagePaste: () -> Void
+ let onDropTargeted: (Bool) -> Void
+
+ func makeCoordinator() -> Coordinator {
+ Coordinator(self)
+ }
+
+ func makeNSView(context: Context) -> NSScrollView {
+ let textView = ImageDropTextView()
+ textView.delegate = context.coordinator
+ textView.string = text
+ textView.font = .systemFont(ofSize: NSFont.systemFontSize)
+ textView.textColor = .labelColor
+ textView.drawsBackground = false
+ textView.isRichText = false
+ textView.allowsUndo = true
+ textView.isVerticallyResizable = true
+ textView.isHorizontallyResizable = false
+ textView.autoresizingMask = [.width]
+ textView.textContainerInset = .zero
+ textView.textContainer?.lineFragmentPadding = 5
+ textView.textContainer?.widthTracksTextView = true
+ textView.setAccessibilityLabel("Prompt")
+ // A promise-only drag — Photos, Mail, most browsers — never reaches
+ // `draggingEntered` unless its types are registered here.
+ textView.registerForDraggedTypes(
+ textView.registeredDraggedTypes
+ + NSFilePromiseReceiver.readableDraggedTypes.map {
+ NSPasteboard.PasteboardType(rawValue: $0)
+ })
+
+ let scrollView = NSScrollView()
+ scrollView.drawsBackground = false
+ scrollView.borderType = .noBorder
+ scrollView.hasVerticalScroller = true
+ scrollView.autohidesScrollers = true
+ scrollView.documentView = textView
+ context.coordinator.textView = textView
+ return scrollView
+ }
+
+ func updateNSView(_ scrollView: NSScrollView, context: Context) {
+ guard let textView = scrollView.documentView as? ImageDropTextView else { return }
+ context.coordinator.parent = self
+ textView.canAcceptImages = canAcceptImages
+ textView.onImagesDropped = onImagesDropped
+ textView.onImageDataPasted = onImageDataPasted
+ textView.onPromisedImagesReceived = onPromisedImagesReceived
+ textView.onPromisedImagesFailed = onPromisedImagesFailed
+ textView.onUnsupportedImagePaste = onUnsupportedImagePaste
+ textView.onDropTargeted = onDropTargeted
+ if textView.string != text {
+ textView.string = text
+ }
+ if isFocused.wrappedValue,
+ textView.window?.firstResponder !== textView {
+ DispatchQueue.main.async {
+ textView.window?.makeFirstResponder(textView)
+ }
+ }
+ }
+
+ final class Coordinator: NSObject, NSTextViewDelegate {
+ var parent: PromptTextEditor
+ weak var textView: NSTextView?
+
+ init(_ parent: PromptTextEditor) {
+ self.parent = parent
+ }
+
+ func textDidChange(_ notification: Notification) {
+ guard let textView = notification.object as? NSTextView else { return }
+ parent.text = textView.string
+ }
+
+ func textDidBeginEditing(_ notification: Notification) {
+ parent.isFocused.wrappedValue = true
+ }
+
+ func textDidEndEditing(_ notification: Notification) {
+ parent.isFocused.wrappedValue = false
}
+
+ func textView(_ textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
+ guard commandSelector == #selector(NSResponder.insertNewline(_:)) else {
+ return false
+ }
+ let event = NSApp.currentEvent
+ switch PromptSubmissionPolicy.decision(
+ newlineShortcut: parent.newlineShortcut,
+ modifiers: Self.modifiers(event?.modifierFlags ?? []),
+ canRun: parent.canRun,
+ hasMarkedText: textView.hasMarkedText(),
+ isRepeat: event?.isARepeat == true) {
+ case .submit:
+ parent.onSubmit()
+ return true
+ case .consume:
+ return true
+ case .deferToEditor:
+ return false
+ }
+ }
+
+ private static func modifiers(_ flags: NSEvent.ModifierFlags) -> EventModifiers {
+ var modifiers: EventModifiers = []
+ if flags.contains(.command) { modifiers.insert(.command) }
+ if flags.contains(.shift) { modifiers.insert(.shift) }
+ if flags.contains(.option) { modifiers.insert(.option) }
+ if flags.contains(.control) { modifiers.insert(.control) }
+ return modifiers
+ }
+ }
+}
+
+private final class ImageDropTextView: NSTextView {
+ var canAcceptImages = false
+ var onImagesDropped: (([URL]) -> Void)?
+ /// Promised files arrive in a directory we made and must not keep.
+ var onPromisedImagesReceived: (([URL], URL) -> Void)?
+ var onImageDataPasted: ((Data, String) -> Void)?
+ var onUnsupportedImagePaste: (() -> Void)?
+ var onPromisedImagesFailed: (() -> Void)?
+ var onDropTargeted: ((Bool) -> Void)?
+
+ override func paste(_ sender: Any?) {
+ guard canAcceptImages else {
+ super.paste(sender)
+ return
+ }
+ let pasteboard = NSPasteboard.general
+ let urls = fileURLs(from: pasteboard)
+ if !urls.isEmpty {
+ onImagesDropped?(urls)
+ return
+ }
+ // Text on the pasteboard wins over a picture that came with it.
+ // Copying a range of cells from Numbers or Excel, or a text box from
+ // Keynote, writes TIFF alongside the RTF and plain text; so does a
+ // rich selection from many other apps. Taking the picture and
+ // returning swallowed the text the user actually selected, in a text
+ // editor, with nothing said about it. A screenshot or an image copied
+ // from an image editor carries no text, so it still attaches.
+ //
+ // Only the byte-carrying branches need this. A file paste is handled
+ // above, and Finder puts the path on the pasteboard as a string too.
+ if pasteboard.string(forType: .string)?.isEmpty == false {
+ super.paste(sender)
+ return
+ }
+ // An image copied from another app arrives as bytes with no file
+ // behind it, which used to be refused with an instruction to go and
+ // find one.
+ if let image = imageData(from: pasteboard) {
+ onImageDataPasted?(image.data, image.name)
+ return
+ }
+ if containsImage(in: pasteboard) {
+ onUnsupportedImagePaste?()
+ return
+ }
+ super.paste(sender)
+ }
+
+ override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {
+ guard carriesImages(sender.draggingPasteboard) else {
+ return super.draggingEntered(sender)
+ }
+ guard canAcceptImages else { return [] }
+ onDropTargeted?(true)
+ return .copy
+ }
+
+ override func draggingUpdated(_ sender: NSDraggingInfo) -> NSDragOperation {
+ guard carriesImages(sender.draggingPasteboard) else {
+ return super.draggingUpdated(sender)
+ }
+ return canAcceptImages ? .copy : []
+ }
+
+ override func draggingExited(_ sender: NSDraggingInfo?) {
+ onDropTargeted?(false)
+ super.draggingExited(sender)
+ }
+
+ override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
+ let urls = fileURLs(from: sender.draggingPasteboard)
+ if !urls.isEmpty {
+ onDropTargeted?(false)
+ guard canAcceptImages else { return false }
+ onImagesDropped?(urls)
+ return true
+ }
+ let promises = filePromises(from: sender.draggingPasteboard)
+ guard !promises.isEmpty else { return super.performDragOperation(sender) }
+ onDropTargeted?(false)
+ guard canAcceptImages else { return false }
+ receive(promises)
+ return true
+ }
+
+ /// Drags from Photos, Mail and most browsers carry a promise rather than a
+ /// file: the source writes the bytes only once a destination asks for them.
+ /// Without this the drop was simply refused.
+ private func receive(_ promises: [NSFilePromiseReceiver]) {
+ let destination = FileManager.default.temporaryDirectory
+ .appendingPathComponent("TurboFieldfare-Promises", isDirectory: true)
+ .appendingPathComponent(UUID().uuidString, isDirectory: true)
+ do {
+ try FileManager.default.createDirectory(
+ at: destination, withIntermediateDirectories: true)
+ } catch {
+ // Failing to make a staging directory is a disk or permission
+ // failure, not a statement about what was dropped. Reporting it as
+ // unsupported content sent someone off converting file formats
+ // because the volume was full.
+ onPromisedImagesFailed?()
+ return
+ }
+ let queue = OperationQueue()
+ // One completion arrives per promised FILE, not per receiver: a legacy
+ // promiser puts several file names on a single pasteboard item. Counting
+ // receivers finished the batch at the first file and handed the
+ // directory straight to `addImages`, whose `defer` deleted it while
+ // AppKit was still writing the rest — so a three-image drag attached one
+ // and destroyed two, with nothing reporting the loss.
+ let expected = promises.reduce(0) { $0 + max(1, $1.fileNames.count) }
+ let received = ReceivedPromises(expected: expected)
+ for promise in promises {
+ promise.receivePromisedFiles(
+ atDestination: destination,
+ options: [:],
+ operationQueue: queue
+ ) { [weak self] url, error in
+ // The staged copy is what the request uses, so the promised
+ // file is only needed until then.
+ let finished = received.record(url: error == nil ? url : nil)
+ guard let finished else { return }
+ DispatchQueue.main.async {
+ if finished.isEmpty {
+ // A promise that failed is not "unsupported content";
+ // saying so sends the user looking for the wrong thing.
+ self?.onPromisedImagesFailed?()
+ try? FileManager.default.removeItem(at: destination)
+ } else if let handler = self?.onPromisedImagesReceived {
+ handler(finished, destination)
+ } else {
+ // The text view went away before the promises resolved,
+ // so nothing downstream will ever own this directory:
+ // the optional chain was a no-op and the sweep covers
+ // only the staging root, so a closed window left the
+ // full-size copies behind for every future launch.
+ try? FileManager.default.removeItem(at: destination)
+ }
+ }
+ }
+ }
+ }
+
+ /// Only files in a format the vision pack can actually decode. Without the
+ /// conformance filter any file URL was staged: copying a document in Finder
+ /// and pressing Cmd-V attached it, replacing the editor's own paste, and the
+ /// failure surfaced only once the run reached image decoding.
+ ///
+ /// The list is the runtime's, not `public.image`: conforming to
+ /// `public.image` admits camera RAW, EXR and WebP, which are copied at full
+ /// size and decoded for a thumbnail before the run refuses them. The picker
+ /// reads the same list, and paste, drop and the drag-accept highlight all
+ /// read through here, so the four stay in agreement.
+ private func fileURLs(from pasteboard: NSPasteboard) -> [URL] {
+ let objects = pasteboard.readObjects(
+ forClasses: [NSURL.self],
+ options: [
+ .urlReadingFileURLsOnly: true,
+ .urlReadingContentsConformToTypes:
+ Array(VisionImageLimits().allowedTypeIdentifiers),
+ ]) as? [NSURL]
+ return objects?.map { $0 as URL } ?? []
+ }
+
+ private func filePromises(from pasteboard: NSPasteboard) -> [NSFilePromiseReceiver] {
+ pasteboard.readObjects(
+ forClasses: [NSFilePromiseReceiver.self],
+ options: nil) as? [NSFilePromiseReceiver] ?? []
+ }
+
+ private func carriesImages(_ pasteboard: NSPasteboard) -> Bool {
+ !fileURLs(from: pasteboard).isEmpty || !filePromises(from: pasteboard).isEmpty
+ }
+
+ /// The first pasteboard representation the vision pack can actually decode.
+ /// PNG and JPEG come through unchanged; anything else is re-encoded as PNG
+ /// rather than handing the decoder a format it was never validated against.
+ private func imageData(from pasteboard: NSPasteboard) -> (data: Data, name: String)? {
+ if let data = pasteboard.data(forType: .png) {
+ return (data, "Pasted image.png")
+ }
+ if let data = pasteboard.data(forType: NSPasteboard.PasteboardType("public.jpeg")) {
+ return (data, "Pasted image.jpeg")
+ }
+ guard let tiff = pasteboard.data(forType: .tiff),
+ let representation = NSBitmapImageRep(data: tiff),
+ let png = representation.representation(using: .png, properties: [:])
+ else { return nil }
+ return (png, "Pasted image.png")
+ }
+
+ private func containsImage(in pasteboard: NSPasteboard) -> Bool {
+ (pasteboard.types ?? []).contains { type in
+ UTType(type.rawValue)?.conforms(to: .image) == true
+ }
+ }
+}
+
+/// Collects the results of a multi-file promise drop, which arrive one
+/// completion at a time on an arbitrary queue.
+private final class ReceivedPromises: @unchecked Sendable {
+ private let lock = NSLock()
+ private let expected: Int
+ private var urls: [URL] = []
+ private var completed = 0
+
+ init(expected: Int) {
+ self.expected = expected
+ }
+
+ /// Returns the collected URLs once every promise has reported, and nil
+ /// until then.
+ func record(url: URL?) -> [URL]? {
+ lock.lock()
+ defer { lock.unlock() }
+ if let url { urls.append(url) }
+ completed += 1
+ return completed == expected ? urls : nil
}
}
diff --git a/Sources/TurboFieldfareApp/MacPresentation/AboutPanelPresentation.swift b/Sources/TurboFieldfareApp/MacPresentation/AboutPanelPresentation.swift
index 1ce8faf0..5aff1037 100644
--- a/Sources/TurboFieldfareApp/MacPresentation/AboutPanelPresentation.swift
+++ b/Sources/TurboFieldfareApp/MacPresentation/AboutPanelPresentation.swift
@@ -17,7 +17,7 @@ public enum AboutPanelPresentation {
// Most users build from a clone, where there is no Info.plist to read a
// version from, so this constant is what they see. Scripts/check_app_version.rb
// fails CI when it falls behind the newest published release.
- public static let fallbackShortVersion = "0.4.6"
+ public static let fallbackShortVersion = "0.5.0"
private static let licenseURL = URL(
string: "https://github.com/drumih/turbo-fieldfare/blob/main/LICENSE")!
diff --git a/Sources/TurboFieldfareApp/MacPresentation/InstructionTranscriptDocumentController.swift b/Sources/TurboFieldfareApp/MacPresentation/InstructionTranscriptDocumentController.swift
index 2bf0b467..4ce0519e 100644
--- a/Sources/TurboFieldfareApp/MacPresentation/InstructionTranscriptDocumentController.swift
+++ b/Sources/TurboFieldfareApp/MacPresentation/InstructionTranscriptDocumentController.swift
@@ -21,6 +21,7 @@ public final class InstructionTranscriptDocumentController {
}
public private(set) var prompt = ""
+ public private(set) var promptPrefixIdentifier = ""
public private(set) var response = ""
public private(set) var isFinalized = false
public private(set) var showsPrefillPlaceholder = false
@@ -66,7 +67,9 @@ public final class InstructionTranscriptDocumentController {
prompt: String,
response: String,
isTerminal: Bool,
- showsPrefillPlaceholder: Bool = false
+ showsPrefillPlaceholder: Bool = false,
+ promptPrefix: NSAttributedString = NSAttributedString(),
+ promptPrefixIdentifier: String = ""
) -> UpdateResult {
let responseChanged = response != self.response
let displaysPrefillPlaceholder = Self.shouldRunPrefillAnimation(
@@ -74,6 +77,7 @@ public final class InstructionTranscriptDocumentController {
isTerminal: isTerminal,
requested: showsPrefillPlaceholder)
let needsRebuild = prompt != self.prompt
+ || promptPrefixIdentifier != self.promptPrefixIdentifier
|| !response.hasPrefix(self.response)
|| (isFinalized && !isTerminal)
|| displaysPrefillPlaceholder != self.showsPrefillPlaceholder
@@ -81,10 +85,12 @@ public final class InstructionTranscriptDocumentController {
var mutation: Mutation = .none
if needsRebuild
|| storage.length == 0
- && (!prompt.isEmpty || !response.isEmpty || displaysPrefillPlaceholder) {
+ && (!prompt.isEmpty || promptPrefix.length > 0
+ || !response.isEmpty || displaysPrefillPlaceholder) {
rebuild(
storage: storage,
prompt: prompt,
+ promptPrefix: promptPrefix,
response: response,
showsPrefillPlaceholder: displaysPrefillPlaceholder)
mutation = .rebuilt
@@ -98,6 +104,7 @@ public final class InstructionTranscriptDocumentController {
}
self.prompt = prompt
+ self.promptPrefixIdentifier = promptPrefixIdentifier
self.response = response
self.showsPrefillPlaceholder = displaysPrefillPlaceholder
@@ -134,17 +141,28 @@ public final class InstructionTranscriptDocumentController {
private func rebuild(
storage: NSMutableAttributedString,
prompt: String,
+ promptPrefix: NSAttributedString,
response: String,
showsPrefillPlaceholder: Bool
) {
let document = NSMutableAttributedString()
- if !prompt.isEmpty {
+ if !prompt.isEmpty || promptPrefix.length > 0 {
document.append(NSAttributedString(
string: "You\n",
attributes: Self.userLabelAttributes()))
- document.append(NSAttributedString(
- string: prompt,
- attributes: Self.promptAttributes()))
+ if promptPrefix.length > 0 {
+ document.append(promptPrefix)
+ if !prompt.isEmpty {
+ document.append(NSAttributedString(
+ string: "\n\n",
+ attributes: Self.promptAttributes()))
+ }
+ }
+ if !prompt.isEmpty {
+ document.append(NSAttributedString(
+ string: prompt,
+ attributes: Self.promptAttributes()))
+ }
document.append(NSAttributedString(
string: "\n\n",
attributes: Self.promptAttributes()))
diff --git a/Sources/TurboFieldfareApp/MacPresentation/MemoryFootprintExplanation.swift b/Sources/TurboFieldfareApp/MacPresentation/MemoryFootprintExplanation.swift
new file mode 100644
index 00000000..b489380e
--- /dev/null
+++ b/Sources/TurboFieldfareApp/MacPresentation/MemoryFootprintExplanation.swift
@@ -0,0 +1,34 @@
+import Foundation
+
+/// The wording behind the app's memory figure, in one place so the HUD popover,
+/// the HUD tooltip and the inspector rows cannot drift apart.
+///
+/// The figure itself is `phys_footprint`, and it stays that way: measurement on
+/// 2026-08-12 showed no per-process counter attributes the GPU-read mapped
+/// weights, so a 26B model idles at roughly 160 MB. That reads as a bug unless
+/// the exclusion is stated, which is what this copy does.
+@MainActor
+public enum MemoryFootprintExplanation {
+ /// Deliberately "expert slots", never "experts": the 16 pread slot buffers
+ /// are inside the footprint, the 12.9 GB routed-expert pool is not.
+ private static func chargedLine(bytes: UInt64?) -> String {
+ "\(MetricFormat.memory(bytes)) charged to the app \u{2014} the KV cache, "
+ + "working buffers and expert slots."
+ }
+
+ /// Figure-free on purpose, so rows that show a different number (peak, for
+ /// instance) can carry the same framing without contradicting themselves.
+ public static let exclusionNote =
+ "The model's weights and the image tower are not counted here: the GPU "
+ + "reads them straight from disk, and macOS keeps them as cached files "
+ + "it can drop at any moment, charged to no app. To see them: Activity "
+ + "Monitor > Memory > Cached Files."
+
+ /// The tower stays wording, never a live figure: a number here invites
+ /// adding it to the charged headline, which would restate the bug this
+ /// copy exists to answer. The diagnostics section still carries the
+ /// measured "Image tower mapped" row for anyone who wants the bytes.
+ public static func text(chargedBytes: UInt64?) -> String {
+ [chargedLine(bytes: chargedBytes), exclusionNote].joined(separator: "\n\n")
+ }
+}
diff --git a/Sources/TurboFieldfareApp/Mac/Diagnostics/MetricFormat.swift b/Sources/TurboFieldfareApp/MacPresentation/MetricFormat.swift
similarity index 71%
rename from Sources/TurboFieldfareApp/Mac/Diagnostics/MetricFormat.swift
rename to Sources/TurboFieldfareApp/MacPresentation/MetricFormat.swift
index 94b028f9..84f3dbc4 100644
--- a/Sources/TurboFieldfareApp/Mac/Diagnostics/MetricFormat.swift
+++ b/Sources/TurboFieldfareApp/MacPresentation/MetricFormat.swift
@@ -1,7 +1,7 @@
import Foundation
@MainActor
-enum MetricFormat {
+public enum MetricFormat {
private static let memoryFormatter: ByteCountFormatter = {
let formatter = ByteCountFormatter()
formatter.countStyle = .memory
@@ -17,39 +17,39 @@ enum MetricFormat {
return formatter
}()
- static func seconds(_ value: Double?) -> String {
+ public static func seconds(_ value: Double?) -> String {
guard let value else { return "\u{2014}" }
if value < 1 { return String(format: "%.0f ms", value * 1000) }
return String(format: "%.2f s", value)
}
- static func milliseconds(_ value: Double?) -> String {
+ public static func milliseconds(_ value: Double?) -> String {
guard let value else { return "\u{2014}" }
return "\(value.formatted(.number.precision(.fractionLength(1)))) ms"
}
- static func rate(_ value: Double) -> String {
+ public static func rate(_ value: Double) -> String {
String(format: "%.1f", value)
}
- static func percent(_ value: Double) -> String {
+ public static func percent(_ value: Double) -> String {
String(format: "%.1f%%", value)
}
- static func perToken(_ value: Double) -> String {
+ public static func perToken(_ value: Double) -> String {
"\(value.formatted(.number.precision(.fractionLength(1))))/tok"
}
- static func megabytesPerToken(_ value: Double) -> String {
+ public static func megabytesPerToken(_ value: Double) -> String {
"\(value.formatted(.number.precision(.fractionLength(1)))) MB/tok"
}
- static func memory(_ bytes: UInt64?) -> String {
+ public static func memory(_ bytes: UInt64?) -> String {
guard let bytes else { return "\u{2014}" }
return memoryFormatter.string(fromByteCount: Int64(bytes))
}
- static func storage(_ bytes: UInt64) -> String {
+ public static func storage(_ bytes: UInt64) -> String {
storageFormatter.string(fromByteCount: Int64(clamping: bytes))
}
diff --git a/Sources/TurboFieldfareApp/MacPresentation/TranscriptImageLoader.swift b/Sources/TurboFieldfareApp/MacPresentation/TranscriptImageLoader.swift
new file mode 100644
index 00000000..bca10020
--- /dev/null
+++ b/Sources/TurboFieldfareApp/MacPresentation/TranscriptImageLoader.swift
@@ -0,0 +1,162 @@
+import AppKit
+import ImageIO
+import UniformTypeIdentifiers
+
+/// The one place an attached image file is decoded for display.
+///
+/// Both call sites go through here — the composer's thumbnail row and the
+/// transcript's inline copy of what was sent — so the decode budget is one rule
+/// rather than one rule per caller. It sits in the presentation module rather
+/// than beside the view because the view lives in the app executable, which no
+/// test target can reach, and a budget no test can reach is a budget that
+/// drifts back out.
+public enum TranscriptImageLoader {
+ /// What a source is measured against before ImageIO is asked for anything.
+ ///
+ /// The numbers come from the caller rather than from an import so the app
+ /// keeps a single mapping site onto the runtime's `VisionImageLimits` (see
+ /// Runtime/Vision/Preprocessing/ImageMetadataReader.swift) and so the rule
+ /// can be exercised against a small image instead of a 50 MP one.
+ public struct Budget: Sendable {
+ let maximumSourcePixels: Int
+ let maximumSourceDimension: Int
+ /// One ceiling for every format, matching `VisionImageLimits`: a
+ /// source the model would refuse should not draw either.
+ let maximumDecodedBytes: Int
+ /// The decoders this is allowed to reach. Every other limit here was
+ /// copied from `VisionImageLimits` except this one, so a camera RAW or
+ /// EXR the runtime refuses still ran through ImageIO's decoder for it
+ /// inside the process holding the model.
+ let allowedTypeIdentifiers: Set<String>
+
+ public init(
+ maximumSourcePixels: Int,
+ maximumSourceDimension: Int,
+ maximumDecodedBytes: Int,
+ allowedTypeIdentifiers: Set<String>
+ ) {
+ self.maximumSourcePixels = maximumSourcePixels
+ self.maximumSourceDimension = maximumSourceDimension
+ self.maximumDecodedBytes = maximumDecodedBytes
+ self.allowedTypeIdentifiers = allowedTypeIdentifiers
+ }
+ }
+
+ /// A thumbnail bounded by `maximumPixelSize`, or nil when the file cannot be
+ /// read or its decode would exceed `budget`.
+ ///
+ /// Nil is the refusal, not an error: both callers already draw their
+ /// placeholder for an image that would not load, so a file the process
+ /// cannot afford costs a tile rather than the process.
+ ///
+ /// `cacheKey` identifies the *contents*, so callers pass the attachment's
+ /// digest rather than its path. Without it every redraw re-decoded the file:
+ /// the transcript rebuilds its prefix whenever the coordinator is recreated,
+ /// and `kCGImageSourceCreateThumbnailFromImageAlways` costs a full decode
+ /// for most formats. Omitting the key skips the cache entirely.
+ public static func thumbnail(
+ at url: URL,
+ maximumPixelSize: Int,
+ budget: Budget,
+ cacheKey: String? = nil
+ ) -> NSImage? {
+ let entry = cacheKey.map { "\($0)-\(maximumPixelSize)" as NSString }
+ if let entry, let cached = cache.storage.object(forKey: entry) { return cached }
+ let sourceOptions = [kCGImageSourceShouldCache: false] as CFDictionary
+ guard let source = CGImageSourceCreateWithURL(url as CFURL, sourceOptions) else {
+ return nil
+ }
+ // ImageIO sniffs the bytes, so this is the real format rather than the
+ // extension's claim. Checked before the budget because an unsupported
+ // format is refused whatever its size.
+ guard let typeIdentifier = CGImageSourceGetType(source) as String?,
+ budget.allowedTypeIdentifiers.contains(typeIdentifier) else {
+ return nil
+ }
+ guard fitsDecodeBudget(source, budget: budget) else { return nil }
+ let thumbnailOptions: [CFString: Any] = [
+ kCGImageSourceCreateThumbnailFromImageAlways: true,
+ kCGImageSourceCreateThumbnailWithTransform: true,
+ kCGImageSourceThumbnailMaxPixelSize: maximumPixelSize,
+ kCGImageSourceShouldCacheImmediately: true,
+ ]
+ guard let image = CGImageSourceCreateThumbnailAtIndex(
+ source, 0, thumbnailOptions as CFDictionary) else { return nil }
+ let result = NSImage(cgImage: image, size: .zero)
+ if let entry {
+ // NSCache so the decoded copies are the first thing released under
+ // pressure. They are a redraw convenience beside a resident model,
+ // never something worth holding against it.
+ cache.storage.setObject(result, forKey: entry,
+ cost: image.width * image.height * 4)
+ }
+ return result
+ }
+
+ /// Decoded copies only. Refusals are not cached: a file that failed the
+ /// budget is cheap to re-refuse, and caching nil would need a second map.
+ ///
+ /// `NSCache` is already thread-safe; the wrapper exists only to say so to
+ /// the compiler, since decoding runs off the main thread.
+ private final class ThumbnailCache: @unchecked Sendable {
+ let storage = NSCache<NSString, NSImage>()
+
+ init() {
+ storage.countLimit = 32
+ storage.totalCostLimit = 64 * 1_024 * 1_024
+ }
+ }
+
+ private static let cache = ThumbnailCache()
+
+ /// Drops every decoded copy, so one case's images cannot satisfy the next
+ /// one's lookup.
+ ///
+ /// This is a test hook, and deliberately not called when the app releases
+ /// the files these were decoded from: the release path lives in `AppModel`,
+ /// in `TurboFieldfareAppCore`, which this module depends on rather than the
+ /// other way round, so it cannot reach here. What bounds the cache in the
+ /// app is `ThumbnailCache` itself — 32 objects, 64 MB, and NSCache evicts
+ /// under memory pressure, which is the normal state beside a resident
+ /// model. Decoded copies of deleted files can therefore outlive them, up to
+ /// that ceiling. Say so rather than claim a call that does not exist.
+ public static func clearCache() {
+ cache.storage.removeAllObjects()
+ }
+
+ /// `kCGImageSourceCreateThumbnailFromImageAlways` costs whatever the full
+ /// decode costs for any format ImageIO cannot decode subsampled, so the
+ /// source is measured from its properties — which decode nothing — before a
+ /// thumbnail is asked for. A 50 MP PNG would otherwise spend about 200 MB
+ /// inside the process that also holds the ~1.4 GB model, to draw a tile a
+ /// few hundred pixels across.
+ private static func fitsDecodeBudget(
+ _ source: CGImageSource,
+ budget: Budget
+ ) -> Bool {
+ guard let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) else {
+ return false
+ }
+ let dictionary = properties as NSDictionary
+ guard let width = (dictionary[kCGImagePropertyPixelWidth] as? NSNumber)?.intValue,
+ let height = (dictionary[kCGImagePropertyPixelHeight] as? NSNumber)?.intValue,
+ width > 0, height > 0,
+ width <= budget.maximumSourceDimension,
+ height <= budget.maximumSourceDimension else {
+ return false
+ }
+ let (pixels, pixelOverflow) = width.multipliedReportingOverflow(by: height)
+ guard !pixelOverflow, pixels <= budget.maximumSourcePixels else { return false }
+ // Four channels is the decode target; source depth drives how much
+ // ImageIO materialises on the way there. Every step is overflow-checked
+ // because the depth comes from the file, not from us.
+ let depth = (dictionary[kCGImagePropertyDepth] as? NSNumber)?.intValue ?? 8
+ let (bytesPerPixel, depthOverflow) = max(1, depth / 8)
+ .multipliedReportingOverflow(by: 4)
+ guard !depthOverflow else { return false }
+ let (decodedBytes, byteOverflow) = pixels.multipliedReportingOverflow(
+ by: bytesPerPixel)
+ return !byteOverflow && decodedBytes <= budget.maximumDecodedBytes
+ }
+
+}
diff --git a/Sources/TurboFieldfareApp/MacPresentation/TranscriptImageTile.swift b/Sources/TurboFieldfareApp/MacPresentation/TranscriptImageTile.swift
new file mode 100644
index 00000000..ae1549d0
--- /dev/null
+++ b/Sources/TurboFieldfareApp/MacPresentation/TranscriptImageTile.swift
@@ -0,0 +1,33 @@
+import CoreGraphics
+
+/// Sizing for attached-image thumbnails.
+///
+/// The composer shows a row of them, and they have to read as one row. Fitting
+/// each image inside the tile preserved its shape but gave every attachment a
+/// different height, so the row was ragged and the remove badge — pinned to the
+/// tile corner — sat clear of the short ones. Filling the tile and cropping the
+/// overflow is what makes a row of mixed screenshots and photos look like a row.
+public enum TranscriptImageTile {
+ /// Largest size that fits inside `tile` with the aspect ratio kept, never
+ /// larger than the source. Used by the transcript, where images are laid out
+ /// inline and may be any shape.
+ ///
+ /// The clamp is what stops a 64 pt icon being drawn into a 240 pt canvas:
+ /// scaling up an attachment smaller than the tile only makes it blurry, and
+ /// "fits inside the tile" was never meant to mean "fills it".
+ public static func fittedSize(_ source: CGSize, within tile: CGSize) -> CGSize {
+ guard source.width > 0, source.height > 0 else { return tile }
+ let scale = min(tile.width / source.width, tile.height / source.height, 1)
+ return CGSize(width: max(1, source.width * scale),
+ height: max(1, source.height * scale))
+ }
+
+ /// Smallest size that covers `tile` with the aspect ratio kept. The excess
+ /// is cropped by the tile, which is the point.
+ public static func filledSize(_ source: CGSize, within tile: CGSize) -> CGSize {
+ guard source.width > 0, source.height > 0 else { return tile }
+ let scale = max(tile.width / source.width, tile.height / source.height)
+ return CGSize(width: max(1, source.width * scale),
+ height: max(1, source.height * scale))
+ }
+}
diff --git a/Sources/TurboFieldfareApp/MacPresentation/TranscriptScrollFollow.swift b/Sources/TurboFieldfareApp/MacPresentation/TranscriptScrollFollow.swift
new file mode 100644
index 00000000..64e1e978
--- /dev/null
+++ b/Sources/TurboFieldfareApp/MacPresentation/TranscriptScrollFollow.swift
@@ -0,0 +1,69 @@
+import CoreGraphics
+
+/// Decides whether the transcript should keep itself pinned to the bottom.
+///
+/// A new run is scrolled into view and held there until its answer starts,
+/// because the images in the prompt finish laying out after the first scroll
+/// and push the content down. The hard part is telling that growth apart from
+/// the reader scrolling back to look at something: both leave the view above
+/// the bottom, and treating the two the same is what broke it in each
+/// direction. Pinning on every tick made it impossible to scroll during
+/// prefill; ending the follow whenever the view was not at the bottom meant a
+/// prompt with several images stayed scrolled off the top, which is the case
+/// the follow exists for.
+///
+/// The discriminator is what moved. Images growing the document change its
+/// height and leave the scroll origin alone; a reader moves the origin while
+/// the height stays put.
+public struct TranscriptScrollFollow: Equatable, Sendable {
+ /// Anything smaller is rounding, not a scroll.
+ public static let tolerance: CGFloat = 0.5
+
+ public private(set) var isFollowing = false
+ private var lastOrigin: CGFloat?
+ private var lastHeight: CGFloat?
+
+ public init() {}
+
+ /// Starts a new run's follow. The previous run's geometry is not a baseline
+ /// for this one.
+ public mutating func beginRun() {
+ isFollowing = true
+ lastOrigin = nil
+ lastHeight = nil
+ }
+
+ /// Ends the follow: the answer has text, the run is over, or the reader
+ /// scrolled in a way the platform reported directly.
+ public mutating func end() {
+ isFollowing = false
+ }
+
+ /// Records where a programmatic scroll left the view. Without this the next
+ /// comparison reads our own scroll as the reader's.
+ public mutating func recordScroll(origin: CGFloat, documentHeight: CGFloat) {
+ lastOrigin = origin
+ lastHeight = documentHeight
+ }
+
+ /// True when the view moved and the document did not, which no layout pass
+ /// can cause.
+ public func readerMoved(origin: CGFloat, documentHeight: CGFloat) -> Bool {
+ guard let lastOrigin, let lastHeight else { return false }
+ guard abs(documentHeight - lastHeight) < Self.tolerance else { return false }
+ return abs(origin - lastOrigin) > Self.tolerance
+ }
+
+ /// The whole decision for one tick: whether to scroll now, having first let
+ /// the reader take over if they moved the view.
+ public mutating func shouldScrollToBottom(
+ origin: CGFloat, documentHeight: CGFloat
+ ) -> Bool {
+ guard isFollowing else { return false }
+ if readerMoved(origin: origin, documentHeight: documentHeight) {
+ isFollowing = false
+ return false
+ }
+ return true
+ }
+}
diff --git a/Sources/TurboFieldfareCLI/Args.swift b/Sources/TurboFieldfareCLI/Args.swift
index 0f20db8a..de719331 100644
--- a/Sources/TurboFieldfareCLI/Args.swift
+++ b/Sources/TurboFieldfareCLI/Args.swift
@@ -3,7 +3,11 @@ import TurboFieldfare
public struct Args: Equatable, Sendable {
public var model: String
public var prompt: String?
+ public var chatPrompt: String?
public var messagesFile: String?
+ public var images: [String]
+ public var visionPack: String?
+ public var visionResidency: VisionResidencyPolicy
public var maxNew: Int
public var maxContext: Int
public var temperature: Float
@@ -17,13 +21,20 @@ public struct Args: Equatable, Sendable {
public var expertCachePolicy: RuntimeExpertCachePolicy
public var prefillPolicy: RuntimePrefillPolicy
public var prefillChunkTokens: Int
+ /// `--prefill-chunk-tokens auto`: the size is decided once the prompt length
+ /// is known, which needs the tokenizer and, for images, their geometry.
+ public var prefillChunkTokensAuto: Bool
public var rdadvisePolicy: RDAdvicePolicyMode
public init(model: String,
prompt: String? = nil,
+ chatPrompt: String? = nil,
messagesFile: String? = nil,
+ images: [String] = [],
+ visionPack: String? = nil,
+ visionResidency: VisionResidencyPolicy = .defaultPolicy,
maxNew: Int = 1_024,
- maxContext: Int = 4096,
+ maxContext: Int = 8192,
temperature: Float = 0.2,
topK: Int? = 64,
topP: Float? = 0.95,
@@ -35,10 +46,15 @@ public struct Args: Equatable, Sendable {
expertCachePolicy: RuntimeExpertCachePolicy = RuntimeConfiguration.production.expertCachePolicy,
prefillPolicy: RuntimePrefillPolicy = RuntimeConfiguration.production.prefillPolicy,
prefillChunkTokens: Int = RuntimeConfiguration.production.prefillChunkTokens,
+ prefillChunkTokensAuto: Bool = false,
rdadvisePolicy: RDAdvicePolicyMode = RuntimeConfiguration.production.rdadvisePolicy) {
self.model = model
self.prompt = prompt
+ self.chatPrompt = chatPrompt
self.messagesFile = messagesFile
+ self.images = images
+ self.visionPack = visionPack
+ self.visionResidency = visionResidency
self.maxNew = maxNew
self.maxContext = maxContext
self.temperature = temperature
@@ -52,6 +68,7 @@ public struct Args: Equatable, Sendable {
self.expertCachePolicy = expertCachePolicy
self.prefillPolicy = prefillPolicy
self.prefillChunkTokens = prefillChunkTokens
+ self.prefillChunkTokensAuto = prefillChunkTokensAuto
self.rdadvisePolicy = rdadvisePolicy
}
}
@@ -64,6 +81,7 @@ public enum ArgsError: Error, Equatable, CustomStringConvertible {
case requiredMissing(String)
case mutuallyExclusive(String, String)
case modeMissing
+ case imagePromptNeedsExpertCacheSlots(have: Int, need: Int)
public var description: String {
switch self {
@@ -73,7 +91,12 @@ public enum ArgsError: Error, Equatable, CustomStringConvertible {
case .invalidValue(let flag, let value): return "invalid value for \(flag): \(value)"
case .requiredMissing(let flag): return "required flag missing: \(flag)"
case .mutuallyExclusive(let a, let b): return "\(a) and \(b) are mutually exclusive"
- case .modeMissing: return "one of --prompt or --messages-file is required"
+ case .modeMissing:
+ return "one of --prompt, --chat-prompt or --messages-file is required"
+ case .imagePromptNeedsExpertCacheSlots(let have, let need):
+ return "--image requires chunked prefill, which needs at least \(need) "
+ + "expert-cache slots; --expert-cache-slots \(have) cannot serve it: "
+ + "raise --expert-cache-slots to \(need) or more, or drop --image"
}
}
}
@@ -82,16 +105,23 @@ extension Args {
public static let usage = """
TurboFieldfareCLI — Gemma 4 26B-A4B text generation
- usage: TurboFieldfareCLI --model <dir> (--prompt <string> | --messages-file <path>) [options]
+ usage: TurboFieldfareCLI --model <dir>
+ (--prompt <string> | --chat-prompt <string> | --messages-file <path>) [options]
required:
--model <dir> Path to a .gturbo model directory.
--prompt <string> Raw-completion prompt.
+ --chat-prompt <string> Single-turn instruction chat; pairs with --image
--messages-file <path> JSON chat messages with role and content fields.
+ --image <path> Attach an image; repeatable. Needs --chat-prompt
+ and an installed companion pack.
+ --vision-pack <dir> Companion pack (default beside the model).
+ --vision-residency <on-demand|keep-ready>
+ Routed-expert residency during vision (default on-demand).
options:
--max-new <int> Generated-token limit (default 1024).
- --max-context <int> Context limit in tokens (default 4096).
+ --max-context <int> Context limit in tokens (default 8192).
--temperature <float> Sampling temperature (default 0.2; 0 = greedy).
--top-k <int> Top-k truncation, 1...256 (default 64; 0 = off).
--top-p <float> Nucleus truncation (default 0.95).
@@ -103,13 +133,29 @@ extension Args {
--expert-cache-policy <s> Expert-cache policy: lfu or lru (default lfu).
--prefill on|off Enable or disable chunked prompt prefill (default on).
Chunked prefill requires 16 or more cache slots.
- --prefill-chunk-tokens <n> Prefill chunk size: 32, 64, or 128 (default 128).
+ --prefill-chunk-tokens <n|auto>
+ Prefill chunk size: 32, 64, 128, 256, or auto
+ (default 128). Each chunk re-reads the routed
+ expert pool, so larger chunks read less; auto
+ picks the smallest size that covers the prompt.
--rdadvise <s> Read-advice policy: off, default, bounded, or adaptive (default off).
--help Show this message.
"""
public func resolvedRuntimeConfiguration(
- forceLogitsHead: Bool) throws -> RuntimeConfiguration {
+ forceLogitsHead: Bool,
+ imagePrompt: Bool = false) throws -> RuntimeConfiguration {
+ // Images reach the runtime two ways, `--image` and `image_file` parts
+ // inside `--messages-file`, and only the first fills `images`. Asking
+ // the caller keeps the second from surviving validation and dying in
+ // the routed tile scheduler after the model load and every GPU encode.
+ guard !imagePrompt
+ || expertCacheSlots
+ >= RuntimeConfiguration.minimumExpertCacheSlotsForChunkedPrefill else {
+ throw ArgsError.imagePromptNeedsExpertCacheSlots(
+ have: expertCacheSlots,
+ need: RuntimeConfiguration.minimumExpertCacheSlotsForChunkedPrefill)
+ }
guard RuntimeConfiguration.allowedExpertCacheSlots.contains(expertCacheSlots) else {
throw ArgsError.invalidValue(
flag: "--expert-cache-slots", value: "\(expertCacheSlots)")
@@ -137,9 +183,13 @@ extension Args {
public static func parse(_ argv: [String]) throws -> Args {
var model: String?
var prompt: String?
+ var chatPrompt: String?
var messagesFile: String?
+ var images: [String] = []
+ var visionPack: String?
+ var visionResidency: VisionResidencyPolicy = .defaultPolicy
var maxNew = 1_024
- var maxContext = 4096
+ var maxContext = 8192
var temperature: Float = 0.2
var topK: Int? = 64
var topP: Float? = 0.95
@@ -152,6 +202,7 @@ extension Args {
var expertCachePolicy = runtimeDefaults.expertCachePolicy
var prefillPolicy = runtimeDefaults.prefillPolicy
var prefillChunkTokens = runtimeDefaults.prefillChunkTokens
+ var prefillChunkTokensAuto = false
var rdadvisePolicy = runtimeDefaults.rdadvisePolicy
var index = 0
@@ -167,6 +218,18 @@ extension Args {
model = try takeValue(argv, &index, flag: flag)
case "--prompt":
prompt = try takeValue(argv, &index, flag: flag)
+ case "--chat-prompt":
+ chatPrompt = try takeValue(argv, &index, flag: flag)
+ case "--image":
+ images.append(try takeValue(argv, &index, flag: flag))
+ case "--vision-pack":
+ visionPack = try takeValue(argv, &index, flag: flag)
+ case "--vision-residency":
+ let value = try takeValue(argv, &index, flag: flag)
+ guard let policy = VisionResidencyPolicy(rawValue: value) else {
+ throw ArgsError.invalidValue(flag: flag, value: value)
+ }
+ visionResidency = policy
case "--messages-file":
messagesFile = try takeValue(argv, &index, flag: flag)
case "--max-new":
@@ -235,10 +298,15 @@ extension Args {
}
case "--prefill-chunk-tokens":
let value = try takeValue(argv, &index, flag: flag)
+ if value == "auto" {
+ prefillChunkTokensAuto = true
+ break
+ }
guard let parsed = Int(value),
RuntimeConfiguration.allowedPrefillChunkTokens.contains(parsed) else {
throw ArgsError.invalidValue(flag: flag, value: value)
}
+ prefillChunkTokensAuto = false
prefillChunkTokens = parsed
case "--rdadvise":
let value = try takeValue(argv, &index, flag: flag)
@@ -255,7 +323,31 @@ extension Args {
if prompt != nil && messagesFile != nil {
throw ArgsError.mutuallyExclusive("--prompt", "--messages-file")
}
- if prompt == nil && messagesFile == nil { throw ArgsError.modeMissing }
+ if prompt != nil, chatPrompt != nil {
+ throw ArgsError.mutuallyExclusive("--prompt", "--chat-prompt")
+ }
+ if messagesFile != nil, chatPrompt != nil {
+ throw ArgsError.mutuallyExclusive("--chat-prompt", "--messages-file")
+ }
+ if prompt != nil, !images.isEmpty {
+ throw ArgsError.mutuallyExclusive("--prompt", "--image")
+ }
+ let minimumSlots = RuntimeConfiguration.minimumExpertCacheSlotsForChunkedPrefill
+ if !images.isEmpty, expertCacheSlots < minimumSlots {
+ throw ArgsError.imagePromptNeedsExpertCacheSlots(
+ have: expertCacheSlots, need: minimumSlots)
+ }
+ if !images.isEmpty, chatPrompt == nil {
+ // Naming the flag the user actually left out. Reporting a conflict
+ // with `--messages-file` sent them looking for a flag they never
+ // passed, in the most likely first-run mistake there is.
+ throw messagesFile == nil
+ ? ArgsError.requiredMissing("--chat-prompt")
+ : ArgsError.mutuallyExclusive("--image", "--messages-file")
+ }
+ if prompt == nil && chatPrompt == nil && messagesFile == nil {
+ throw ArgsError.modeMissing
+ }
if temperature > 0, topK == nil, let topP, topP < 1 {
throw ArgsError.invalidValue(
flag: "--top-p",
@@ -263,7 +355,11 @@ extension Args {
}
let arguments = Args(model: model,
prompt: prompt,
+ chatPrompt: chatPrompt,
messagesFile: messagesFile,
+ images: images,
+ visionPack: visionPack,
+ visionResidency: visionResidency,
maxNew: maxNew,
maxContext: maxContext,
temperature: temperature,
@@ -277,6 +373,7 @@ extension Args {
expertCachePolicy: expertCachePolicy,
prefillPolicy: prefillPolicy,
prefillChunkTokens: prefillChunkTokens,
+ prefillChunkTokensAuto: prefillChunkTokensAuto,
rdadvisePolicy: rdadvisePolicy)
_ = try arguments.resolvedRuntimeConfiguration(forceLogitsHead: false)
return arguments
diff --git a/Sources/TurboFieldfareCLI/Run.swift b/Sources/TurboFieldfareCLI/Run.swift
index 068a0460..7b30406a 100644
--- a/Sources/TurboFieldfareCLI/Run.swift
+++ b/Sources/TurboFieldfareCLI/Run.swift
@@ -2,9 +2,44 @@ import Foundation
import Metal
import TurboFieldfare
+/// One row of the `--messages-file` JSON.
private struct MessageJSON: Decodable {
let role: String
- let content: String
+ let content: MessageContentJSON
+}
+
+private enum MessageContentJSON: Decodable {
+ case text(String)
+ case parts([MessagePartJSON])
+
+ init(from decoder: Decoder) throws {
+ let container = try decoder.singleValueContainer()
+ if let text = try? container.decode(String.self) {
+ self = .text(text)
+ } else {
+ self = .parts(try container.decode([MessagePartJSON].self))
+ }
+ }
+}
+
+private struct MessagePartJSON: Decodable {
+ let type: String
+ let text: String?
+ let path: String?
+}
+
+enum PromptInput {
+ case raw(String)
+ case messages([GFTokenizer.Message])
+ case multimodal(messages: [MultimodalMessage], images: [UUID: URL])
+
+ /// Whether this prompt carries images. `--messages-file` reaches the image
+ /// path with `args.images` empty, so the runtime checks that depend on
+ /// images ask the parsed input, not the flag list.
+ var hasImages: Bool {
+ if case .multimodal = self { return true }
+ return false
+ }
}
public struct RunResult: Equatable, Sendable {
@@ -17,48 +52,128 @@ public func run(args: Args,
stderr: FileHandle = .standardError) async -> RunResult {
do {
let modelURL = URL(fileURLWithPath: args.model)
- let tokenizer = try await GFTokenizer.load(forModelDirectory: modelURL)
- let promptIds: [Int32]
- if let rawPrompt = args.prompt {
- promptIds = tokenizer.encode(rawPrompt, addBOS: true)
- } else if let messagesFile = args.messagesFile {
- let data = try Data(contentsOf: URL(fileURLWithPath: messagesFile),
- options: [.mappedIfSafe])
- let rows = try JSONDecoder().decode([MessageJSON].self, from: data)
- let messages = try rows.map { row -> GFTokenizer.Message in
- guard let role = GFTokenizer.Role(rawValue: row.role) else {
- throw GFTokenizerError.invalidChatTemplate("unsupported role \(row.role)")
- }
- return GFTokenizer.Message(role: role, content: row.content)
+ let input = try parseInput(args: args)
+ var selectedDevice: MTLDevice?
+ if input.hasImages {
+ guard let device = MTLCreateSystemDefaultDevice() else {
+ return errored(stderr, "no Metal device", 1)
}
- let rendered = try tokenizer.applyChatTemplate(messages)
- promptIds = tokenizer.encode(rendered, addBOS: false)
- } else {
- return errored(stderr, "one of --prompt or --messages-file is required", 2)
+ try VisionRuntime.requireSupportedDevice(device)
+ selectedDevice = device
}
- guard !promptIds.isEmpty else { return errored(stderr, "empty prompt", 2) }
- guard promptIds.count < args.maxContext else {
+ let tokenizer = try await GFTokenizer.load(forModelDirectory: modelURL)
+ var promptIds: [Int32]
+ var multimodalMessages: [MultimodalMessage]?
+ var imageURLs: [UUID: URL] = [:]
+ switch input {
+ case .raw(let text):
+ multimodalMessages = nil
+ promptIds = tokenizer.encode(text, addBOS: true)
+ case .messages(let messages):
+ multimodalMessages = nil
+ promptIds = tokenizer.encode(
+ try tokenizer.applyChatTemplate(messages), addBOS: false)
+ case .multimodal(let messages, let images):
+ multimodalMessages = messages
+ imageURLs = images
+ // Filled in after the tower runs; the renderer needs the projected
+ // features to lay out the placeholder spans.
+ promptIds = []
+ }
+ if multimodalMessages == nil {
+ guard !promptIds.isEmpty else { return errored(stderr, "empty prompt", 2) }
+ }
+ guard multimodalMessages != nil || promptIds.count < args.maxContext else {
return errored(
stderr,
"context overflow: prompt \(promptIds.count) reaches maxContext \(args.maxContext)",
2)
}
- let effectiveMaxNew = min(args.maxNew, args.maxContext - promptIds.count)
- let config = GenerationConfig(
- maxNewTokens: effectiveMaxNew,
- temperature: args.temperature,
- topK: args.topK,
- topP: args.topP,
- repetitionPenalty: args.repetitionPenalty,
- seed: args.seed,
- stopStrings: args.stops,
- extraStopTokens: [])
+ func makeConfig(maxNewTokens: Int) -> GenerationConfig {
+ GenerationConfig(
+ maxNewTokens: maxNewTokens,
+ temperature: args.temperature,
+ topK: args.topK,
+ topP: args.topP,
+ repetitionPenalty: args.repetitionPenalty,
+ seed: args.seed,
+ stopStrings: args.stops,
+ extraStopTokens: [])
+ }
+ // Hoisted above the `auto` estimate, which needs a device to read image
+ // geometry. Planning never touches the GPU, but building the plan does
+ // need the device the run will use.
+ guard let device = selectedDevice ?? MTLCreateSystemDefaultDevice() else {
+ return errored(stderr, "no Metal device", 1)
+ }
+
+ var effectiveArgs = args
+ if args.prefillChunkTokensAuto {
+ let promptTokens = try estimatedPromptTokens(
+ input: input, tokenizer: tokenizer, device: device)
+ effectiveArgs.prefillChunkTokens =
+ PrefillRuntimeConfig.autoChunkTokens(promptTokens: promptTokens)
+ if !args.quiet {
+ let line = "[prefill chunk auto: "
+ + "\(effectiveArgs.prefillChunkTokens) tokens for a "
+ + "\(promptTokens)-token prompt]\n"
+ stderr.write(Data(line.utf8))
+ }
+ }
+ let args = effectiveArgs
let runtime = try args.resolvedRuntimeConfiguration(
- forceLogitsHead: !config.isPureGreedy)
+ forceLogitsHead: !makeConfig(maxNewTokens: args.maxNew).isPureGreedy,
+ imagePrompt: input.hasImages)
- guard MTLCreateSystemDefaultDevice() != nil else {
- return errored(stderr, "no Metal device", 1)
+ if !args.quiet,
+ let notice = prefillCoercionNotice(
+ hasImages: input.hasImages, config: runtime.prefillConfig) {
+ stderr.write(Data((notice + "\n").utf8))
+ }
+
+ // An image prompt that cannot fit is decided by geometry, so decide it
+ // before spending a model load and a GPU encode on it. The plan reads
+ // metadata only, and the same plan is reused at encode time so each
+ // image is opened and parsed once.
+ var imagePlans: [UUID: VisionImagePlan] = [:]
+ if let multimodalMessages {
+ // Dictionary order depends on a per-process hash seed, so planning
+ // straight from `imageURLs` named a different image on each run when
+ // two were bad. The prompt's own part order is the stable one.
+ let ordered = orderedImageIDs(messages: multimodalMessages, images: imageURLs)
+ // The device from the guard above, not a fresh `MetalContext`:
+ // building one compiles every shader module, and planning never
+ // touches the GPU.
+ let preprocessor = Gemma4ImagePreprocessor(device: device, config: VisionConfig())
+ var projected = 0
+ for id in ordered {
+ guard let url = imageURLs[id] else { continue }
+ let plan = try preprocessor.plan(fileURL: url)
+ imagePlans[id] = plan
+ projected += plan.geometry.softTokenCount
+ + VisionImageTokenBudget.markerTokensPerImage
+ }
+ // The text counts too. The tokenizer is already loaded, so this is
+ // free and it closes the common case: a prompt whose text overflows
+ // used to be refused only after the pack opened and every image had
+ // been encoded. A lower bound - the template's framing tokens are
+ // not counted - so it can only refuse what could never fit.
+ for message in multimodalMessages {
+ for part in message.content {
+ if case .text(let text) = part {
+ projected += tokenizer.encode(text, addBOS: false).count
+ }
+ }
+ }
+ guard projected < args.maxContext else {
+ return errored(
+ stderr,
+ "context overflow: prompt needs at least \(projected) tokens, "
+ + "which reaches maxContext \(args.maxContext)",
+ 2)
+ }
}
+
let context = try MetalContext()
let model = try Model.load(
directoryURL: modelURL,
@@ -73,10 +188,62 @@ public func run(args: Args,
runtimeConfiguration: runtime)
let scratch = try RawCompletionScratch(context: context,
vocab: model.config.vocabSize)
+ let multimodalInput: MultimodalPrefillInput?
+ if let multimodalMessages {
+ let vision = try VisionRuntime.open(
+ textModelURL: modelURL,
+ context: context,
+ visionPackURL: args.visionPack.map { URL(fileURLWithPath: $0) })
+ var features: [UUID: VisionFeatures] = [:]
+ features.reserveCapacity(imageURLs.count)
+ let visionStarted = ContinuousClock.now
+ for id in orderedImageIDs(messages: multimodalMessages, images: imageURLs) {
+ guard let url = imageURLs[id] else { continue }
+ try Task.checkCancellation()
+ if let plan = imagePlans[id] {
+ features[id] = try vision.encodeImage(
+ plan: plan,
+ languageModel: model,
+ residencyPolicy: args.visionResidency,
+ checkCancellation: { try Task.checkCancellation() })
+ } else {
+ features[id] = try vision.encodeImage(
+ at: url,
+ languageModel: model,
+ residencyPolicy: args.visionResidency,
+ checkCancellation: { try Task.checkCancellation() })
+ }
+ }
+ if !args.quiet {
+ let duration = visionStarted.duration(to: .now)
+ let seconds = Double(duration.components.seconds)
+ + Double(duration.components.attoseconds) / 1e18
+ stderr.write(Data(
+ "[vision images=\(imageURLs.count) encode=\(String(format: "%.3f", seconds))s]\n".utf8))
+ }
+ let rendered = try MultimodalPromptRenderer.render(
+ messages: multimodalMessages,
+ featuresByID: features,
+ tokenizer: tokenizer)
+ promptIds = rendered.effectiveTokenIDs
+ multimodalInput = rendered
+ guard promptIds.count < args.maxContext else {
+ return errored(
+ stderr,
+ "context overflow: prompt \(promptIds.count) reaches maxContext \(args.maxContext)",
+ 2)
+ }
+ } else {
+ multimodalInput = nil
+ }
+ let effectiveMaxNew = min(args.maxNew, args.maxContext - promptIds.count)
+ let config = makeConfig(maxNewTokens: effectiveMaxNew)
+
let stats = try await runRawCompletion(
producer: runner,
tokenizer: tokenizer,
promptIds: promptIds,
+ multimodalInput: multimodalInput,
config: config,
context: context,
scratch: scratch,
@@ -99,6 +266,12 @@ public func run(args: Args,
stderr.write(Data(footer.utf8))
}
return RunResult(exitCode: 0)
+ } catch let error as ArgsError {
+ return errored(stderr, "\(error)", 2)
+ } catch let error as VisionImageError {
+ return errored(stderr, "\(error)", 3)
+ } catch let error as VisionPackError {
+ return errored(stderr, "\(error)", 4)
} catch is CancellationError {
stdout.write(Data("\n".utf8))
return RunResult(exitCode: 130)
@@ -107,6 +280,175 @@ public func run(args: Args,
}
}
+
+/// The order the messages reference their images, so a repeated command plans
+/// and encodes them the same way every run.
+func orderedImageIDs(messages: [MultimodalMessage],
+ images: [UUID: URL]) -> [UUID] {
+ var ordered: [UUID] = []
+ var seen: Set<UUID> = []
+ for message in messages {
+ for part in message.content {
+ if case .image(let id) = part, images[id] != nil, seen.insert(id).inserted {
+ ordered.append(id)
+ }
+ }
+ }
+ for id in images.keys.sorted(by: { $0.uuidString < $1.uuidString })
+ where !seen.contains(id) {
+ ordered.append(id)
+ }
+ return ordered
+}
+
+/// The line to print when an image prompt overrides the requested prefill mode.
+///
+/// The override itself happens deep in `RawCompletion`, silently, while
+/// `RUNTIME_CONTROLS.md` says `--prefill off` disables that path. A flag that is
+/// ignored without a word is worse than one that is refused, so the CLI says it
+/// before the model loads.
+
+/// A prompt-length estimate good enough to choose a chunk size.
+///
+/// Deliberately cheap: it tokenises text and reads image geometry, and never
+/// loads the model. Being a little low only costs one extra chunk.
+func estimatedPromptTokens(
+ input: PromptInput,
+ tokenizer: GFTokenizer,
+ device: MTLDevice
+) throws -> Int {
+ switch input {
+ case .raw(let text):
+ return tokenizer.encode(text, addBOS: true).count
+ case .messages(let messages):
+ return tokenizer.encode(try tokenizer.applyChatTemplate(messages),
+ addBOS: false).count
+ case .multimodal(let messages, let images):
+ var total = 0
+ for message in messages {
+ for part in message.content {
+ if case .text(let text) = part {
+ total += tokenizer.encode(text, addBOS: false).count
+ }
+ }
+ }
+ let preprocessor = Gemma4ImagePreprocessor(
+ device: device, config: VisionConfig())
+ for url in images.values {
+ // Not `try?`: an image that cannot be planned would count as zero
+ // soft tokens, so `auto` would size the chunk for the text alone and
+ // put the multimodal prompt back on the many-chunk path this flag
+ // exists to avoid. An unplannable image fails the run anyway, and
+ // failing here says why, before the load.
+ total += try preprocessor.plan(fileURL: url).geometry.softTokenCount
+ total += VisionImageTokenBudget.markerTokensPerImage
+ }
+ return total
+ }
+}
+
+func prefillCoercionNotice(
+ hasImages: Bool, config: PrefillRuntimeConfig
+) -> String? {
+ guard hasImages, config.coercedForImagePrompt() != nil else { return nil }
+ return "[prefill coerced to chunked: image prompts require it]"
+}
+
+func parseInput(args: Args) throws -> PromptInput {
+ if let prompt = args.prompt {
+ return .raw(prompt)
+ }
+ if let chatPrompt = args.chatPrompt {
+ guard !args.images.isEmpty else {
+ return .messages([GFTokenizer.Message(role: .user, content: chatPrompt)])
+ }
+ var images: [UUID: URL] = [:]
+ var content: [MultimodalContentPart] = []
+ for path in args.images {
+ let id = UUID()
+ images[id] = URL(fileURLWithPath: path)
+ content.append(.image(id: id))
+ }
+ if !chatPrompt.isEmpty { content.append(.text(chatPrompt)) }
+ return .multimodal(
+ messages: [MultimodalMessage(role: .user, content: content)],
+ images: images)
+ }
+ guard let path = args.messagesFile else {
+ throw ArgsError.modeMissing
+ }
+ let url = URL(fileURLWithPath: path)
+ let data = try Data(contentsOf: url)
+ let rows = try JSONDecoder().decode([MessageJSON].self, from: data)
+ let base = url.deletingLastPathComponent()
+ var images: [UUID: URL] = [:]
+ let messages: [MultimodalMessage] = try rows.map { row in
+ guard let role = GFTokenizer.Role(rawValue: row.role) else {
+ throw ArgsError.invalidValue(flag: "--messages-file", value: "unknown role: \(row.role)")
+ }
+ let parts: [MultimodalContentPart]
+ switch row.content {
+ case .text(let text):
+ parts = [.text(text)]
+ case .parts(let rows):
+ parts = try rows.map { part in
+ switch part.type {
+ case "text":
+ guard let text = part.text else {
+ throw ArgsError.invalidValue(
+ flag: "--messages-file", value: "text part is missing text")
+ }
+ return .text(text)
+ case "image_file":
+ guard role == .user, let path = part.path else {
+ throw ArgsError.invalidValue(
+ flag: "--messages-file", value: "image_file requires a user role and path")
+ }
+ let id = UUID()
+ // Test the string, not a URL: `URL(fileURLWithPath:)`
+ // resolves against the process directory, so its `path` is
+ // always absolute and the relative branch never ran. A
+ // relative path belongs to the messages file's directory.
+ images[id] = path.hasPrefix("/")
+ ? URL(fileURLWithPath: path)
+ : base.appendingPathComponent(path)
+ return .image(id: id)
+ default:
+ throw ArgsError.invalidValue(
+ flag: "--messages-file", value: "unknown content type: \(part.type)")
+ }
+ }
+ }
+ return MultimodalMessage(role: role, content: parts)
+ }
+ if images.isEmpty {
+ return .messages(messages.map { message in
+ GFTokenizer.Message(
+ role: message.role,
+ content: message.content.compactMap {
+ if case .text(let text) = $0 { text } else { nil }
+ }.joined())
+ })
+ }
+ return .multimodal(messages: messages, images: images)
+}
+
+/// An image prompt's token count follows from geometry, so an oversized one can
+/// be refused in milliseconds instead of after a model load and a GPU encode.
+func validatePromptSize(
+ tokens: Int,
+ args: Args,
+ stderr: FileHandle
+) -> RunResult? {
+ guard tokens + args.maxNew <= args.maxContext else {
+ return errored(
+ stderr,
+ "context overflow: prompt \(tokens) + maxNew \(args.maxNew) exceeds maxContext \(args.maxContext)",
+ 2)
+ }
+ return nil
+}
+
private func errored(_ stderr: FileHandle, _ message: String, _ code: Int32) -> RunResult {
stderr.write(Data("error: \(message)\n".utf8))
return RunResult(exitCode: code)
diff --git a/Sources/TurboFieldfareDecodeProtocol/DecodeProtocol.swift b/Sources/TurboFieldfareDecodeProtocol/DecodeProtocol.swift
index 8276fb98..ae0a707c 100644
--- a/Sources/TurboFieldfareDecodeProtocol/DecodeProtocol.swift
+++ b/Sources/TurboFieldfareDecodeProtocol/DecodeProtocol.swift
@@ -7,19 +7,39 @@ public struct DecodeRuntimeOptions: Codable, Sendable, Equatable {
public var prefillChunkTokens: Int
public var rdadvisePolicy: String
public var modelVerification: String
+ public var visionResidencyPolicy: String?
public init(expertCacheSlots: Int = 16,
expertCachePolicy: String = "lfu",
prefillEnabled: Bool = true,
prefillChunkTokens: Int = 128,
rdadvisePolicy: String = "off",
- modelVerification: String = "full-sha256") {
+ modelVerification: String = "full-sha256",
+ visionResidencyPolicy: String? = nil) {
self.expertCacheSlots = expertCacheSlots
self.expertCachePolicy = expertCachePolicy
self.prefillEnabled = prefillEnabled
self.prefillChunkTokens = prefillChunkTokens
self.rdadvisePolicy = rdadvisePolicy
self.modelVerification = modelVerification
+ self.visionResidencyPolicy = visionResidencyPolicy
+ }
+}
+
+public struct DecodeImageAttachment: Codable, Sendable, Equatable {
+ public var id: UUID
+ public var path: String
+ public var displayName: String
+ public var encodedBytes: Int
+ public var sha256: String
+
+ public init(id: UUID, path: String, displayName: String,
+ encodedBytes: Int, sha256: String) {
+ self.id = id
+ self.path = path
+ self.displayName = displayName
+ self.encodedBytes = encodedBytes
+ self.sha256 = sha256
}
}
@@ -44,21 +64,35 @@ public struct DecodeLoadRequest: Codable, Sendable {
public struct DecodeGenerationRequest: Codable, Sendable {
public var prompt: String
+ public var imageAttachments: [DecodeImageAttachment]?
public var maxNewTokens: Int
public var maxContextTokens: Int
public var temperature: Float
+ /// Carried explicitly, and optional because nil means "no cut". Leaving
+ /// them off the wire did not fall back to the sender's settings: the
+ /// service rebuilt the request from its own initializer defaults, so
+ /// turning Top-K off, or setting any value other than 64 / 0.95, was
+ /// silently ignored on the only client the app ships with.
+ public var topK: Int?
+ public var topP: Float?
public var repetitionPenalty: Float
public var runtimeOptions: DecodeRuntimeOptions
public var generationID: UUID
- public init(prompt: String, maxNewTokens: Int, maxContextTokens: Int,
- temperature: Float, repetitionPenalty: Float = 1,
+ public init(prompt: String,
+ imageAttachments: [DecodeImageAttachment]? = nil,
+ maxNewTokens: Int, maxContextTokens: Int,
+ temperature: Float, topK: Int? = nil, topP: Float? = nil,
+ repetitionPenalty: Float = 1,
runtimeOptions: DecodeRuntimeOptions = DecodeRuntimeOptions(),
generationID: UUID = UUID()) {
self.prompt = prompt
+ self.imageAttachments = imageAttachments
self.maxNewTokens = maxNewTokens
self.maxContextTokens = maxContextTokens
self.temperature = temperature
+ self.topK = topK
+ self.topP = topP
self.repetitionPenalty = repetitionPenalty
self.runtimeOptions = runtimeOptions
self.generationID = generationID
@@ -78,6 +112,9 @@ public enum DecodeServiceEventKind: String, Codable, Sendable {
case ready
case prefill
case snapshot
+ /// Carries a live memory reading while image encoding or another silent
+ /// phase has not produced progress or tokens yet.
+ case memory
case finished
case cancelled
case failed
@@ -151,6 +188,9 @@ public struct DecodeServiceEvent: Codable, Sendable {
public var error: String?
public var currentMemoryBytes: UInt64?
public var peakMemoryBytes: UInt64?
+ /// Bytes of image tower the inference process holds mapped, or nil when
+ /// it has no vision runtime.
+ public var visionTowerMappedBytes: UInt64?
public var prefill: DecodePrefillDiagnostics?
public var runner: DecodeRunnerDiagnostics?
@@ -163,6 +203,7 @@ public struct DecodeServiceEvent: Codable, Sendable {
decodeSeconds: Double = 0, tokensPerSecond: Double = 0,
stopReason: String? = nil, error: String? = nil,
currentMemoryBytes: UInt64? = nil, peakMemoryBytes: UInt64? = nil,
+ visionTowerMappedBytes: UInt64? = nil,
prefill: DecodePrefillDiagnostics? = nil,
runner: DecodeRunnerDiagnostics? = nil) {
self.kind = kind
@@ -181,6 +222,7 @@ public struct DecodeServiceEvent: Codable, Sendable {
self.error = error
self.currentMemoryBytes = currentMemoryBytes
self.peakMemoryBytes = peakMemoryBytes
+ self.visionTowerMappedBytes = visionTowerMappedBytes
self.prefill = prefill
self.runner = runner
}
diff --git a/Sources/TurboFieldfareDecodeProtocol/DecodeUnixSocket.swift b/Sources/TurboFieldfareDecodeProtocol/DecodeUnixSocket.swift
index db8eaad1..5cd8c7c9 100644
--- a/Sources/TurboFieldfareDecodeProtocol/DecodeUnixSocket.swift
+++ b/Sources/TurboFieldfareDecodeProtocol/DecodeUnixSocket.swift
@@ -2,6 +2,22 @@ import Darwin
import Foundation
public enum DecodeUnixSocket {
+ /// Both ends write to a peer that can die at any time, so the signal has to
+ /// be off before the first write - otherwise a dead decode service takes
+ /// the app with it, and a dead app takes the service.
+ public static func ignoreSIGPIPEProcessWide() {
+ signal(SIGPIPE, SIG_IGN)
+ }
+
+ /// Per-descriptor belt to the process-wide braces above: it works on pipes
+ /// as well as sockets, and it survives anything that resets the handler.
+ public static func disableSIGPIPE(on descriptor: Int32) {
+ var enabled: Int32 = 1
+ _ = fcntl(descriptor, F_SETNOSIGPIPE, 1)
+ _ = setsockopt(descriptor, SOL_SOCKET, SO_NOSIGPIPE,
+ &enabled, socklen_t(MemoryLayout<Int32>.size))
+ }
+
public static func connect(path: String) throws -> (input: FileHandle, output: FileHandle) {
let fd = socket(AF_UNIX, SOCK_STREAM, 0)
guard fd >= 0 else { throw POSIXError(.init(rawValue: errno) ?? .EIO) }
@@ -24,6 +40,7 @@ public enum DecodeUnixSocket {
-> (input: FileHandle, output: FileHandle) {
let fd = socket(AF_UNIX, SOCK_STREAM, 0)
guard fd >= 0 else { throw POSIXError(.init(rawValue: errno) ?? .EIO) }
+ var listeningClosed = false
do {
var address = try makeAddress(path: path)
unlink(path)
@@ -33,22 +50,57 @@ public enum DecodeUnixSocket {
}
}
guard bindResult == 0 else { throw POSIXError(.init(rawValue: errno) ?? .EIO) }
+ // The socket lives in a world-writable directory, so without this
+ // any local user can connect in the window before the app does and
+ // drive the service.
+ guard chmod(path, 0o600) == 0 else {
+ throw POSIXError(.init(rawValue: errno) ?? .EIO)
+ }
guard listen(fd, 1) == 0 else { throw POSIXError(.init(rawValue: errno) ?? .EIO) }
- let accepted = Darwin.accept(fd, nil, nil)
- guard accepted >= 0 else { throw POSIXError(.init(rawValue: errno) ?? .EIO) }
+ let accepted = try acceptFromOwner(fd)
Darwin.close(fd)
- return try handles(for: accepted)
+ listeningClosed = true
+ do {
+ return try handles(for: accepted)
+ } catch {
+ Darwin.close(accepted)
+ throw error
+ }
} catch {
- Darwin.close(fd)
+ // The listening descriptor is closed once, at the handover. Closing
+ // it again here could close a number another thread now owns.
+ if !listeningClosed { Darwin.close(fd) }
unlink(path)
throw error
}
}
+ /// Accepts only a connection from this user, dropping anything else and
+ /// continuing to listen, so a probe cannot deny the real client its
+ /// connection.
+ private static func acceptFromOwner(_ listening: Int32) throws -> Int32 {
+ let owner = getuid()
+ while true {
+ let accepted = Darwin.accept(listening, nil, nil)
+ guard accepted >= 0 else {
+ if errno == EINTR { continue }
+ throw POSIXError(.init(rawValue: errno) ?? .EIO)
+ }
+ var peerUID = uid_t(0)
+ var peerGID = gid_t(0)
+ if getpeereid(accepted, &peerUID, &peerGID) == 0, peerUID == owner {
+ return accepted
+ }
+ Darwin.close(accepted)
+ }
+ }
+
private static func handles(for fd: Int32) throws
-> (input: FileHandle, output: FileHandle) {
let outputFD = dup(fd)
guard outputFD >= 0 else { throw POSIXError(.init(rawValue: errno) ?? .EIO) }
+ disableSIGPIPE(on: fd)
+ disableSIGPIPE(on: outputFD)
return (FileHandle(fileDescriptor: fd, closeOnDealloc: true),
FileHandle(fileDescriptor: outputFD, closeOnDealloc: true))
}
diff --git a/Sources/TurboFieldfareDecodeService/DecodeServiceOutbox.swift b/Sources/TurboFieldfareDecodeService/DecodeServiceOutbox.swift
index 5f65cd23..d3cd8a54 100644
--- a/Sources/TurboFieldfareDecodeService/DecodeServiceOutbox.swift
+++ b/Sources/TurboFieldfareDecodeService/DecodeServiceOutbox.swift
@@ -24,14 +24,25 @@ final class DecodeServiceOutbox: @unchecked Sendable {
private let generationID: UUID
private let memorySampler = AppMemorySampler()
- init(generationID: UUID) {
+ /// Bytes of image tower currently held mapped, or nil when there is no
+ /// vision runtime. Sampled per event so Keep Ready is visible while a run
+ /// is happening, not only in its final diagnostics.
+ private let towerBytes: @Sendable () -> UInt64?
+
+ init(generationID: UUID,
+ towerBytes: @escaping @Sendable () -> UInt64? = { nil }) {
self.generationID = generationID
+ self.towerBytes = towerBytes
memorySampler.resetPeak()
}
func publish(_ event: AppInferenceEvent) {
condition.lock()
switch event {
+ case .memorySample:
+ // The writer samples on its own schedule; an inbound reading is the
+ // runtime's, and there is nothing to queue.
+ break
case .prefillProgress(let done, let total):
state.latestPrefill = PrefillProgress(done: done, total: total)
condition.signal()
@@ -98,11 +109,25 @@ final class DecodeServiceOutbox: @unchecked Sendable {
}
condition.unlock()
+ _ = memorySampler.sample()
+
+ if prefill == nil, text.isEmpty, token == nil, terminal == nil, !done {
+ let snapshot = DecodeServiceEvent(
+ kind: .memory, generationID: generationID,
+ currentMemoryBytes: memorySampler.sample(),
+ peakMemoryBytes: memorySampler.peakBytes,
+ visionTowerMappedBytes: towerBytes())
+ try handle.write(contentsOf: DecodeFrameCodec.encode(snapshot))
+ continue
+ }
if let prefill, let prefillSequence {
let snapshot = DecodeServiceEvent(
kind: .prefill, generationID: generationID,
sequence: prefillSequence,
- prefillDone: prefill.done, prefillTotal: prefill.total)
+ prefillDone: prefill.done, prefillTotal: prefill.total,
+ currentMemoryBytes: memorySampler.sample(),
+ peakMemoryBytes: memorySampler.peakBytes,
+ visionTowerMappedBytes: towerBytes())
try handle.write(contentsOf: DecodeFrameCodec.encode(snapshot))
}
if !text.isEmpty || token != nil {
@@ -114,14 +139,15 @@ final class DecodeServiceOutbox: @unchecked Sendable {
decodeSeconds: elapsed,
tokensPerSecond: elapsed > 0 ? Double(count) / elapsed : 0,
currentMemoryBytes: memorySampler.sample(),
- peakMemoryBytes: memorySampler.peakBytes)
+ peakMemoryBytes: memorySampler.peakBytes,
+ visionTowerMappedBytes: towerBytes())
try handle.write(contentsOf: DecodeFrameCodec.encode(snapshot))
}
if let terminal {
try handle.write(contentsOf: DecodeFrameCodec.encode(terminal))
}
- if done, terminal == nil { return }
- if terminal != nil && done { return }
+ if terminal != nil { return }
+ if done { return }
}
}
@@ -140,6 +166,7 @@ final class DecodeServiceOutbox: @unchecked Sendable {
error: error,
currentMemoryBytes: memorySampler.sample(),
peakMemoryBytes: memorySampler.peakBytes,
+ visionTowerMappedBytes: diagnostics?.visionTowerMappedBytes,
prefill: diagnostics?.prefill.map(Self.prefillDiagnostics),
runner: diagnostics?.runner.map(Self.runnerDiagnostics))
}
diff --git a/Sources/TurboFieldfareDecodeService/Entry.swift b/Sources/TurboFieldfareDecodeService/Entry.swift
index 202be99e..14cf4d2d 100644
--- a/Sources/TurboFieldfareDecodeService/Entry.swift
+++ b/Sources/TurboFieldfareDecodeService/Entry.swift
@@ -1,8 +1,20 @@
import Darwin
+import TurboFieldfare
import Foundation
import TurboFieldfareAppCore
import TurboFieldfareDecodeProtocol
+enum DecodeServiceError: Error, CustomStringConvertible {
+ case attachmentOutsideStore(path: String)
+
+ var description: String {
+ switch self {
+ case .attachmentOutsideStore(let path):
+ "image attachment is not a staged attachment: \(path)"
+ }
+ }
+}
+
@main enum TurboFieldfareDecodeServiceMain {
static func main() async {
let socketPath = argument(after: "--socket")
@@ -23,6 +35,7 @@ import TurboFieldfareDecodeProtocol
if let launchLabel { retireLaunchJob(launchLabel) }
}
+ DecodeUnixSocket.ignoreSIGPIPEProcessWide()
let client = RealInferenceClient()
let commands = DecodeCommandQueue()
let input = Thread {
@@ -74,7 +87,15 @@ import TurboFieldfareDecodeProtocol
error: "model is not loaded"), to: handles.output)
continue
}
- guard request.runtimeOptions == loadedOptions else {
+ // Prefill is chosen per request, not at load, so it must not be
+ // part of this comparison: toggling it and pressing Generate was
+ // refused as a mismatched session.
+ var comparable = request.runtimeOptions
+ comparable.prefillEnabled = loadedOptions?.prefillEnabled
+ ?? comparable.prefillEnabled
+ comparable.prefillChunkTokens = loadedOptions?.prefillChunkTokens
+ ?? comparable.prefillChunkTokens
+ guard comparable == loadedOptions else {
try? write(DecodeServiceEvent(
kind: .failed, generationID: request.generationID,
error: "generation runtime options do not match the loaded session"),
@@ -82,7 +103,9 @@ import TurboFieldfareDecodeProtocol
continue
}
- let outbox = DecodeServiceOutbox(generationID: request.generationID)
+ let outbox = DecodeServiceOutbox(
+ generationID: request.generationID,
+ towerBytes: { client.currentVisionTowerBytes })
let writerFinished = DispatchSemaphore(value: 0)
let writer = Thread {
defer { writerFinished.signal() }
@@ -96,12 +119,32 @@ import TurboFieldfareDecodeProtocol
writer.start()
do {
+ // The trust boundary: these paths arrive over a socket, and
+ // this process opens and hashes whatever they name. Without
+ // this, a peer could use the service to report on any file
+ // the user can read.
+ if let outside = (request.imageAttachments ?? []).first(where: {
+ !AppImageAttachmentStore.contains(URL(fileURLWithPath: $0.path))
+ }) {
+ throw DecodeServiceError.attachmentOutsideStore(
+ path: outside.path)
+ }
let options = try appRuntimeOptions(request.runtimeOptions)
let generation = AppGenerationRequest(
modelDirectory: modelDirectory, prompt: request.prompt,
+ imageAttachments: (request.imageAttachments ?? []).map {
+ AppImageAttachment(
+ id: $0.id,
+ fileURL: URL(fileURLWithPath: $0.path),
+ displayName: $0.displayName,
+ encodedBytes: $0.encodedBytes,
+ sha256: $0.sha256)
+ },
maxNewTokens: request.maxNewTokens,
maxContextTokens: request.maxContextTokens,
temperature: request.temperature,
+ topK: request.topK,
+ topP: request.topP,
repetitionPenalty: request.repetitionPenalty,
runtimeOptions: options)
for try await event in client.generate(generation) {
@@ -163,13 +206,22 @@ import TurboFieldfareDecodeProtocol
throw AppInferenceError.invalidRequest(
"unknown model verification \(options.modelVerification)")
}
+ // An unknown policy is a request for behaviour that does not exist;
+ // absent means the shipped default.
+ guard let visionResidencyPolicy = VisionResidencyPolicy(
+ rawValue: options.visionResidencyPolicy ?? VisionResidencyPolicy.onDemand.rawValue)
+ else {
+ throw AppInferenceError.invalidRequest(
+ "unknown vision residency policy \(options.visionResidencyPolicy ?? "")")
+ }
let resolved = AppRuntimeOptions(
expertCacheSlots: options.expertCacheSlots,
expertCachePolicy: cachePolicy,
prefillEnabled: options.prefillEnabled,
prefillChunkTokens: options.prefillChunkTokens,
rdadvisePolicy: rdadvisePolicy,
- modelVerification: modelVerification)
+ modelVerification: modelVerification,
+ visionResidencyPolicy: visionResidencyPolicy)
try resolved.validate()
return resolved
}
diff --git a/Sources/TurboFieldfareFormat/GTurboVisionFormatV1.swift b/Sources/TurboFieldfareFormat/GTurboVisionFormatV1.swift
new file mode 100644
index 00000000..507781ed
--- /dev/null
+++ b/Sources/TurboFieldfareFormat/GTurboVisionFormatV1.swift
@@ -0,0 +1,404 @@
+import Foundation
+
+package enum GTurboVisionFormatV1 {
+ package static let magic = "GTURBO-VISION"
+ package static let artifactKind = "gemma4_vision_companion"
+ package static let versionMajor = 1
+ package static let versionMinor = 0
+ package static let alignmentBytes: UInt64 = 16_384
+ package static let metadataMaxBytes: UInt64 = 4 * 1024 * 1024
+ package static let weightsFile = "vision_weights.bin"
+ package static let processorFile = "processor_config.json"
+ package static let manifestFile = "manifest.json"
+ package static let receiptFile = "verified-install.json"
+ /// Whether an entry is something the OS wrote beside the pack rather than
+ /// part of it.
+ ///
+ /// Naming `.DS_Store` alone fixed one case and left every other sidecar:
+ /// a pack round-tripped through ExFAT, SMB or an archive carries
+ /// AppleDouble companions (`._manifest.json`), and Spotlight and iCloud
+ /// leave their own. Each of those made a pack whose manifest, receipt,
+ /// sizes and SHA-256 all verified fail to open, reporting that image
+ /// support was unavailable. The cryptographic checks are what establish the
+ /// pack is intact; an unexpected neighbour does not disprove it.
+ package static func isSidecarEntry(_ name: String) -> Bool {
+ name == ".DS_Store"
+ || name.hasPrefix("._")
+ || name.hasPrefix(".Spotlight-")
+ || name.hasPrefix(".fseventsd")
+ || name.hasPrefix(".TemporaryItems")
+ || name.hasSuffix(".icloud")
+ }
+
+ /// A directory mismatch stated in both directions. Reporting only what is
+ /// present labels the *surviving* files "unexpected" when the real problem
+ /// is a deleted one, which is the opposite of what the reader needs.
+ package static func entryDifference(
+ expected: Set<String>, actual: Set<String>
+ ) -> String {
+ let missing = expected.subtracting(actual).sorted()
+ let unexpected = actual.subtracting(expected).sorted()
+ var parts: [String] = []
+ if !missing.isEmpty { parts.append("missing \(missing)") }
+ if !unexpected.isEmpty { parts.append("unexpected \(unexpected)") }
+ return parts.isEmpty ? "entries differ" : parts.joined(separator: ", ")
+ }
+}
+
+package enum GTurboVisionDTypeV1: String, Codable, Equatable, Sendable {
+ case u32
+ case bf16
+
+ fileprivate var elementBytes: UInt64 {
+ switch self {
+ case .u32: 4
+ case .bf16: 2
+ }
+ }
+}
+
+package struct GTurboVisionQuantizationV1: Codable, Equatable, Sendable {
+ package let weightBits: Int
+ package let scheme: String
+ package let scaleType: String
+ package let biasType: String
+ package let groupSize: Int
+
+ package init(weightBits: Int, scheme: String, scaleType: String,
+ biasType: String, groupSize: Int) {
+ self.weightBits = weightBits
+ self.scheme = scheme
+ self.scaleType = scaleType
+ self.biasType = biasType
+ self.groupSize = groupSize
+ }
+}
+
+package struct GTurboVisionTensorRegionV1: Codable, Equatable, Sendable {
+ package let name: String
+ package let executionPosition: Int
+ package let file: String
+ package let offset: UInt64
+ package let size: UInt64
+ package let shape: [UInt64]
+ package let dtype: GTurboVisionDTypeV1
+ package let quantization: GTurboVisionQuantizationV1?
+
+ package init(name: String, executionPosition: Int,
+ file: String = GTurboVisionFormatV1.weightsFile,
+ offset: UInt64, size: UInt64, shape: [UInt64],
+ dtype: GTurboVisionDTypeV1,
+ quantization: GTurboVisionQuantizationV1? = nil) {
+ self.name = name
+ self.executionPosition = executionPosition
+ self.file = file
+ self.offset = offset
+ self.size = size
+ self.shape = shape
+ self.dtype = dtype
+ self.quantization = quantization
+ }
+}
+
+package struct GTurboVisionManifestV1: Codable, Equatable, Sendable {
+ package let magic: String
+ package let artifactKind: String
+ package let versionMajor: Int
+ package let versionMinor: Int
+ package let modelID: String
+ package let sourceRevision: String
+ package let sourceIndexSha256: String
+ package let processorConfigSha256: String
+ package let compatibleTextSourceSnapshotHash: String
+ package let compatibleTextManifestSha256: String
+ package let files: [String: GTurboManifestFileV1]
+ package let tensors: [GTurboVisionTensorRegionV1]
+
+ package init(magic: String = GTurboVisionFormatV1.magic,
+ artifactKind: String = GTurboVisionFormatV1.artifactKind,
+ versionMajor: Int = GTurboVisionFormatV1.versionMajor,
+ versionMinor: Int = GTurboVisionFormatV1.versionMinor,
+ modelID: String, sourceRevision: String,
+ sourceIndexSha256: String, processorConfigSha256: String,
+ compatibleTextSourceSnapshotHash: String,
+ compatibleTextManifestSha256: String,
+ files: [String: GTurboManifestFileV1],
+ tensors: [GTurboVisionTensorRegionV1]) {
+ self.magic = magic
+ self.artifactKind = artifactKind
+ self.versionMajor = versionMajor
+ self.versionMinor = versionMinor
+ self.modelID = modelID
+ self.sourceRevision = sourceRevision
+ self.sourceIndexSha256 = sourceIndexSha256
+ self.processorConfigSha256 = processorConfigSha256
+ self.compatibleTextSourceSnapshotHash = compatibleTextSourceSnapshotHash
+ self.compatibleTextManifestSha256 = compatibleTextManifestSha256
+ self.files = files
+ self.tensors = tensors
+ }
+}
+
+package enum GTurboVisionManifestCodec {
+ package static func decode(_ data: Data) throws -> GTurboVisionManifestV1 {
+ guard UInt64(data.count) <= GTurboVisionFormatV1.metadataMaxBytes else {
+ throw GTurboFormatError.invalid(
+ field: GTurboVisionFormatV1.manifestFile, reason: "metadata exceeds 4 MiB")
+ }
+ let manifest: GTurboVisionManifestV1
+ do { manifest = try JSONDecoder().decode(GTurboVisionManifestV1.self, from: data) }
+ catch {
+ throw GTurboFormatError.invalid(
+ field: GTurboVisionFormatV1.manifestFile, reason: "\(error)")
+ }
+ try GTurboVisionStructuralValidator.validate(manifest)
+ return manifest
+ }
+
+ package static func encode(_ manifest: GTurboVisionManifestV1) throws -> Data {
+ try GTurboVisionStructuralValidator.validate(manifest)
+ let encoder = JSONEncoder()
+ do {
+ let object = try JSONSerialization.jsonObject(with: encoder.encode(manifest))
+ let data = try JSONSerialization.data(
+ withJSONObject: object,
+ options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes])
+ guard UInt64(data.count) <= GTurboVisionFormatV1.metadataMaxBytes else {
+ throw GTurboFormatError.invalid(
+ field: GTurboVisionFormatV1.manifestFile, reason: "metadata exceeds 4 MiB")
+ }
+ return data
+ } catch let error as GTurboFormatError {
+ throw error
+ } catch {
+ throw GTurboFormatError.invalid(
+ field: GTurboVisionFormatV1.manifestFile, reason: "\(error)")
+ }
+ }
+}
+
+package enum GTurboVisionStructuralValidator {
+ package static func validate(_ manifest: GTurboVisionManifestV1) throws {
+ guard manifest.magic == GTurboVisionFormatV1.magic,
+ manifest.artifactKind == GTurboVisionFormatV1.artifactKind else {
+ throw GTurboFormatError.invalid(field: "vision.manifest.identity",
+ reason: "unsupported artifact")
+ }
+ guard manifest.versionMajor == GTurboVisionFormatV1.versionMajor,
+ manifest.versionMinor == GTurboVisionFormatV1.versionMinor else {
+ throw GTurboFormatError.invalid(field: "vision.manifest.version",
+ reason: "unsupported version")
+ }
+ guard !manifest.modelID.isEmpty, !manifest.sourceRevision.isEmpty,
+ !manifest.compatibleTextSourceSnapshotHash.isEmpty else {
+ throw GTurboFormatError.invalid(field: "vision.manifest",
+ reason: "missing source identity")
+ }
+ try validateSHA(manifest.sourceIndexSha256, field: "vision.sourceIndexSha256")
+ try validateSHA(manifest.processorConfigSha256, field: "vision.processorConfigSha256")
+ try validateSHA(manifest.compatibleTextManifestSha256,
+ field: "vision.compatibleTextManifestSha256")
+
+ let expectedFiles = Set([
+ GTurboVisionFormatV1.weightsFile,
+ GTurboVisionFormatV1.processorFile,
+ ])
+ guard Set(manifest.files.keys) == expectedFiles else {
+ throw GTurboFormatError.invalid(field: "vision.manifest.files",
+ reason: "expected exactly two payload files")
+ }
+ var filesystemKeys = Set<String>()
+ for path in manifest.files.keys {
+ try GTurboPathValidator.validateBasename(path, field: "vision.manifest.files.\(path)")
+ guard filesystemKeys.insert(GTurboPathValidator.appleFilesystemKey(path)).inserted else {
+ throw GTurboFormatError.invalid(field: "vision.manifest.files.\(path)",
+ reason: "filesystem-equivalent duplicate path")
+ }
+ try validateSHA(manifest.files[path]!.sha256,
+ field: "vision.manifest.files.\(path).sha256")
+ }
+
+ guard !manifest.tensors.isEmpty else {
+ throw GTurboFormatError.invalid(field: "vision.manifest.tensors",
+ reason: "expected at least one tensor")
+ }
+ var names = Set<String>()
+ var previousEnd: UInt64 = 0
+ let weightsSize = manifest.files[GTurboVisionFormatV1.weightsFile]!.size
+ for (index, tensor) in manifest.tensors.enumerated() {
+ guard !tensor.name.isEmpty, !tensor.name.contains("\0"),
+ names.insert(tensor.name).inserted else {
+ throw GTurboFormatError.invalid(field: "vision.tensor.name",
+ reason: "empty or duplicate tensor name")
+ }
+ guard tensor.executionPosition == index else {
+ throw GTurboFormatError.invalid(field: "vision.tensor.executionPosition",
+ reason: "regions are reordered or duplicated")
+ }
+ guard tensor.file == GTurboVisionFormatV1.weightsFile else {
+ throw GTurboFormatError.invalid(field: "vision.tensor.file",
+ reason: "tensor must use vision_weights.bin")
+ }
+ guard tensor.offset % GTurboVisionFormatV1.alignmentBytes == 0,
+ tensor.offset >= previousEnd else {
+ throw GTurboFormatError.invalid(field: "vision.tensor.offset",
+ reason: "misaligned or overlapping region")
+ }
+ guard !tensor.shape.isEmpty, tensor.shape.allSatisfy({ $0 > 0 }) else {
+ throw GTurboFormatError.invalid(field: "vision.tensor.shape",
+ reason: "invalid shape")
+ }
+ var elements: UInt64 = 1
+ for dimension in tensor.shape {
+ elements = try gturboCheckedMultiply(
+ elements, dimension, field: "vision.tensor.shape")
+ }
+ let expectedSize = try gturboCheckedMultiply(
+ elements, tensor.dtype.elementBytes, field: "vision.tensor.size")
+ guard tensor.size == expectedSize else {
+ throw GTurboFormatError.invalid(field: "vision.tensor.size",
+ reason: "size does not match storage shape")
+ }
+ switch (tensor.dtype, tensor.quantization) {
+ case (.bf16, nil):
+ break
+ case let (.u32, quantization?):
+ guard quantization.weightBits == 4,
+ quantization.scheme == "affine",
+ quantization.scaleType == "bf16",
+ quantization.biasType == "bf16",
+ quantization.groupSize == 64 else {
+ throw GTurboFormatError.invalid(field: "vision.tensor.quantization",
+ reason: "unsupported quantization")
+ }
+ default:
+ throw GTurboFormatError.invalid(field: "vision.tensor.quantization",
+ reason: "dtype and quantization disagree")
+ }
+ let end = try gturboCheckedAdd(tensor.offset, tensor.size,
+ field: "vision.tensor.range")
+ guard end <= weightsSize else {
+ throw GTurboFormatError.invalid(field: "vision.tensor.range",
+ reason: "region exceeds vision_weights.bin")
+ }
+ previousEnd = end
+ }
+ }
+
+ private static func validateSHA(_ value: String, field: String) throws {
+ guard value.count == 64,
+ value.unicodeScalars.allSatisfy({
+ (48...57).contains($0.value) || (65...70).contains($0.value)
+ || (97...102).contains($0.value)
+ }) else {
+ throw GTurboFormatError.invalid(field: field,
+ reason: "expected 64 hexadecimal characters")
+ }
+ }
+}
+
+package struct GTurboVisionReceiptV1: Codable, Equatable, Sendable {
+ package let schemaVersion: Int
+ package let artifactKind: String
+ package let manifestSha256: String
+ package let companionDirectoryPath: String
+ package let compatibleTextManifestSha256: String
+ package let sourceRepoID: String
+ package let sourceRevision: String
+ package let verificationTimestamp: String
+ package let toolVersion: String
+ package let files: [String: GTurboManifestFileV1]
+
+ package init(schemaVersion: Int = 1,
+ artifactKind: String = GTurboVisionFormatV1.artifactKind,
+ manifestSha256: String, companionDirectoryPath: String,
+ compatibleTextManifestSha256: String,
+ sourceRepoID: String, sourceRevision: String,
+ verificationTimestamp: String, toolVersion: String,
+ files: [String: GTurboManifestFileV1]) {
+ self.schemaVersion = schemaVersion
+ self.artifactKind = artifactKind
+ self.manifestSha256 = manifestSha256
+ self.companionDirectoryPath = companionDirectoryPath
+ self.compatibleTextManifestSha256 = compatibleTextManifestSha256
+ self.sourceRepoID = sourceRepoID
+ self.sourceRevision = sourceRevision
+ self.verificationTimestamp = verificationTimestamp
+ self.toolVersion = toolVersion
+ self.files = files
+ }
+}
+
+package enum GTurboVisionReceiptCodec {
+ package static func decode(_ data: Data) throws -> GTurboVisionReceiptV1 {
+ guard UInt64(data.count) <= GTurboVisionFormatV1.metadataMaxBytes else {
+ throw GTurboFormatError.invalid(field: GTurboVisionFormatV1.receiptFile,
+ reason: "metadata exceeds 4 MiB")
+ }
+ let receipt: GTurboVisionReceiptV1
+ do { receipt = try JSONDecoder().decode(GTurboVisionReceiptV1.self, from: data) }
+ catch {
+ throw GTurboFormatError.invalid(field: GTurboVisionFormatV1.receiptFile,
+ reason: "\(error)")
+ }
+ try validate(receipt)
+ return receipt
+ }
+
+ package static func encode(_ receipt: GTurboVisionReceiptV1) throws -> Data {
+ try validate(receipt)
+ let encoder = JSONEncoder()
+ do {
+ let object = try JSONSerialization.jsonObject(with: encoder.encode(receipt))
+ let data = try JSONSerialization.data(
+ withJSONObject: object,
+ options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes])
+ guard UInt64(data.count) <= GTurboVisionFormatV1.metadataMaxBytes else {
+ throw GTurboFormatError.invalid(field: GTurboVisionFormatV1.receiptFile,
+ reason: "metadata exceeds 4 MiB")
+ }
+ return data
+ } catch let error as GTurboFormatError {
+ throw error
+ } catch {
+ throw GTurboFormatError.invalid(field: GTurboVisionFormatV1.receiptFile,
+ reason: "\(error)")
+ }
+ }
+
+ private static func validate(_ receipt: GTurboVisionReceiptV1) throws {
+ guard receipt.schemaVersion == 1,
+ receipt.artifactKind == GTurboVisionFormatV1.artifactKind,
+ !receipt.companionDirectoryPath.isEmpty,
+ !receipt.sourceRepoID.isEmpty, !receipt.sourceRevision.isEmpty,
+ !receipt.verificationTimestamp.isEmpty, !receipt.toolVersion.isEmpty else {
+ throw GTurboFormatError.invalid(field: "vision.receipt",
+ reason: "invalid identity")
+ }
+ try GTurboVisionStructuralValidator.validateReceiptSHA(
+ receipt.manifestSha256, field: "vision.receipt.manifestSha256")
+ try GTurboVisionStructuralValidator.validateReceiptSHA(
+ receipt.compatibleTextManifestSha256,
+ field: "vision.receipt.compatibleTextManifestSha256")
+ let expected = Set([
+ GTurboVisionFormatV1.manifestFile,
+ GTurboVisionFormatV1.weightsFile,
+ GTurboVisionFormatV1.processorFile,
+ ])
+ guard Set(receipt.files.keys) == expected else {
+ throw GTurboFormatError.invalid(field: "vision.receipt.files",
+ reason: "file set mismatch")
+ }
+ for (path, file) in receipt.files {
+ try GTurboPathValidator.validateBasename(path, field: "vision.receipt.files.\(path)")
+ try GTurboVisionStructuralValidator.validateReceiptSHA(
+ file.sha256, field: "vision.receipt.files.\(path).sha256")
+ }
+ }
+}
+
+private extension GTurboVisionStructuralValidator {
+ static func validateReceiptSHA(_ value: String, field: String) throws {
+ try validateSHA(value, field: field)
+ }
+}
diff --git a/Sources/TurboFieldfareFormat/GTurboVisionLockPathsV1.swift b/Sources/TurboFieldfareFormat/GTurboVisionLockPathsV1.swift
new file mode 100644
index 00000000..71f267c7
--- /dev/null
+++ b/Sources/TurboFieldfareFormat/GTurboVisionLockPathsV1.swift
@@ -0,0 +1,30 @@
+import Darwin
+import Foundation
+
+/// Lock-file path derivation shared by every process that synchronizes on a
+/// vision companion pack. The reader's shared use lease and a writer's
+/// exclusive mutation lock must lock the same file, and a derivation mismatch
+/// does not fail loudly — it silently leaves the two sides locking different
+/// files — so the derivation lives here, next to the format it protects,
+/// instead of being duplicated per module.
+package enum GTurboVisionLockPathsV1 {
+ /// `.<companion-basename>.use.lock` beside the companion, with the parent
+ /// resolved physically so a symlinked path and its target derive the same
+ /// lock file.
+ package static func useLockURL(forCompanion companionURL: URL) -> URL {
+ let companion = companionURL.standardizedFileURL
+ let parent = companion.deletingLastPathComponent()
+ let resolvedParent: URL
+ if let resolved = realpath(parent.path, nil) {
+ defer { free(resolved) }
+ resolvedParent = URL(fileURLWithPath: String(cString: resolved),
+ isDirectory: true)
+ } else {
+ // The parent does not exist yet; the caller's `open` will fail
+ // and say so.
+ resolvedParent = parent.resolvingSymlinksInPath()
+ }
+ return resolvedParent
+ .appendingPathComponent(".\(companion.lastPathComponent).use.lock")
+ }
+}
diff --git a/Sources/TurboFieldfareRepack/Command/main.swift b/Sources/TurboFieldfareRepack/Command/main.swift
index ccf5ad6f..f7db6acf 100644
--- a/Sources/TurboFieldfareRepack/Command/main.swift
+++ b/Sources/TurboFieldfareRepack/Command/main.swift
@@ -6,12 +6,28 @@ Usage:
TurboFieldfareRepack --output <model.gturbo> [--overwrite] [--resume]
TurboFieldfareRepack --discard-partial --output <model.gturbo>
TurboFieldfareRepack --verify-install --input-gturbo <model.gturbo>
+ TurboFieldfareRepack --vision-output <model.vision.gturbo>
+ --text-model <model.gturbo> [--overwrite] [--resume]
+ TurboFieldfareRepack --verify-vision-install
+ --vision-output <model.vision.gturbo>
+ --text-model <model.gturbo>
+ TurboFieldfareRepack --activate-vision-install
+ --vision-output <model.vision.gturbo>
+ --text-model <model.gturbo>
+ TurboFieldfareRepack --remove-vision-install
+ --vision-output <model.vision.gturbo>
+ TurboFieldfareRepack --discard-partial
+ --vision-output <model.vision.gturbo>
TurboFieldfareRepack --help
The installer streams the supported Gemma 4 checkpoint from Hugging Face and
repackages it without materializing the source checkpoint on disk. Set HF_TOKEN
only if Hugging Face requests authentication. A cancelled or interrupted
download can be continued with --resume or removed with --discard-partial.
+
+The optional image companion pack installs beside an existing text model and
+is bound to it. Without the pack the text runtime is unchanged; image input is
+simply unavailable.
"""
private struct Arguments {
@@ -21,6 +37,11 @@ private struct Arguments {
var discardPartial = false
var verifyInstall = false
var inputGTurbo: String?
+ var visionOutput: String?
+ var textModel: String?
+ var verifyVisionInstall = false
+ var activateVisionInstall = false
+ var removeVisionInstall = false
static func parse(_ values: [String]) throws -> Arguments {
var parsed = Arguments()
@@ -42,6 +63,27 @@ private struct Arguments {
case "--verify-install":
parsed.verifyInstall = true
index += 1
+ case "--verify-vision-install":
+ parsed.verifyVisionInstall = true
+ index += 1
+ case "--activate-vision-install":
+ parsed.activateVisionInstall = true
+ index += 1
+ case "--remove-vision-install":
+ parsed.removeVisionInstall = true
+ index += 1
+ case "--vision-output":
+ guard index + 1 < values.count else {
+ throw ParseError.missingValue(flag)
+ }
+ parsed.visionOutput = values[index + 1]
+ index += 2
+ case "--text-model":
+ guard index + 1 < values.count else {
+ throw ParseError.missingValue(flag)
+ }
+ parsed.textModel = values[index + 1]
+ index += 2
case "--output", "--input-gturbo":
guard index + 1 < values.count else {
throw ParseError.missingValue(flag)
@@ -57,6 +99,55 @@ private struct Arguments {
}
}
+ let visionModes = [parsed.verifyVisionInstall,
+ parsed.activateVisionInstall,
+ parsed.removeVisionInstall].filter { $0 }.count
+ guard visionModes <= 1 else {
+ throw ParseError.invalidMode("vision install modes are mutually exclusive")
+ }
+ if visionModes == 1 || parsed.visionOutput != nil {
+ guard parsed.visionOutput != nil else {
+ throw ParseError.missingRequired("--vision-output")
+ }
+ guard parsed.output == nil, parsed.inputGTurbo == nil,
+ !parsed.verifyInstall else {
+ throw ParseError.invalidMode(
+ "vision install operations do not accept text install arguments")
+ }
+ // Discard runs first below, so accepting it alongside another mode
+ // would silently perform the discard and exit 0 without ever doing
+ // what was asked.
+ guard !(parsed.discardPartial && visionModes == 1) else {
+ throw ParseError.invalidMode(
+ "--discard-partial is mutually exclusive with the other vision "
+ + "install operations")
+ }
+ if parsed.removeVisionInstall || parsed.discardPartial {
+ guard parsed.textModel == nil, !parsed.overwrite, !parsed.resume else {
+ throw ParseError.invalidMode(
+ "this vision operation only accepts --vision-output")
+ }
+ } else if parsed.verifyVisionInstall || parsed.activateVisionInstall {
+ guard parsed.textModel != nil else {
+ throw ParseError.missingRequired("--text-model")
+ }
+ // Neither reads a download, so a transfer flag here is a
+ // request this mode cannot honour rather than a no-op.
+ guard !parsed.overwrite, !parsed.resume else {
+ throw ParseError.invalidMode(
+ "this vision operation only accepts --vision-output and "
+ + "--text-model")
+ }
+ } else {
+ guard parsed.textModel != nil else {
+ throw ParseError.missingRequired("--text-model")
+ }
+ }
+ return parsed
+ }
+ guard parsed.textModel == nil else {
+ throw ParseError.invalidMode("--text-model requires --vision-output")
+ }
guard !(parsed.resume && parsed.discardPartial) else {
throw ParseError.invalidMode("--resume and --discard-partial are mutually exclusive")
}
@@ -110,6 +201,86 @@ private func printError(_ message: String) {
FileHandle.standardError.write(Data((message + "\n").utf8))
}
+private func runVisionInstall(_ arguments: Arguments) async -> Int32? {
+ guard let visionOutput = arguments.visionOutput else { return nil }
+
+ if arguments.discardPartial {
+ do {
+ try RemoteVisionPackInstaller.discardPartial(outputDirectory: visionOutput)
+ print("Discarded saved image-pack download for \(visionOutput)")
+ return 0
+ } catch {
+ printError("discard failed: \(error)")
+ return 1
+ }
+ }
+
+ if arguments.removeVisionInstall {
+ do {
+ try RemoteVisionPackInstaller.removeInstalled(outputDirectory: visionOutput)
+ print("Removed image pack \(visionOutput)")
+ return 0
+ } catch {
+ printError("remove-vision-install failed: \(error)")
+ return 1
+ }
+ }
+
+ guard let textModel = arguments.textModel else { return 2 }
+
+ if arguments.verifyVisionInstall {
+ do {
+ let verification = try VisionPackVerifier.verify(
+ directory: URL(fileURLWithPath: visionOutput, isDirectory: true),
+ installedDirectory: URL(fileURLWithPath: visionOutput, isDirectory: true),
+ textModelDirectory: URL(fileURLWithPath: textModel, isDirectory: true),
+ verifyWeights: true)
+ print("Verified image pack \(visionOutput)")
+ print("Bound to text model \(textModel)")
+ print("Text manifest sha256 \(verification.compatibleTextManifestSha256)")
+ return 0
+ } catch {
+ printError("verify-vision-install failed: \(error)")
+ return 1
+ }
+ }
+
+ if arguments.activateVisionInstall {
+ do {
+ try RemoteVisionPackInstaller.activatePrepared(
+ outputDirectory: visionOutput,
+ textModelDirectory: textModel,
+ repoID: SupportedModelSource.repoID,
+ requestedRevision: SupportedModelSource.revision)
+ print("Activated image pack \(visionOutput)")
+ return 0
+ } catch {
+ printError("activate-vision-install failed: \(error)")
+ return 1
+ }
+ }
+
+ let options = RemoteVisionPackInstallOptions(
+ repoID: SupportedModelSource.repoID,
+ revision: SupportedModelSource.revision,
+ textModelDirectory: textModel,
+ outputDirectory: visionOutput,
+ token: ProcessInfo.processInfo.environment["HF_TOKEN"],
+ overwrite: arguments.overwrite,
+ resume: arguments.resume)
+ do {
+ let progress = InstallProgressReporter()
+ try await RemoteVisionPackInstaller(options: options).run(
+ progress: { progress($0) })
+ print("Installed image pack \(visionOutput)")
+ print("Text model: \(textModel)")
+ return 0
+ } catch {
+ printError("vision install failed: \(error)")
+ return 1
+ }
+}
+
private func run(_ values: [String]) async -> Int32 {
let arguments: Arguments
do {
@@ -122,6 +293,10 @@ private func run(_ values: [String]) async -> Int32 {
return 2
}
+ if let code = await runVisionInstall(arguments) {
+ return code
+ }
+
if arguments.discardPartial, let output = arguments.output {
do {
try RemoteStreamingRepacker.discardPartial(outputDirectory: output)
@@ -153,7 +328,9 @@ private func run(_ values: [String]) async -> Int32 {
token: ProcessInfo.processInfo.environment["HF_TOKEN"],
resume: arguments.resume)
do {
- let result = try await RemoteStreamingRepacker(options: options).run()
+ let progress = InstallProgressReporter()
+ let result = try await RemoteStreamingRepacker(options: options).run(
+ progress: { progress($0) })
print("Installed \(SupportedModelSource.displayName)")
print("Source revision: \(result.resolvedCommit)")
print("Model: \(result.outputDir)")
diff --git a/Sources/TurboFieldfareRepack/Core/Format/Safetensors.swift b/Sources/TurboFieldfareRepack/Core/Format/Safetensors.swift
index 9a0ff26f..659db43e 100644
--- a/Sources/TurboFieldfareRepack/Core/Format/Safetensors.swift
+++ b/Sources/TurboFieldfareRepack/Core/Format/Safetensors.swift
@@ -7,13 +7,54 @@ enum Safetensors {
static let maxHeaderBytes: UInt64 = 1 << 24 // 16 MB — generous; observed ~95 KB
struct Header {
+ let path: String
+ /// Where tensor payloads begin, so a caller can bound a read against
+ /// the header rather than trusting an offset the file supplied.
+ let payloadBaseOffset: UInt64
let tensors: [SourceTensor]
}
+ static func parseHeader(path: String) throws -> Header {
+ let fd = try Posix.openRead(path)
+ defer { close(fd) }
+ var st = stat()
+ if fstat(fd, &st) != 0 {
+ throw RepackError.fileStatFailed(path: path, errno: errno)
+ }
+ let fileSize = UInt64(st.st_size)
+ if fileSize < 8 {
+ throw RepackError.safetensorsHeaderInvalid(path: path, detail: "file too short")
+ }
+
+ var headerSizeLE: UInt64 = 0
+ try withUnsafeMutableBytes(of: &headerSizeLE) { raw in
+ try Posix.preadAll(fd: fd, path: path, buf: raw.baseAddress!, count: 8, offset: 0)
+ }
+ let headerSize = UInt64(littleEndian: headerSizeLE)
+ if headerSize > maxHeaderBytes || headerSize > fileSize - 8 {
+ throw RepackError.safetensorsHeaderTooLarge(path: path, size: headerSize)
+ }
+
+ let buf = UnsafeMutableRawBufferPointer.allocate(byteCount: Int(headerSize), alignment: 16)
+ defer { buf.deallocate() }
+ try Posix.preadAll(fd: fd, path: path, buf: buf.baseAddress!, count: Int(headerSize), offset: 8)
+ let data = Data(bytesNoCopy: buf.baseAddress!, count: Int(headerSize), deallocator: .none)
+
+ return try parseHeaderBytes(path: path,
+ fileSize: fileSize,
+ headerBytes: data)
+ }
+
static func parseHeaderBytes(path: String,
fileSize: UInt64,
headerBytes data: Data) throws -> Header {
let headerSize = UInt64(data.count)
+ // `fileSize - 8` underflows and traps on a file shorter than its own
+ // length prefix, which is exactly what a hostile shard supplies.
+ guard fileSize >= 8 else {
+ throw RepackError.safetensorsHeaderInvalid(
+ path: path, detail: "file too short")
+ }
if headerSize > maxHeaderBytes || headerSize > fileSize - 8 {
throw RepackError.safetensorsHeaderTooLarge(path: path, size: headerSize)
}
@@ -47,29 +88,54 @@ enum Safetensors {
throw RepackError.safetensorsHeaderInvalid(path: path,
detail: "entry for \(name) has no shape")
}
- let shapeU64: [UInt64] = try shape.map { e in
- if let n = e as? NSNumber { return n.uint64Value }
- if let n = e as? Int { return UInt64(n) }
- throw RepackError.safetensorsHeaderInvalid(path: path,
- detail: "entry for \(name) has non-integer shape entry")
+ let shapeU64: [UInt64] = try shape.map { element in
+ guard let extent = Self.nonNegativeUInt64(element) else {
+ throw RepackError.safetensorsHeaderInvalid(
+ path: path,
+ detail: "entry for \(name) has non-integer shape entry")
+ }
+ return extent
}
guard let offs = entry["data_offsets"] as? [Any], offs.count == 2,
- let begin = (offs[0] as? NSNumber)?.uint64Value ?? (offs[0] as? Int).map({ UInt64($0) }),
- let end = (offs[1] as? NSNumber)?.uint64Value ?? (offs[1] as? Int).map({ UInt64($0) })
+ let begin = Self.nonNegativeUInt64(offs[0]),
+ let end = Self.nonNegativeUInt64(offs[1])
else {
throw RepackError.safetensorsHeaderInvalid(path: path,
detail: "entry for \(name) has bad data_offsets")
}
- let abs = payloadBase + begin
+ // Every term below comes from a JSON header that, for a remote
+ // model, is not covered by any pinned digest - only the index file
+ // is. Unchecked `+`/`-`/`*` on those values traps, so a hostile or
+ // corrupt shard would abort the process instead of failing the
+ // download.
+ guard end >= begin else {
+ throw RepackError.safetensorsHeaderInvalid(
+ path: path,
+ detail: "entry for \(name) has data_offsets end \(end) "
+ + "before begin \(begin)")
+ }
let size = end - begin
- let endAbs = abs + size
+ let abs = try Self.checked(path: path, name: name, "absolute offset") {
+ payloadBase.addingReportingOverflow(begin)
+ }
+ let endAbs = try Self.checked(path: path, name: name, "absolute end") {
+ abs.addingReportingOverflow(size)
+ }
if endAbs > fileSize {
throw RepackError.safetensorsTensorOutOfRange(path: path, name: name,
end: endAbs, fileSize: fileSize)
}
let elemBytes = UInt64(dtype.elementBytes)
- let elements = shapeU64.reduce(UInt64(1), *)
- if elements * elemBytes != size {
+ var elements = UInt64(1)
+ for extent in shapeU64 {
+ elements = try Self.checked(path: path, name: name, "shape product") {
+ elements.multipliedReportingOverflow(by: extent)
+ }
+ }
+ let declaredBytes = try Self.checked(path: path, name: name, "element bytes") {
+ elements.multipliedReportingOverflow(by: elemBytes)
+ }
+ if declaredBytes != size {
throw RepackError.shapeMismatch(name: name,
detail: "shape product \(elements)*\(elemBytes) != size \(size)")
}
@@ -77,6 +143,42 @@ enum Safetensors {
shape: shapeU64,
absoluteOffset: abs, sizeBytes: size))
}
- return Header(tensors: tensors)
+ return Header(path: path, payloadBaseOffset: payloadBase, tensors: tensors)
+ }
+
+ /// A whole number in `0...UInt64.max`, or nil.
+ ///
+ /// Sign alone is not enough. JSON has one number type, so `1.5` and `1e30`
+ /// parse as `NSNumber` just as `1` does, and `uint64Value` answers both —
+ /// by truncating the first and saturating the second. Either would let a
+ /// header we did not write name a shape or an offset that is not the one it
+ /// declares.
+ private static func nonNegativeUInt64(_ value: Any) -> UInt64? {
+ if let number = value as? Int { return number >= 0 ? UInt64(number) : nil }
+ guard let number = value as? NSNumber else { return nil }
+ guard number.compare(NSNumber(value: 0)) != .orderedAscending else { return nil }
+ let double = number.doubleValue
+ guard double == double.rounded(),
+ double <= Double(UInt64.max),
+ number.compare(NSNumber(value: UInt64.max)) != .orderedDescending else {
+ return nil
+ }
+ return number.uint64Value
+ }
+
+ /// Turns an overflowing header computation into a diagnosable error rather
+ /// than a trap.
+ private static func checked(
+ path: String,
+ name: String,
+ _ field: String,
+ _ operation: () -> (partialValue: UInt64, overflow: Bool)
+ ) throws -> UInt64 {
+ let (value, overflow) = operation()
+ guard !overflow else {
+ throw RepackError.safetensorsHeaderInvalid(
+ path: path, detail: "entry for \(name) overflows \(field)")
+ }
+ return value
}
}
diff --git a/Sources/TurboFieldfareRepack/Core/Planning/RangeCopyPlanner.swift b/Sources/TurboFieldfareRepack/Core/Planning/RangeCopyPlanner.swift
index 391e693d..1119e59c 100644
--- a/Sources/TurboFieldfareRepack/Core/Planning/RangeCopyPlanner.swift
+++ b/Sources/TurboFieldfareRepack/Core/Planning/RangeCopyPlanner.swift
@@ -1,4 +1,5 @@
import Foundation
+import TurboFieldfareFormat
public struct RangeCopy: Sendable, Equatable {
public let shardID: String
@@ -44,6 +45,49 @@ public struct RangeCopyPlan: Sendable {
}
public enum RangeCopyPlanner {
+ static func plan(
+ visionPackPlan: VisionPackPlan,
+ outputDirectory: String,
+ rangeChunkBytes: Int,
+ textManifestSha256: String
+ ) throws -> RangeCopyPlan {
+ let weightsPath = (outputDirectory as NSString)
+ .appendingPathComponent(GTurboVisionFormatV1.weightsFile)
+ let copies = visionPackPlan.entries.map { entry in
+ RangeCopy(
+ shardID: entry.source.shardPath,
+ sourceOffset: entry.source.absoluteOffset,
+ size: entry.source.sizeBytes,
+ destinationPath: weightsPath,
+ destinationOffset: entry.fileOffset)
+ }
+ try validateDestinationIntervals(copies, outputRoot: outputDirectory)
+ let coalesced = try coalesce(copies: copies, rangeChunkBytes: rangeChunkBytes)
+ let expectedOutputs = [RemoteExpectedOutput(
+ relativePath: GTurboVisionFormatV1.weightsFile,
+ size: visionPackPlan.weightsFileSize)]
+ // A separate domain so a vision plan can never share a fingerprint with
+ // a text plan that happens to coalesce to the same ranges.
+ let fingerprint = try canonicalFingerprint(
+ domain: "TurboFieldfare.RemoteVisionInstallPlan.v1",
+ copies: coalesced,
+ outputRoot: outputDirectory,
+ rangeChunkBytes: rangeChunkBytes,
+ layoutMode: "vision-execution-order",
+ layoutOrderSha256: textManifestSha256,
+ residentIndexSha256: "",
+ expectedOutputs: expectedOutputs)
+ let downloaded = coalesced.reduce(UInt64(0)) { $0 + $1.size }
+ return RangeCopyPlan(
+ scalarCopies: copies,
+ coalescedCopies: coalesced,
+ remoteBytesToDownload: downloaded,
+ remoteGapBytesDownloaded: downloaded - visionPackPlan.sourcePayloadBytes,
+ canonicalFingerprint: fingerprint,
+ residentIndexSha256: "",
+ expectedOutputs: expectedOutputs)
+ }
+
static func plan(repackPlan: RepackPlan,
rangeChunkBytes: Int,
layoutMode: String = "identity",
@@ -239,6 +283,7 @@ public enum RangeCopyPlanner {
}
static func canonicalFingerprint(
+ domain: String = "TurboFieldfare.RemoteInstallPlan.v1",
copies: [CoalescedRangeCopy],
outputRoot: String,
rangeChunkBytes: Int,
@@ -247,7 +292,7 @@ public enum RangeCopyPlanner {
residentIndexSha256: String,
expectedOutputs: [RemoteExpectedOutput]
) throws -> String {
- var writer = FingerprintWriter(domain: "TurboFieldfare.RemoteInstallPlan.v1")
+ var writer = FingerprintWriter(domain: domain)
writer.append(UInt64(GTurboJSON.versionMajor))
writer.append(UInt64(GTurboJSON.versionMinor))
writer.append(UInt64(rangeChunkBytes))
diff --git a/Sources/TurboFieldfareRepack/Core/Planning/RepackPlanner.swift b/Sources/TurboFieldfareRepack/Core/Planning/RepackPlanner.swift
index f8a5d951..3a2b5d57 100644
--- a/Sources/TurboFieldfareRepack/Core/Planning/RepackPlanner.swift
+++ b/Sources/TurboFieldfareRepack/Core/Planning/RepackPlanner.swift
@@ -95,8 +95,101 @@ struct RepackPlan: Sendable {
// MARK: - Planner
+struct VisionPackPlan: Sendable {
+ struct Entry: Sendable {
+ let source: SourceTensor
+ let executionPosition: Int
+ let fileOffset: UInt64
+ let quantSpec: QuantSpec?
+ /// Affine group size, pinned to 64 by `planVisionCompanion`.
+ let groupSize: Int
+ }
+
+ let entries: [Entry]
+ let weightsFileSize: UInt64
+ let sourcePayloadBytes: UInt64
+}
+
enum RepackPlanner {
+ static func planVisionCompanion(
+ meta: IndexLoader.SourceMetadata,
+ shardHeaders: [Safetensors.Header]
+ ) throws -> VisionPackPlan {
+ guard meta.baseBits == 4, meta.baseGroupSize == 64,
+ meta.baseMode.lowercased() == "affine" else {
+ throw RepackError.configurationInvalid(
+ detail: "vision companion requires MLX affine 4-bit group-64 source metadata")
+ }
+
+ let tensors = shardHeaders.flatMap(\.tensors).filter {
+ isMultimodalTensorName($0.name)
+ }
+ guard tensors.count == 358 else {
+ throw RepackError.configurationInvalid(
+ detail: "expected 358 vision tensors, found \(tensors.count)")
+ }
+ let sourceBytes = tensors.reduce(UInt64(0)) { $0 + $1.sizeBytes }
+ guard sourceBytes == 1_140_925_536 else {
+ throw RepackError.configurationInvalid(
+ detail: "expected 1140925536 vision bytes, found \(sourceBytes)")
+ }
+
+ let ordered = tensors.sorted { visionExecutionKey($0.name) < visionExecutionKey($1.name) }
+ var offset: UInt64 = 0
+ var entries: [VisionPackPlan.Entry] = []
+ entries.reserveCapacity(ordered.count)
+ for (position, tensor) in ordered.enumerated() {
+ offset = visionAlignUp(offset, to: GTurboVisionFormatV1.alignmentBytes)
+ let quantSpec: QuantSpec?
+ if tensor.dtype == .u32 {
+ let spec = IndexLoader.quantSpec(forTensor: tensor.name, meta: meta)
+ // Group size is not carried per tensor in this tree; the base
+ // group was already pinned to 64 above.
+ guard spec.bits == 4 else {
+ throw RepackError.configurationInvalid(
+ detail: "unsupported vision quantization for \(tensor.name)")
+ }
+ quantSpec = spec
+ } else {
+ guard tensor.dtype == .bf16 else {
+ throw RepackError.configurationInvalid(
+ detail: "unsupported vision dtype for \(tensor.name)")
+ }
+ quantSpec = nil
+ }
+ entries.append(.init(source: tensor,
+ executionPosition: position,
+ fileOffset: offset,
+ quantSpec: quantSpec,
+ groupSize: meta.baseGroupSize))
+ offset += tensor.sizeBytes
+ }
+ return VisionPackPlan(entries: entries,
+ weightsFileSize: offset,
+ sourcePayloadBytes: sourceBytes)
+ }
+
+ private static func visionExecutionKey(_ name: String) -> String {
+ if name.hasPrefix("vision_tower.patch_embedder.") {
+ return "0000/\(name)"
+ }
+ if let layer = layerIndex(in: name), name.hasPrefix("vision_tower.encoder.layers.") {
+ return String(format: "1000/%03d/%@", layer, name)
+ }
+ if name == "vision_tower.std_bias" || name == "vision_tower.std_scale" {
+ return "2000/\(name)"
+ }
+ if name.hasPrefix("embed_vision.") {
+ return "3000/\(name)"
+ }
+ return "9999/\(name)"
+ }
+
+ private static func visionAlignUp(_ value: UInt64, to alignment: UInt64) -> UInt64 {
+ ((value + alignment - 1) / alignment) * alignment
+ }
+
/// Classify a tensor name. Routed-expert tensors split off the LM bucket.
enum Bucket: Equatable {
case lmResident
diff --git a/Sources/TurboFieldfareRepack/Core/Remote/RemoteSnapshotLoader.swift b/Sources/TurboFieldfareRepack/Core/Remote/RemoteSnapshotLoader.swift
index 71ea7d37..088df49a 100644
--- a/Sources/TurboFieldfareRepack/Core/Remote/RemoteSnapshotLoader.swift
+++ b/Sources/TurboFieldfareRepack/Core/Remote/RemoteSnapshotLoader.swift
@@ -77,6 +77,12 @@ enum RemoteSnapshotLoader {
}
return value
}
+ // The remote reports `info.size`; a value under 8 would underflow
+ // the bound below into ~2^64 and admit any header at all.
+ guard info.size >= 8 else {
+ throw RepackError.safetensorsHeaderInvalid(
+ path: shard, detail: "remote reports \(info.size) bytes")
+ }
if headerSize > Safetensors.maxHeaderBytes || headerSize > info.size - 8 {
throw RepackError.safetensorsHeaderTooLarge(path: shard, size: headerSize)
}
diff --git a/Sources/TurboFieldfareRepack/Core/Remote/RemoteVisionPackInstaller.swift b/Sources/TurboFieldfareRepack/Core/Remote/RemoteVisionPackInstaller.swift
new file mode 100644
index 00000000..bf6f4957
--- /dev/null
+++ b/Sources/TurboFieldfareRepack/Core/Remote/RemoteVisionPackInstaller.swift
@@ -0,0 +1,647 @@
+import Darwin
+import Foundation
+import TurboFieldfareFormat
+
+public struct RemoteVisionPackInstallOptions: Sendable {
+ public let repoID: String
+ public let revision: String
+ public let textModelDirectory: String
+ public let outputDirectory: String
+ public let token: String?
+ public let rangeChunkBytes: Int
+ public let writeTileBytes: Int
+ public let minFreeReserveBytes: UInt64
+ public let overwrite: Bool
+ public let resume: Bool
+ public let downloadSession: RemoteDownloadSession
+ public let baseURL: URL
+ public let rangeRetryAttempts: Int
+ public let retryBaseDelayNs: UInt64
+
+ public init(
+ repoID: String,
+ revision: String,
+ textModelDirectory: String,
+ outputDirectory: String,
+ token: String? = nil,
+ rangeChunkBytes: Int = RemoteChunkPolicy.defaultBytes,
+ writeTileBytes: Int = WriterCore.tileBytes,
+ minFreeReserveBytes: UInt64 = 1_073_741_824,
+ overwrite: Bool = false,
+ resume: Bool = false,
+ downloadSession: RemoteDownloadSession = RemoteDownloadSession(),
+ baseURL: URL = URL(string: "https://huggingface.co")!,
+ rangeRetryAttempts: Int = 4,
+ retryBaseDelayNs: UInt64 = 1_000_000_000
+ ) {
+ self.repoID = repoID
+ self.revision = revision
+ self.textModelDirectory = textModelDirectory
+ self.outputDirectory = outputDirectory
+ self.token = token
+ self.rangeChunkBytes = rangeChunkBytes
+ self.writeTileBytes = writeTileBytes
+ self.minFreeReserveBytes = minFreeReserveBytes
+ self.overwrite = overwrite
+ self.resume = resume
+ self.downloadSession = downloadSession
+ self.baseURL = baseURL
+ self.rangeRetryAttempts = rangeRetryAttempts
+ self.retryBaseDelayNs = retryBaseDelayNs
+ }
+}
+
+public struct RemoteVisionPackInstallResult: Sendable {
+ public let outputDirectory: String
+ public let resolvedCommit: String
+ public let tensorCount: Int
+ public let weightsBytes: UInt64
+ public let remoteBytesToDownload: UInt64
+ public let reusedBytes: UInt64
+ public let downloadedThisRunBytes: UInt64
+ public let peakRSSBytes: UInt64
+ public let largestScratchBytes: Int
+}
+
+public final class RemoteVisionPackInstaller {
+ private let options: RemoteVisionPackInstallOptions
+ private let audit: RepackAudit
+
+ /// Exactly what a finished companion pack contains. `VisionPackVerifier`
+ /// rejects a directory holding anything else, which is deliberate — but the
+ /// same directory doubles as download scratch, so a crash can leave a range
+ /// temp file or an interrupted `atomicWrite`'s `.tmp` beside the four real
+ /// ones and make an otherwise complete download unverifiable forever.
+ static let packEntries: Set<String> = [
+ GTurboVisionFormatV1.manifestFile,
+ GTurboVisionFormatV1.weightsFile,
+ GTurboVisionFormatV1.processorFile,
+ GTurboVisionFormatV1.receiptFile,
+ ]
+
+ /// Deletes everything in the partial directory that is not part of the pack
+ /// itself, and returns what it removed.
+ ///
+ /// Only ever called while holding the install lock, and only at a point
+ /// where no transfer is in flight, so anything it finds is abandoned
+ /// scratch. Discarding an in-flight range costs a re-download of that
+ /// chunk; the checkpoint, not the scratch file, is what records progress.
+ @discardableResult
+ static func reclaimPartialScratch(directory: String) throws -> [String] {
+ guard try Posix.entryKind(directory) == .directory else { return [] }
+ let manager = FileManager.default
+ let entries = try manager.contentsOfDirectory(atPath: directory)
+ var reclaimed: [String] = []
+ for entry in entries where !packEntries.contains(entry) {
+ let path = (directory as NSString).appendingPathComponent(entry)
+ // Surfaced, not swallowed: a scratch file we cannot delete is the
+ // difference between a resumable install and a stuck one.
+ try manager.removeItem(atPath: path)
+ reclaimed.append(entry)
+ }
+ if !reclaimed.isEmpty {
+ try Posix.fsyncDirectory(directory)
+ }
+ return reclaimed
+ }
+
+ public init(
+ options: RemoteVisionPackInstallOptions,
+ audit: RepackAudit = RepackAudit()
+ ) {
+ self.options = options
+ self.audit = audit
+ }
+
+ public func run(
+ progress: @escaping @Sendable (ModelInstallProgress) -> Void = { _ in }
+ ) async throws -> RemoteVisionPackInstallResult {
+ let result = try await prepare(progress: progress)
+ try Self.activatePrepared(
+ outputDirectory: options.outputDirectory,
+ textModelDirectory: options.textModelDirectory,
+ repoID: options.repoID,
+ requestedRevision: options.revision)
+ return result
+ }
+
+ public func prepare(
+ progress: @escaping @Sendable (ModelInstallProgress) -> Void = { _ in }
+ ) async throws -> RemoteVisionPackInstallResult {
+ try validateOptions()
+ let lock = try InstallLock.acquire(outputDirectory: options.outputDirectory)
+ defer { withExtendedLifetime(lock) {} }
+ let paths = lock.paths
+ let finalKind = try Posix.entryKind(paths.finalDirectory)
+ if finalKind == .directory, !options.overwrite {
+ throw RepackError.configurationInvalid(
+ detail: "vision companion already exists: \(paths.finalDirectory)"
+ + "; pass --overwrite to replace it, or --resume --overwrite "
+ + "to continue a saved download over it")
+ }
+ if finalKind == .directory {
+ // Activation needs this lock exclusively. Probing it now turns "a
+ // loaded model was holding the pack" from a refusal that arrives
+ // after the whole 1.09 GB transfer into one that arrives before the
+ // first byte. The probe releases immediately, so it does not block
+ // readers for the duration of the download, and a model that loads
+ // mid-transfer is still caught at activation.
+ _ = try VisionPackMutationLock.acquire(
+ outputDirectory: paths.finalDirectory)
+ }
+ var hasPartial = try Posix.entryKind(paths.partialDirectory) == .directory
+ let hasCheckpoint = try Posix.entryKind(paths.checkpointFile) == .regular
+ if hasPartial, !hasCheckpoint {
+ // The partial directory is created before the checkpoint that
+ // identifies its source, so a crash in that window leaves a
+ // directory nothing can interpret — and, without this, an error on
+ // every later attempt including a fresh one. It holds no progress
+ // worth keeping, so reclaim it.
+ try FileManager.default.removeItem(atPath: paths.partialDirectory)
+ try Posix.fsyncDirectory(paths.parentDirectory)
+ hasPartial = false
+ }
+ guard hasPartial == hasCheckpoint else {
+ throw RepackError.installStateCorrupt(
+ path: paths.partialDirectory,
+ detail: "partial directory and checkpoint must exist together")
+ }
+ if hasPartial {
+ try Self.reclaimPartialScratch(directory: paths.partialDirectory)
+ }
+ if options.resume {
+ guard hasPartial else {
+ throw RepackError.installStateMissing(path: paths.checkpointFile)
+ }
+ } else if hasPartial {
+ throw RepackError.installStateIncompatible(
+ detail: "saved vision download exists; resume or discard it")
+ }
+ do {
+ return try await runPrepared(paths: paths, progress: progress)
+ } catch {
+ if !hasCheckpoint,
+ (try? Posix.entryKind(paths.checkpointFile)) != .regular {
+ try? FileManager.default.removeItem(atPath: paths.partialDirectory)
+ }
+ throw error
+ }
+ }
+
+ public static func inspectPersistentInstall(
+ outputDirectory: String,
+ repoID: String,
+ requestedRevision: String
+ ) throws -> RemoteInstallCheckpoint? {
+ try RemoteStreamingRepacker.inspectPersistentInstall(
+ outputDirectory: outputDirectory,
+ repoID: repoID,
+ requestedRevision: requestedRevision)
+ }
+
+ public static func discardPartial(outputDirectory: String) throws {
+ try RemoteStreamingRepacker.discardPartial(outputDirectory: outputDirectory)
+ }
+
+ public static func preparedInstallIsValid(
+ outputDirectory: String,
+ textModelDirectory: String,
+ verifyWeights: Bool = false
+ ) -> Bool {
+ guard let paths = try? RemoteInstallPaths(outputDirectory: outputDirectory),
+ (try? Posix.entryKind(paths.partialDirectory)) == .directory,
+ (try? Posix.entryKind(paths.checkpointFile)) == .regular else {
+ return false
+ }
+ return (try? VisionPackVerifier.verify(
+ directory: URL(fileURLWithPath: paths.partialDirectory, isDirectory: true),
+ installedDirectory: URL(fileURLWithPath: paths.finalDirectory, isDirectory: true),
+ textModelDirectory: URL(fileURLWithPath: textModelDirectory, isDirectory: true),
+ verifyWeights: verifyWeights)) != nil
+ }
+
+ public static func activatePrepared(
+ outputDirectory: String,
+ textModelDirectory: String,
+ repoID: String,
+ requestedRevision: String,
+ onVerifyProgress: ((UInt64, UInt64) throws -> Void)? = nil
+ ) throws {
+ let lock = try InstallLock.acquire(outputDirectory: outputDirectory)
+ defer { withExtendedLifetime(lock) {} }
+ let paths = lock.paths
+ guard try Posix.entryKind(paths.checkpointFile) == .regular else {
+ throw RepackError.installStateMissing(path: paths.checkpointFile)
+ }
+ let checkpoint = try RemoteInstallCheckpoint.load(from: paths.checkpointFile)
+ guard checkpoint.repoID == repoID,
+ checkpoint.requestedRevision == requestedRevision else {
+ throw RepackError.installStateIncompatible(
+ detail: "prepared vision pack belongs to a different source")
+ }
+ let partialExists = try Posix.entryKind(paths.partialDirectory) == .directory
+ if partialExists {
+ // A download that finished but crashed before its own cleanup
+ // leaves scratch the verifier will reject. Nothing is in flight
+ // here — the install lock is held — so it is safe to reclaim.
+ try Self.reclaimPartialScratch(directory: paths.partialDirectory)
+ }
+ let verificationDirectory = partialExists
+ ? paths.partialDirectory
+ : paths.finalDirectory
+ guard try Posix.entryKind(verificationDirectory) == .directory else {
+ throw RepackError.installStateMissing(path: paths.partialDirectory)
+ }
+ // The only cancellable part of activation: everything after it either
+ // renames or removes, and neither may be abandoned half done.
+ let verification = try VisionPackVerifier.verify(
+ directory: URL(fileURLWithPath: verificationDirectory, isDirectory: true),
+ installedDirectory: URL(fileURLWithPath: paths.finalDirectory, isDirectory: true),
+ textModelDirectory: URL(fileURLWithPath: textModelDirectory, isDirectory: true),
+ onHashProgress: onVerifyProgress)
+ guard checkpoint.resolvedCommit == verification.sourceRevision,
+ checkpoint.sourceIndexSHA256.lowercased()
+ == verification.sourceIndexSha256.lowercased() else {
+ throw RepackError.installStateIncompatible(
+ detail: "prepared vision pack and checkpoint source identity differ")
+ }
+ if !partialExists {
+ try FileManager.default.removeItem(atPath: paths.checkpointFile)
+ try Posix.fsyncDirectory(paths.parentDirectory)
+ return
+ }
+ let useLock = try VisionPackMutationLock.acquire(
+ outputDirectory: paths.finalDirectory)
+ defer { withExtendedLifetime(useLock) {} }
+ if try Posix.entryKind(paths.finalDirectory) == .directory {
+ try Posix.renameSwap(paths.partialDirectory, paths.finalDirectory)
+ try Posix.fsyncDirectory(paths.parentDirectory)
+ try FileManager.default.removeItem(atPath: paths.partialDirectory)
+ } else {
+ try Posix.rename(from: paths.partialDirectory, to: paths.finalDirectory)
+ try Posix.fsyncDirectory(paths.parentDirectory)
+ }
+ try FileManager.default.removeItem(atPath: paths.checkpointFile)
+ try Posix.fsyncDirectory(paths.parentDirectory)
+ }
+
+ public static func removeInstalled(outputDirectory: String) throws {
+ let lock = try InstallLock.acquire(outputDirectory: outputDirectory)
+ defer { withExtendedLifetime(lock) {} }
+ guard try Posix.entryKind(lock.paths.finalDirectory) == .directory else {
+ throw RepackError.installStateMissing(path: lock.paths.finalDirectory)
+ }
+ let useLock = try VisionPackMutationLock.acquire(
+ outputDirectory: lock.paths.finalDirectory)
+ defer { withExtendedLifetime(useLock) {} }
+ for path in [
+ lock.paths.finalDirectory,
+ lock.paths.partialDirectory,
+ lock.paths.checkpointFile,
+ ] {
+ if try Posix.entryKind(path) != .absent {
+ try FileManager.default.removeItem(atPath: path)
+ }
+ }
+ try Posix.fsyncDirectory(lock.paths.parentDirectory)
+ }
+
+ private func runPrepared(
+ paths: RemoteInstallPaths,
+ progress: @escaping @Sendable (ModelInstallProgress) -> Void
+ ) async throws -> RemoteVisionPackInstallResult {
+ try Task.checkCancellation()
+ let textBinding = try readTextBinding()
+ let saved = options.resume
+ ? try RemoteInstallCheckpoint.load(from: paths.checkpointFile)
+ : nil
+ if let saved {
+ guard saved.repoID == options.repoID,
+ saved.requestedRevision == options.revision else {
+ throw RepackError.installStateIncompatible(
+ detail: "saved vision download belongs to a different source")
+ }
+ }
+
+ let retryPolicy = RemoteRetryPolicy(
+ attempts: options.rangeRetryAttempts,
+ baseDelayNs: options.retryBaseDelayNs)
+ let remote = HuggingFaceRemoteSource(
+ repoID: options.repoID,
+ requestedRevision: options.revision,
+ resolvedCommit: saved?.resolvedCommit,
+ token: options.token,
+ downloadSession: options.downloadSession,
+ baseURL: options.baseURL,
+ tempDirectory: paths.partialDirectory,
+ retryPolicy: retryPolicy)
+ progress(.downloadingMetadata)
+ let snapshot = try await RemoteSnapshotLoader.load(
+ remote: remote,
+ requireKnownSource: true,
+ metadataDirectory: paths.metadataDirectory,
+ audit: audit)
+ guard SourceFingerprint.modelID(forIndexSha256: snapshot.metadata.indexSha256Hex)
+ == options.repoID else {
+ throw RepackError.sourceFingerprintRejected(
+ path: snapshot.metadata.indexPath,
+ sha256: snapshot.metadata.indexSha256Hex)
+ }
+ let visionPlan = try RepackPlanner.planVisionCompanion(
+ meta: snapshot.metadata,
+ shardHeaders: snapshot.shardHeaders)
+ let rangePlan = try RangeCopyPlanner.plan(
+ visionPackPlan: visionPlan,
+ outputDirectory: paths.partialDirectory,
+ rangeChunkBytes: options.rangeChunkBytes,
+ textManifestSha256: textBinding.manifestSha256)
+ var checkpoint = saved ?? RemoteInstallCheckpoint(
+ repoID: options.repoID,
+ requestedRevision: options.revision,
+ resolvedCommit: snapshot.resolvedCommit,
+ sourceIndexSHA256: snapshot.metadata.indexSha256Hex,
+ planFingerprint: rangePlan.canonicalFingerprint,
+ totalSourceBytes: rangePlan.remoteBytesToDownload)
+ if saved != nil {
+ guard checkpoint.resolvedCommit == snapshot.resolvedCommit,
+ checkpoint.totalSourceBytes == rangePlan.remoteBytesToDownload,
+ checkpoint.matches(
+ repoID: options.repoID,
+ requestedRevision: options.revision,
+ sourceIndexSHA256: snapshot.metadata.indexSha256Hex,
+ planFingerprint: rangePlan.canonicalFingerprint) else {
+ throw RepackError.installStateIncompatible(
+ detail: "saved vision download source, text binding, or copy plan changed")
+ }
+ if try outputFileMatches(
+ path: paths.partialDirectory,
+ size: visionPlan.weightsFileSize) {
+ checkpoint.completedRanges = try RemoteStreamingRepacker
+ .validatedCompletedRanges(
+ checkpoint.completedRanges,
+ copies: rangePlan.coalescedCopies,
+ partialDirectory: paths.partialDirectory)
+ } else {
+ checkpoint.completedRanges = []
+ try createWeightsFile(paths: paths, size: visionPlan.weightsFileSize)
+ }
+ try checkpoint.write(
+ to: paths.checkpointFile,
+ parentDirectory: paths.parentDirectory)
+ }
+
+ let reusedDestinationBytes = checkpoint.completedRanges.reduce(UInt64(0)) {
+ $0 + $1.destinationBytes
+ }
+ let remainingBytes = visionPlan.weightsFileSize > reusedDestinationBytes
+ ? visionPlan.weightsFileSize - reusedDestinationBytes
+ : 0
+ progress(.planning(
+ downloadBytes: rangePlan.remoteBytesToDownload,
+ outputBytes: visionPlan.weightsFileSize))
+ let requirement = try DiskSpaceChecker.requireAvailable(
+ path: paths.parentDirectory,
+ bytes: remainingBytes + UInt64(options.rangeChunkBytes),
+ reserveBytes: options.minFreeReserveBytes)
+ progress(.checkingDisk(requirement))
+ try Task.checkCancellation()
+
+ if saved == nil {
+ progress(.reservingOutput(bytes: visionPlan.weightsFileSize))
+ try createWeightsFile(paths: paths, size: visionPlan.weightsFileSize)
+ try checkpoint.write(
+ to: paths.checkpointFile,
+ parentDirectory: paths.parentDirectory)
+ }
+
+ let pinned = remote.pinned(commit: snapshot.resolvedCommit)
+ let processorInfo = try await pinned.resolveFileInfo(
+ filename: GTurboVisionFormatV1.processorFile,
+ audit: audit)
+ guard processorInfo.resolvedCommit == snapshot.resolvedCommit else {
+ throw RepackError.remoteProtocolInvalid(
+ detail: "processor config commit differs from model commit")
+ }
+ let processorPath = (paths.partialDirectory as NSString)
+ .appendingPathComponent(GTurboVisionFormatV1.processorFile)
+ try await pinned.fetchSmallFile(
+ filename: GTurboVisionFormatV1.processorFile,
+ info: processorInfo,
+ capBytes: GTurboVisionFormatV1.metadataMaxBytes,
+ outputPath: processorPath,
+ audit: audit)
+
+ let provider = HTTPRangeSourceByteProvider(
+ remote: pinned,
+ files: snapshot.remoteFiles,
+ writeTileBytes: options.writeTileBytes)
+ let reusedBytes = checkpoint.completedRanges.reduce(UInt64(0)) {
+ $0 + $1.sourceBytes
+ }
+ let downloadStart = audit.remoteBytesDownloaded
+ progress(.copyingPayload(
+ reusedBytes: reusedBytes,
+ downloadedThisRunBytes: 0,
+ totalBytes: rangePlan.remoteBytesToDownload))
+ try await provider.copyBatch(
+ rangePlan.coalescedCopies,
+ completedRangeIDs: Set(checkpoint.completedRanges.map(\.id)),
+ partialDirectory: paths.partialDirectory,
+ temporaryPath: paths.rangeTemporaryFile,
+ audit: audit,
+ progress: { downloaded in
+ progress(.copyingPayload(
+ reusedBytes: reusedBytes,
+ downloadedThisRunBytes: downloaded,
+ totalBytes: rangePlan.remoteBytesToDownload))
+ },
+ commit: { completed in
+ checkpoint.completedRanges.removeAll { $0.id == completed.id }
+ checkpoint.completedRanges.append(completed)
+ checkpoint.completedRanges.sort { $0.id < $1.id }
+ try checkpoint.write(
+ to: paths.checkpointFile,
+ parentDirectory: paths.parentDirectory)
+ })
+
+ let weightsPath = (paths.partialDirectory as NSString)
+ .appendingPathComponent(GTurboVisionFormatV1.weightsFile)
+ progress(.hashingOutput(GTurboVisionFormatV1.weightsFile))
+ let weightsSHA = try Sha256Stream.hashFile(
+ path: weightsPath, noCache: true, noFollow: true)
+ progress(.hashingOutput(GTurboVisionFormatV1.processorFile))
+ let processorData = try Posix.readBoundedData(
+ processorPath,
+ maximumBytes: GTurboVisionFormatV1.metadataMaxBytes)
+ let processorSHA = hash(processorData)
+ progress(.finalizing)
+ try Task.checkCancellation()
+ try writeMetadata(
+ plan: visionPlan,
+ sourceIndexSha256: snapshot.metadata.indexSha256Hex,
+ sourceRevision: snapshot.resolvedCommit,
+ textBinding: textBinding,
+ processorData: processorData,
+ processorSha256: processorSHA,
+ weightsSha256: weightsSHA,
+ paths: paths)
+ // Removes the range scratch and the metadata cache along with anything
+ // else left over: the verifier below accepts the four pack entries and
+ // nothing besides.
+ try Self.reclaimPartialScratch(directory: paths.partialDirectory)
+ try Posix.fsyncDirectory(paths.partialDirectory)
+ try Task.checkCancellation()
+ _ = try VisionPackVerifier.verify(
+ directory: URL(fileURLWithPath: paths.partialDirectory, isDirectory: true),
+ installedDirectory: URL(fileURLWithPath: paths.finalDirectory, isDirectory: true),
+ textModelDirectory: URL(fileURLWithPath: options.textModelDirectory, isDirectory: true))
+ try Task.checkCancellation()
+ audit.sampleRSS()
+ return RemoteVisionPackInstallResult(
+ outputDirectory: paths.finalDirectory,
+ resolvedCommit: snapshot.resolvedCommit,
+ tensorCount: visionPlan.entries.count,
+ weightsBytes: visionPlan.weightsFileSize,
+ remoteBytesToDownload: rangePlan.remoteBytesToDownload,
+ reusedBytes: reusedBytes,
+ downloadedThisRunBytes: audit.remoteBytesDownloaded - downloadStart,
+ peakRSSBytes: audit.peakRssBytes,
+ largestScratchBytes: audit.largestScratchBytes)
+ }
+
+ private func validateOptions() throws {
+ guard options.rangeChunkBytes > 0,
+ options.rangeChunkBytes <= RemoteChunkPolicy.maxBytes else {
+ throw RepackError.configurationInvalid(
+ detail: "bad range chunk bytes \(options.rangeChunkBytes)")
+ }
+ guard options.writeTileBytes > 0,
+ options.writeTileBytes <= BoundedScratch.defaultLimitBytes else {
+ throw RepackError.configurationInvalid(
+ detail: "bad write tile bytes \(options.writeTileBytes)")
+ }
+ guard options.rangeRetryAttempts >= 0 else {
+ throw RepackError.configurationInvalid(
+ detail: "bad range retry attempts \(options.rangeRetryAttempts)")
+ }
+ }
+
+ private func readTextBinding() throws -> TextBinding {
+ let path = (options.textModelDirectory as NSString)
+ .appendingPathComponent(GTurboVisionFormatV1.manifestFile)
+ let data = try Posix.readBoundedData(
+ path,
+ maximumBytes: GTurboVisionFormatV1.metadataMaxBytes)
+ let manifest = try GTurboManifestCodec.decode(data)
+ guard let source = manifest.sourceSnapshotHash, !source.isEmpty else {
+ throw RepackError.configurationInvalid(
+ detail: "text manifest has no sourceSnapshotHash")
+ }
+ return TextBinding(
+ sourceSnapshotHash: source,
+ manifestSha256: hash(data))
+ }
+
+ private func createWeightsFile(paths: RemoteInstallPaths, size: UInt64) throws {
+ try Posix.mkdirP(paths.partialDirectory)
+ let path = (paths.partialDirectory as NSString)
+ .appendingPathComponent(GTurboVisionFormatV1.weightsFile)
+ if try Posix.entryKind(path) != .absent {
+ try FileManager.default.removeItem(atPath: path)
+ }
+ let descriptor = try Posix.openCreateRW(path)
+ defer { close(descriptor) }
+ try Posix.ftruncate(descriptor, path: path, size: size)
+ try Posix.fsync(descriptor, path: path)
+ try Posix.fsyncDirectory(paths.partialDirectory)
+ }
+
+ private func outputFileMatches(path: String, size: UInt64) throws -> Bool {
+ let weights = (path as NSString)
+ .appendingPathComponent(GTurboVisionFormatV1.weightsFile)
+ guard try Posix.entryKind(weights) == .regular else { return false }
+ let descriptor = try Posix.openReadNoFollow(weights)
+ defer { close(descriptor) }
+ return try Posix.fileSize(fd: descriptor, path: weights) == size
+ }
+
+ private func writeMetadata(
+ plan: VisionPackPlan,
+ sourceIndexSha256: String,
+ sourceRevision: String,
+ textBinding: TextBinding,
+ processorData: Data,
+ processorSha256: String,
+ weightsSha256: String,
+ paths: RemoteInstallPaths
+ ) throws {
+ let files = [
+ GTurboVisionFormatV1.weightsFile: GTurboManifestFileV1(
+ size: plan.weightsFileSize, sha256: weightsSha256),
+ GTurboVisionFormatV1.processorFile: GTurboManifestFileV1(
+ size: UInt64(processorData.count), sha256: processorSha256),
+ ]
+ let tensors = plan.entries.map { entry in
+ GTurboVisionTensorRegionV1(
+ name: entry.source.name,
+ executionPosition: entry.executionPosition,
+ offset: entry.fileOffset,
+ size: entry.source.sizeBytes,
+ shape: entry.source.shape,
+ dtype: entry.source.dtype == .u32 ? .u32 : .bf16,
+ quantization: entry.quantSpec.map { spec in
+ GTurboVisionQuantizationV1(
+ weightBits: spec.bits,
+ scheme: "affine",
+ scaleType: "bf16",
+ biasType: "bf16",
+ groupSize: entry.groupSize)
+ })
+ }
+ let manifest = GTurboVisionManifestV1(
+ modelID: options.repoID,
+ sourceRevision: sourceRevision,
+ sourceIndexSha256: sourceIndexSha256,
+ processorConfigSha256: processorSha256,
+ compatibleTextSourceSnapshotHash: textBinding.sourceSnapshotHash,
+ compatibleTextManifestSha256: textBinding.manifestSha256,
+ files: files,
+ tensors: tensors)
+ let manifestData = try GTurboVisionManifestCodec.encode(manifest)
+ let manifestSHA = hash(manifestData)
+ let receiptFiles = files.merging([
+ GTurboVisionFormatV1.manifestFile: GTurboManifestFileV1(
+ size: UInt64(manifestData.count), sha256: manifestSHA)
+ ]) { _, new in new }
+ let receipt = GTurboVisionReceiptV1(
+ manifestSha256: manifestSHA,
+ companionDirectoryPath: paths.finalDirectory,
+ compatibleTextManifestSha256: textBinding.manifestSha256,
+ sourceRepoID: options.repoID,
+ sourceRevision: sourceRevision,
+ verificationTimestamp: "source-revision:\(sourceRevision)",
+ toolVersion: "TurboFieldfareRepack/remote-vision-v1",
+ files: receiptFiles)
+ try Posix.atomicWrite(
+ manifestData,
+ to: (paths.partialDirectory as NSString)
+ .appendingPathComponent(GTurboVisionFormatV1.manifestFile),
+ durableIn: paths.partialDirectory)
+ try Posix.atomicWrite(
+ try GTurboVisionReceiptCodec.encode(receipt),
+ to: (paths.partialDirectory as NSString)
+ .appendingPathComponent(GTurboVisionFormatV1.receiptFile),
+ durableIn: paths.partialDirectory)
+ }
+
+ private func hash(_ data: Data) -> String {
+ var stream = Sha256Stream()
+ data.withUnsafeBytes { stream.update($0) }
+ return stream.finalizeHexString()
+ }
+}
+
+private struct TextBinding: Sendable {
+ let sourceSnapshotHash: String
+ let manifestSha256: String
+}
diff --git a/Sources/TurboFieldfareRepack/Core/System/GTurboDirectoryAccess.swift b/Sources/TurboFieldfareRepack/Core/System/GTurboDirectoryAccess.swift
index 5c76e404..d072ad1a 100644
--- a/Sources/TurboFieldfareRepack/Core/System/GTurboDirectoryAccess.swift
+++ b/Sources/TurboFieldfareRepack/Core/System/GTurboDirectoryAccess.swift
@@ -164,6 +164,12 @@ package final class GTurboDirectoryAccess {
}
if (info.st_mode & S_IFMT) == S_IFDIR {
if prefix.isEmpty, name == "tokenizer" { continue }
+ // Directory-shaped OS sidecars (.Spotlight-V100, .fseventsd,
+ // .TemporaryItems) land beside an artifact after any Finder or
+ // SMB round-trip. Descending into a Spotlight index is never
+ // right, and refusing the whole artifact over one is worse:
+ // list the entry so callers can filter it, and stop there.
+ if GTurboVisionFormatV1.isSidecarEntry(name) { continue }
guard depth < maxDepth else {
throw RepackError.configurationInvalid(
detail: "artifact directory nesting exceeds \(maxDepth)")
diff --git a/Sources/TurboFieldfareRepack/Core/System/VisionPackMutationLock.swift b/Sources/TurboFieldfareRepack/Core/System/VisionPackMutationLock.swift
new file mode 100644
index 00000000..8f079f38
--- /dev/null
+++ b/Sources/TurboFieldfareRepack/Core/System/VisionPackMutationLock.swift
@@ -0,0 +1,56 @@
+import Darwin
+import Foundation
+
+final class VisionPackMutationLock {
+ private let descriptor: Int32
+
+ private init(descriptor: Int32) {
+ self.descriptor = descriptor
+ }
+
+ deinit {
+ _ = flock(descriptor, LOCK_UN)
+ close(descriptor)
+ }
+
+ /// The path both sides of this lock must agree on. Readers derive it in
+ /// another module, from a companion URL; if the two derivations ever differ
+ /// the lock silently stops excluding anything, so the rule is written once:
+ /// resolve the parent physically, then name the file after the companion's
+ /// own last component.
+ static func lockPath(outputDirectory: String) throws -> String {
+ let output = URL(fileURLWithPath: outputDirectory).standardizedFileURL
+ let parent = try Posix.physicalPath(output.deletingLastPathComponent().path)
+ return (parent as NSString).appendingPathComponent(
+ ".\(output.lastPathComponent).use.lock")
+ }
+
+ static func acquire(outputDirectory: String) throws -> VisionPackMutationLock {
+ let path = try lockPath(outputDirectory: outputDirectory)
+ let descriptor = try Posix.openLock(path)
+ guard flock(descriptor, LOCK_EX | LOCK_NB) == 0 else {
+ let savedErrno = errno
+ close(descriptor)
+ if savedErrno == EWOULDBLOCK {
+ throw RepackError.installBusy(
+ path: path, holder: .installerOrLoadedModel)
+ }
+ throw RepackError.fileOpenFailed(path: path, errno: savedErrno)
+ }
+ do {
+ // The file could have been replaced between open and flock, which
+ // would leave this holding an exclusive lock on an unlinked inode
+ // while a reader locks the new one. `InstallLock` already checks
+ // this; both mutation paths have to.
+ guard try Posix.descriptorMatchesPath(descriptor, path: path) else {
+ throw RepackError.installPathUnsafe(
+ path: path, detail: "lock path was replaced during acquisition")
+ }
+ } catch {
+ _ = flock(descriptor, LOCK_UN)
+ close(descriptor)
+ throw error
+ }
+ return VisionPackMutationLock(descriptor: descriptor)
+ }
+}
diff --git a/Sources/TurboFieldfareRepack/Core/Verification/Sha256Stream.swift b/Sources/TurboFieldfareRepack/Core/Verification/Sha256Stream.swift
index 24ad3280..4720f729 100644
--- a/Sources/TurboFieldfareRepack/Core/Verification/Sha256Stream.swift
+++ b/Sources/TurboFieldfareRepack/Core/Verification/Sha256Stream.swift
@@ -23,7 +23,8 @@ struct Sha256Stream {
static func hashFile(path: String,
tileBytes: Int = 65_536,
noCache: Bool = false,
- noFollow: Bool = false) throws -> String {
+ noFollow: Bool = false,
+ onProgress: ((UInt64) throws -> Void)? = nil) throws -> String {
let flags = O_RDONLY | (noFollow ? O_NOFOLLOW : 0)
let fd = open(path, flags)
if fd < 0 { throw RepackError.fileOpenFailed(path: path, errno: errno) }
@@ -31,13 +32,15 @@ struct Sha256Stream {
if noCache {
_ = fcntl(fd, F_NOCACHE, 1)
}
- return try hashFileDescriptor(fd, displayPath: path, tileBytes: tileBytes)
+ return try hashFileDescriptor(fd, displayPath: path, tileBytes: tileBytes,
+ onProgress: onProgress)
}
package static func hashFileDescriptor(_ fd: Int32,
displayPath: String,
tileBytes: Int = 65_536,
- noCache: Bool = false) throws -> String {
+ noCache: Bool = false,
+ onProgress: ((UInt64) throws -> Void)? = nil) throws -> String {
guard tileBytes > 0 else {
throw RepackError.configurationInvalid(detail: "SHA-256 tile size must be positive")
}
@@ -56,6 +59,7 @@ struct Sha256Stream {
if got == 0 { break }
hasher.update(UnsafeRawBufferPointer(start: buf.baseAddress, count: got))
off += off_t(got)
+ try onProgress?(UInt64(off))
}
return hasher.finalizeHexString()
}
diff --git a/Sources/TurboFieldfareRepack/Core/Verification/VerifiedInstallTool.swift b/Sources/TurboFieldfareRepack/Core/Verification/VerifiedInstallTool.swift
index 582e3bd9..b6963372 100644
--- a/Sources/TurboFieldfareRepack/Core/Verification/VerifiedInstallTool.swift
+++ b/Sources/TurboFieldfareRepack/Core/Verification/VerifiedInstallTool.swift
@@ -192,7 +192,13 @@ public enum VerifiedInstallTool {
var unexpected: [String] = []
for rel in try access.relativeEntries(maxDepth: scanDepth) {
- if rel == ".DS_Store" { continue }
+ // Every path component, not just a literal top-level `.DS_Store`:
+ // a directory that went through Finder, SMB or an archive comes back
+ // with AppleDouble `._x` files, `.icloud` placeholders and a Spotlight
+ // index, none of which make a cryptographically valid install invalid.
+ if rel.split(separator: "/").contains(where: {
+ GTurboVisionFormatV1.isSidecarEntry(String($0))
+ }) { continue }
if rel == "tokenizer" || rel.hasPrefix("tokenizer/") { continue }
if !allowed.contains(rel) {
unexpected.append(rel)
diff --git a/Sources/TurboFieldfareRepack/Core/Verification/VisionPackVerifier.swift b/Sources/TurboFieldfareRepack/Core/Verification/VisionPackVerifier.swift
new file mode 100644
index 00000000..5bddd255
--- /dev/null
+++ b/Sources/TurboFieldfareRepack/Core/Verification/VisionPackVerifier.swift
@@ -0,0 +1,162 @@
+import Darwin
+import Foundation
+import TurboFieldfareFormat
+
+public struct VisionPackVerification: Sendable, Equatable {
+ public let manifestSha256: String
+ public let weightsBytes: UInt64
+ public let sourceRevision: String
+ public let sourceIndexSha256: String
+ /// The text manifest this pack is bound to. Carried out so a successful
+ /// verification can say *what it verified against*: two installs of the
+ /// same revision are byte-identical, and without this the success line
+ /// cannot distinguish which binding was checked.
+ public let compatibleTextManifestSha256: String
+}
+
+public enum VisionPackVerifier {
+ public static func verify(
+ directory: URL,
+ installedDirectory: URL? = nil,
+ textModelDirectory: URL,
+ verifyWeights: Bool = true,
+ onHashProgress: ((UInt64, UInt64) throws -> Void)? = nil
+ ) throws -> VisionPackVerification {
+ let directory = directory.standardizedFileURL
+ let installedDirectory = (installedDirectory ?? directory).standardizedFileURL
+ let access = try GTurboDirectoryAccess(rootPath: directory.path)
+ let expectedEntries = Set([
+ GTurboVisionFormatV1.manifestFile,
+ GTurboVisionFormatV1.weightsFile,
+ GTurboVisionFormatV1.processorFile,
+ GTurboVisionFormatV1.receiptFile,
+ ])
+ // Room for the four payload files plus every sidecar a round-trip can
+ // leave beside them: `.DS_Store`, an AppleDouble `._x` per file, an
+ // `.icloud` placeholder per file. The cap is what bounds the listing's
+ // memory and its one fstat per entry, so it stays a small constant
+ // instead of walking an arbitrarily large directory.
+ let scanned = try access.relativeEntries(maxDepth: 0, maxEntries: 64)
+ // Ignoring what the OS wrote beside the pack, exactly as the runtime
+ // store does, so the installer and the loader agree on what a valid
+ // pack directory is. A depth-0 scan yields basenames, which is what
+ // isSidecarEntry matches on. Equality still rejects a missing, renamed
+ // or genuinely unexpected file.
+ let entries = Set(scanned.filter { !GTurboVisionFormatV1.isSidecarEntry($0) })
+ guard entries == expectedEntries else {
+ // Both directions, because a *missing* file used to be reported as
+ // the surviving files being "unexpected", which sends the reader
+ // looking for surplus entries that are not there.
+ throw RepackError.configurationInvalid(
+ detail: "vision companion directory does not match the v1 "
+ + "contract: " + GTurboVisionFormatV1.entryDifference(
+ expected: expectedEntries, actual: entries))
+ }
+
+ let manifestData = try access.readMetadata(
+ GTurboVisionFormatV1.manifestFile,
+ maxBytes: GTurboVisionFormatV1.metadataMaxBytes)
+ let receiptData = try access.readMetadata(
+ GTurboVisionFormatV1.receiptFile,
+ maxBytes: GTurboVisionFormatV1.metadataMaxBytes)
+ let manifest = try GTurboVisionManifestCodec.decode(manifestData)
+ let receipt = try GTurboVisionReceiptCodec.decode(receiptData)
+
+ let textManifestPath = textModelDirectory.standardizedFileURL
+ .appendingPathComponent(GTurboVisionFormatV1.manifestFile).path
+ let textManifestData = try Posix.readBoundedData(
+ textManifestPath,
+ maximumBytes: GTurboVisionFormatV1.metadataMaxBytes)
+ let textManifest = try GTurboManifestCodec.decode(textManifestData)
+ guard let textSource = textManifest.sourceSnapshotHash,
+ manifest.compatibleTextSourceSnapshotHash == textSource else {
+ throw RepackError.installStateIncompatible(
+ detail: "vision companion belongs to a different text checkpoint")
+ }
+ let textManifestSHA = hash(textManifestData)
+ guard manifest.compatibleTextManifestSha256.lowercased() == textManifestSHA,
+ receipt.compatibleTextManifestSha256.lowercased() == textManifestSHA else {
+ throw RepackError.installStateIncompatible(
+ detail: "vision companion text manifest binding changed")
+ }
+
+ let manifestSHA = hash(manifestData)
+ let receiptDirectory = canonicalDirectoryPath(URL(
+ fileURLWithPath: receipt.companionDirectoryPath,
+ isDirectory: true))
+ let expectedDirectory = canonicalDirectoryPath(installedDirectory)
+ guard receipt.manifestSha256.lowercased() == manifestSHA else {
+ throw RepackError.configurationInvalid(
+ detail: "vision companion receipt manifest binding mismatch")
+ }
+ guard receiptDirectory == expectedDirectory else {
+ throw RepackError.configurationInvalid(
+ detail: "vision companion receipt directory binding mismatch")
+ }
+ guard receipt.sourceRepoID == manifest.modelID,
+ receipt.sourceRevision == manifest.sourceRevision else {
+ throw RepackError.configurationInvalid(
+ detail: "vision companion receipt source binding mismatch")
+ }
+
+ let totalBytes = manifest.files.reduce(UInt64(0)) { total, entry in
+ verifyWeights || entry.key != GTurboVisionFormatV1.weightsFile
+ ? total + entry.value.size : total
+ }
+ var hashedBytes: UInt64 = 0
+ for (relativePath, expected) in manifest.files {
+ let actualSize = try access.fileSize(relativePath)
+ guard actualSize == expected.size else {
+ throw RepackError.configurationInvalid(
+ detail: "\(relativePath) size \(actualSize) != \(expected.size)")
+ }
+ guard receipt.files[relativePath] == expected else {
+ throw RepackError.configurationInvalid(
+ detail: "\(relativePath) receipt mismatch")
+ }
+ if verifyWeights || relativePath != GTurboVisionFormatV1.weightsFile {
+ let path = directory.appendingPathComponent(relativePath).path
+ // Reported against the total the manifest declares, so the
+ // caller can show a fraction rather than a bare spinner for the
+ // minutes this takes over ~1.5 GB.
+ let alreadyHashed = hashedBytes
+ let actualSHA = try Sha256Stream.hashFile(
+ path: path, noCache: true, noFollow: true,
+ onProgress: onHashProgress.map { report in
+ { try report(alreadyHashed + $0, totalBytes) }
+ })
+ hashedBytes = alreadyHashed + actualSize
+ guard actualSHA == expected.sha256.lowercased() else {
+ throw RepackError.configurationInvalid(
+ detail: "\(relativePath) hash mismatch")
+ }
+ }
+ }
+ guard let manifestReceipt = receipt.files[GTurboVisionFormatV1.manifestFile],
+ manifestReceipt.size == UInt64(manifestData.count),
+ manifestReceipt.sha256.lowercased() == manifestSHA else {
+ throw RepackError.configurationInvalid(
+ detail: "vision manifest receipt entry mismatch")
+ }
+ return VisionPackVerification(
+ manifestSha256: manifestSHA,
+ weightsBytes: manifest.files[GTurboVisionFormatV1.weightsFile]!.size,
+ sourceRevision: manifest.sourceRevision,
+ sourceIndexSha256: manifest.sourceIndexSha256,
+ compatibleTextManifestSha256: textManifestSHA)
+ }
+
+ private static func hash(_ data: Data) -> String {
+ var stream = Sha256Stream()
+ data.withUnsafeBytes { stream.update($0) }
+ return stream.finalizeHexString()
+ }
+
+ private static func canonicalDirectoryPath(_ url: URL) -> String {
+ let standardized = url.standardizedFileURL
+ return standardized.deletingLastPathComponent()
+ .resolvingSymlinksInPath()
+ .appendingPathComponent(standardized.lastPathComponent, isDirectory: true)
+ .standardizedFileURL.path
+ }
+}
diff --git a/Sources/TurboFieldfareRepack/Core/Workflow/Errors.swift b/Sources/TurboFieldfareRepack/Core/Workflow/Errors.swift
index 607e7bfc..689adcf7 100644
--- a/Sources/TurboFieldfareRepack/Core/Workflow/Errors.swift
+++ b/Sources/TurboFieldfareRepack/Core/Workflow/Errors.swift
@@ -1,5 +1,14 @@
import Foundation
+/// Who a refused lock is waiting on. The pack's use lease is *shared*, so a
+/// blocked mutation is as likely to be waiting on a loaded model as on another
+/// install, and saying "another installer" sent users hunting for a process
+/// that does not exist.
+public enum RepackBusyHolder: Sendable, Equatable {
+ case installer
+ case installerOrLoadedModel
+}
+
public enum RepackError: Error, CustomStringConvertible {
case fileOpenFailed(path: String, errno: Int32)
case fileStatFailed(path: String, errno: Int32)
@@ -10,7 +19,7 @@ public enum RepackError: Error, CustomStringConvertible {
case renameFailed(from: String, to: String, errno: Int32)
case fsyncFailed(path: String, errno: Int32)
case mkdirFailed(path: String, errno: Int32)
- case installBusy(path: String)
+ case installBusy(path: String, holder: RepackBusyHolder = .installer)
case installPathUnsafe(path: String, detail: String)
case installStateMissing(path: String)
case installStateCorrupt(path: String, detail: String)
@@ -62,8 +71,15 @@ public enum RepackError: Error, CustomStringConvertible {
case .renameFailed(let a, let b, let e):return "rename(\(a) -> \(b)) failed: errno \(e)"
case .fsyncFailed(let p, let e): return "fsync(\(p)) failed: errno \(e)"
case .mkdirFailed(let p, let e): return "mkdir(\(p)) failed: errno \(e)"
- case .installBusy(let p):
- return "another installer holds \(p)"
+ case .installBusy(let p, let holder):
+ switch holder {
+ case .installer:
+ return "another installer holds \(p)"
+ case .installerOrLoadedModel:
+ return "\(p) is in use: another installer or a loaded model "
+ + "holds this pack; unload the model or wait for the "
+ + "install to finish"
+ }
case .installPathUnsafe(let p, let d):
return "unsafe installer path \(p): \(d)"
case .installStateMissing(let p):
diff --git a/Sources/TurboFieldfareRepack/Core/Workflow/InstallProgressReporter.swift b/Sources/TurboFieldfareRepack/Core/Workflow/InstallProgressReporter.swift
new file mode 100644
index 00000000..0bec84a2
--- /dev/null
+++ b/Sources/TurboFieldfareRepack/Core/Workflow/InstallProgressReporter.swift
@@ -0,0 +1,92 @@
+import Foundation
+
+/// Turns install progress into one terse stderr line, rate-limited so a
+/// 14.6 GB transfer reports movement without scrolling.
+///
+/// Without this the installer printed nothing at all between the command and
+/// "Installed", for the whole transfer: no bytes, no percentage, no sign it was
+/// alive. The data was already there - both installers take a progress closure,
+/// and `main.swift` passed none.
+public struct InstallProgressReporter: Sendable {
+ private let write: @Sendable (String) -> Void
+ private let minimumInterval: Double
+ private let state = State()
+
+ private final class State: @unchecked Sendable {
+ var lastReport: Double = 0
+ var lastPhase: String = ""
+ }
+
+ public init(minimumInterval: Double = 2,
+ write: @escaping @Sendable (String) -> Void = { message in
+ FileHandle.standardError.write(Data(message.utf8))
+ }) {
+ self.minimumInterval = minimumInterval
+ self.write = write
+ }
+
+ public func report(_ progress: ModelInstallProgress, now: Double) {
+ guard let line = Self.line(for: progress) else { return }
+ let phase = Self.phase(of: progress)
+ // Rate-limited per phase, so the byte counter throttles while a phase
+ // change is always announced.
+ if phase == state.lastPhase, now - state.lastReport < minimumInterval {
+ return
+ }
+ state.lastPhase = phase
+ state.lastReport = now
+ write(line + "\n")
+ }
+
+ public func callAsFunction(_ progress: ModelInstallProgress) {
+ report(progress, now: Date().timeIntervalSince1970)
+ }
+
+ static func phase(of progress: ModelInstallProgress) -> String {
+ switch progress {
+ case .downloadingMetadata: "metadata"
+ case .planning: "planning"
+ case .checkingDisk: "disk"
+ case .reservingOutput: "reserving"
+ case .copyingPayload: "copying"
+ case .hashingOutput: "hashing"
+ case .finalizing: "finalizing"
+ }
+ }
+
+ static func line(for progress: ModelInstallProgress) -> String? {
+ switch progress {
+ case .downloadingMetadata:
+ return "[install] reading source metadata"
+ case let .planning(downloadBytes, outputBytes):
+ return "[install] planned: \(bytes(downloadBytes)) to download, "
+ + "\(bytes(outputBytes)) to write"
+ case .checkingDisk:
+ return "[install] checking free space"
+ case let .reservingOutput(bytes: reserved):
+ return "[install] reserving \(bytes(reserved))"
+ case let .copyingPayload(reused, downloaded, total):
+ let done = reused + downloaded
+ let percent = total == 0 ? 0 : Int((Double(done) / Double(total)) * 100)
+ return "[install] \(bytes(done)) of \(bytes(total)) (\(percent)%)"
+ + (reused > 0 ? ", \(bytes(reused)) already on disk" : "")
+ case let .hashingOutput(file):
+ return "[install] verifying \(file)"
+ case .finalizing:
+ return "[install] finalizing"
+ }
+ }
+
+ static func bytes(_ count: UInt64) -> String {
+ let units = ["B", "KiB", "MiB", "GiB"]
+ var value = Double(count)
+ var unit = 0
+ while value >= 1024, unit < units.count - 1 {
+ value /= 1024
+ unit += 1
+ }
+ return unit == 0
+ ? "\(count) B"
+ : String(format: "%.1f %@", value, units[unit])
+ }
+}
diff --git a/Sources/TurboFieldfareRepack/Core/Writing/VisionPackWriter.swift b/Sources/TurboFieldfareRepack/Core/Writing/VisionPackWriter.swift
new file mode 100644
index 00000000..f2b4b890
--- /dev/null
+++ b/Sources/TurboFieldfareRepack/Core/Writing/VisionPackWriter.swift
@@ -0,0 +1,211 @@
+import Darwin
+import Foundation
+import TurboFieldfareFormat
+
+public struct VisionPackWriteOptions: Sendable {
+ public let inputDirectory: String
+ public let textModelDirectory: String
+ public let outputDirectory: String
+ public let sourceRevision: String
+ public let overwrite: Bool
+
+ public init(inputDirectory: String, textModelDirectory: String,
+ outputDirectory: String, sourceRevision: String,
+ overwrite: Bool = false) {
+ self.inputDirectory = inputDirectory
+ self.textModelDirectory = textModelDirectory
+ self.outputDirectory = outputDirectory
+ self.sourceRevision = sourceRevision
+ self.overwrite = overwrite
+ }
+}
+
+public struct VisionPackWriteResult: Sendable {
+ public let tensorCount: Int
+ public let sourcePayloadBytes: UInt64
+ public let weightsFileSize: UInt64
+ public let manifestSha256: String
+ public let peakRSSBytes: UInt64
+ public let largestScratchBytes: Int
+}
+
+public enum VisionPackWriter {
+ public static func write(
+ options: VisionPackWriteOptions,
+ audit: RepackAudit = RepackAudit()
+ ) throws -> VisionPackWriteResult {
+ let meta = try IndexLoader.load(snapshotDir: options.inputDirectory)
+ guard let modelID = SourceFingerprint.modelID(forIndexSha256: meta.indexSha256Hex),
+ modelID == "mlx-community/gemma-4-26b-a4b-it-4bit" else {
+ throw RepackError.sourceFingerprintRejected(
+ path: meta.indexPath, sha256: meta.indexSha256Hex)
+ }
+
+ var headers: [Safetensors.Header] = []
+ for filename in meta.shardFilenames {
+ let path = (options.inputDirectory as NSString).appendingPathComponent(filename)
+ headers.append(try Safetensors.parseHeader(path: path))
+ }
+ let plan = try RepackPlanner.planVisionCompanion(meta: meta, shardHeaders: headers)
+
+ let textManifestPath = (options.textModelDirectory as NSString)
+ .appendingPathComponent(GTurboVisionFormatV1.manifestFile)
+ let textManifestData = try Posix.readBoundedData(
+ textManifestPath, maximumBytes: GTurboVisionFormatV1.metadataMaxBytes)
+ let textManifest = try GTurboManifestCodec.decode(textManifestData)
+ guard let textSnapshot = textManifest.sourceSnapshotHash,
+ !textSnapshot.isEmpty else {
+ throw RepackError.configurationInvalid(
+ detail: "text manifest has no sourceSnapshotHash")
+ }
+ let textManifestSHA = Sha256Stream.hash(data: textManifestData)
+
+ let processorSource = (options.inputDirectory as NSString)
+ .appendingPathComponent(GTurboVisionFormatV1.processorFile)
+ let processorData = try Posix.readBoundedData(
+ processorSource,
+ maximumBytes: GTurboVisionFormatV1.metadataMaxBytes,
+ followCallerSymlink: true)
+ let processorSHA = Sha256Stream.hash(data: processorData)
+
+ let installLock = try InstallLock.acquire(
+ outputDirectory: options.outputDirectory)
+ defer { withExtendedLifetime(installLock) {} }
+ let finalURL = URL(
+ fileURLWithPath: installLock.paths.finalDirectory,
+ isDirectory: true)
+ let partial = installLock.paths.partialDirectory
+ let fm = FileManager.default
+ if fm.fileExists(atPath: partial) {
+ guard options.overwrite else {
+ throw RepackError.configurationInvalid(
+ detail: "output exists: \(partial); pass --overwrite")
+ }
+ try fm.removeItem(atPath: partial)
+ }
+ if fm.fileExists(atPath: finalURL.path), !options.overwrite {
+ throw RepackError.configurationInvalid(
+ detail: "output exists: \(finalURL.path); pass --overwrite")
+ }
+ try Posix.mkdirP(partial)
+ do {
+ let weightsPath = (partial as NSString)
+ .appendingPathComponent(GTurboVisionFormatV1.weightsFile)
+ let weightsFD = try Posix.openCreateRW(weightsPath)
+ defer { close(weightsFD) }
+ try Posix.ftruncate(weightsFD, path: weightsPath, size: plan.weightsFileSize)
+
+ var mappings: [String: MmapHandle] = [:]
+ for entry in plan.entries {
+ let mapping: MmapHandle
+ if let existing = mappings[entry.source.shardPath] {
+ mapping = existing
+ } else {
+ mapping = try MmapHandle(path: entry.source.shardPath)
+ mappings[entry.source.shardPath] = mapping
+ }
+ try WriterCore.pwriteTensorRegion(
+ srcShard: mapping,
+ srcAbsoluteOffset: entry.source.absoluteOffset,
+ size: entry.source.sizeBytes,
+ dstFd: weightsFD,
+ dstPath: weightsPath,
+ dstOffset: entry.fileOffset,
+ audit: audit)
+ }
+ try Posix.fsync(weightsFD, path: weightsPath)
+ mappings.removeAll()
+
+ let processorPath = (partial as NSString)
+ .appendingPathComponent(GTurboVisionFormatV1.processorFile)
+ try Posix.atomicWrite(processorData, to: processorPath, durableIn: partial)
+
+ let weightsSHA = try WriterCore.hashEntireFile(
+ path: weightsPath, size: plan.weightsFileSize, audit: audit)
+ let files = [
+ GTurboVisionFormatV1.weightsFile: GTurboManifestFileV1(
+ size: plan.weightsFileSize, sha256: weightsSHA),
+ GTurboVisionFormatV1.processorFile: GTurboManifestFileV1(
+ size: UInt64(processorData.count), sha256: processorSHA),
+ ]
+ let tensors = plan.entries.map { entry in
+ GTurboVisionTensorRegionV1(
+ name: entry.source.name,
+ executionPosition: entry.executionPosition,
+ offset: entry.fileOffset,
+ size: entry.source.sizeBytes,
+ shape: entry.source.shape,
+ dtype: entry.source.dtype == .u32 ? .u32 : .bf16,
+ quantization: entry.quantSpec.map { spec in
+ GTurboVisionQuantizationV1(
+ weightBits: spec.bits, scheme: "affine",
+ scaleType: "bf16", biasType: "bf16",
+ groupSize: entry.groupSize)
+ })
+ }
+ let manifest = GTurboVisionManifestV1(
+ modelID: modelID,
+ sourceRevision: options.sourceRevision,
+ sourceIndexSha256: meta.indexSha256Hex,
+ processorConfigSha256: processorSHA,
+ compatibleTextSourceSnapshotHash: textSnapshot,
+ compatibleTextManifestSha256: textManifestSHA,
+ files: files,
+ tensors: tensors)
+ let manifestData = try GTurboVisionManifestCodec.encode(manifest)
+ let manifestPath = (partial as NSString)
+ .appendingPathComponent(GTurboVisionFormatV1.manifestFile)
+ try Posix.atomicWrite(manifestData, to: manifestPath, durableIn: partial)
+ let manifestSHA = Sha256Stream.hash(data: manifestData)
+
+ let receiptFiles = files.merging([
+ GTurboVisionFormatV1.manifestFile: GTurboManifestFileV1(
+ size: UInt64(manifestData.count), sha256: manifestSHA)
+ ]) { _, new in new }
+ let receipt = GTurboVisionReceiptV1(
+ manifestSha256: manifestSHA,
+ companionDirectoryPath: finalURL.path,
+ compatibleTextManifestSha256: textManifestSHA,
+ sourceRepoID: modelID,
+ sourceRevision: options.sourceRevision,
+ verificationTimestamp: "source-revision:\(options.sourceRevision)",
+ toolVersion: "TurboFieldfareRepack/vision-v1",
+ files: receiptFiles)
+ let receiptData = try GTurboVisionReceiptCodec.encode(receipt)
+ let receiptPath = (partial as NSString)
+ .appendingPathComponent(GTurboVisionFormatV1.receiptFile)
+ try Posix.atomicWrite(receiptData, to: receiptPath, durableIn: partial)
+ try Posix.fsyncDirectory(partial)
+ let useLock = try VisionPackMutationLock.acquire(
+ outputDirectory: finalURL.path)
+ defer { withExtendedLifetime(useLock) {} }
+ if try Posix.entryKind(finalURL.path) == .directory {
+ try Posix.renameSwap(partial, finalURL.path)
+ try Posix.fsyncDirectory(finalURL.deletingLastPathComponent().path)
+ try fm.removeItem(atPath: partial)
+ } else {
+ try Posix.rename(from: partial, to: finalURL.path)
+ try Posix.fsyncDirectory(finalURL.deletingLastPathComponent().path)
+ }
+
+ audit.sampleRSS()
+ return VisionPackWriteResult(
+ tensorCount: plan.entries.count,
+ sourcePayloadBytes: plan.sourcePayloadBytes,
+ weightsFileSize: plan.weightsFileSize,
+ manifestSha256: manifestSHA,
+ peakRSSBytes: audit.peakRssBytes,
+ largestScratchBytes: audit.largestScratchBytes)
+ } catch {
+ throw error
+ }
+ }
+}
+
+private extension Sha256Stream {
+ static func hash(data: Data) -> String {
+ var hasher = Sha256Stream()
+ data.withUnsafeBytes { hasher.update($0) }
+ return hasher.finalizeHexString()
+ }
+}
diff --git a/Sources/TurboFieldfareServer/Command/main.swift b/Sources/TurboFieldfareServer/Command/main.swift
index f9f4ec60..bb2f6899 100644
--- a/Sources/TurboFieldfareServer/Command/main.swift
+++ b/Sources/TurboFieldfareServer/Command/main.swift
@@ -3,6 +3,13 @@ import Foundation
import TurboFieldfare
import TurboFieldfareServerCore
+// Every request line goes to stderr, which is unbuffered, while the ready line
+// below goes to stdout, which is fully buffered when it is not a terminal. A
+// server started with its output redirected therefore showed an empty log for
+// its whole life and printed "ready" only as it exited - exactly inverted from
+// what an operator needs. Line buffering puts the line where it is useful.
+setvbuf(stdout, nil, _IOLBF, 0)
+
let arguments: ServerArguments
let runtimeConfiguration: RuntimeConfiguration
do {
@@ -24,14 +31,19 @@ do {
let backend = try await ServerModelSession.load(
modelDirectory: modelURL,
maxContext: arguments.maxContext,
+ visionPackURL: arguments.visionPack.map {
+ URL(fileURLWithPath: $0).standardizedFileURL
+ },
+ visionResidencyPolicy: arguments.visionResidency,
promptCacheMode: arguments.promptCacheMode,
runtimeConfiguration: runtimeConfiguration)
let server = TurboFieldfareHTTPServer(
modelID: arguments.modelID,
queueLimit: arguments.queueLimit,
- backend: backend)
+ backend: backend,
+ visionCapability: backend.visionCapability)
_ = try await server.start(port: arguments.port)
- print("TurboFieldfareServer ready at http://127.0.0.1:\(arguments.port) model=\(arguments.modelID) context=\(arguments.maxContext) prompt_cache=\(arguments.promptCacheMode.rawValue)")
+ print("TurboFieldfareServer ready at http://127.0.0.1:\(arguments.port) model=\(arguments.modelID) context=\(arguments.maxContext) prompt_cache=\(arguments.promptCacheMode.rawValue) vision=\(backend.visionCapability) vision_residency=\(arguments.visionResidency.rawValue)")
_ = await signals.wait()
try await server.shutdown()
diff --git a/Sources/TurboFieldfareServer/Core/HTTPServer.swift b/Sources/TurboFieldfareServer/Core/HTTPServer.swift
index 7bb7a5b7..539d9218 100644
--- a/Sources/TurboFieldfareServer/Core/HTTPServer.swift
+++ b/Sources/TurboFieldfareServer/Core/HTTPServer.swift
@@ -6,13 +6,23 @@ import Synchronization
import TurboFieldfare
public actor TurboFieldfareHTTPServer {
- public static let maximumBodyBytes = 1_048_576
+ public static let maximumBodyBytes = StreamingChatRequestBody.maximumWireBytes
+ /// Accepted sockets are unbounded otherwise, and each one costs a file
+ /// descriptor plus whatever its half-sent request has staged.
+ public static let maximumConnections = 128
+ /// How long a connection may sit without being read from before it is
+ /// closed. Generous, because it must never interrupt a slow client that is
+ /// still uploading images.
+ public static let idleTimeout = TimeAmount.seconds(120)
private let group: MultiThreadedEventLoopGroup
private let modelID: String
private let backend: any ServerInferenceBackend
private let coordinator: ServerCoordinator
private let heartbeatInterval: TimeAmount
+ private let visionCapability: String
+ private let attachmentRoot: URL
+ private let idleTimeout: TimeAmount
private let childChannels = ChildChannelRegistry()
private var channel: Channel?
private var shutdownTask: Task<Void, any Error>?
@@ -21,12 +31,19 @@ public actor TurboFieldfareHTTPServer {
queueLimit: Int,
backend: any ServerInferenceBackend,
heartbeatInterval: TimeAmount = .seconds(5),
+ visionCapability: String = "missing",
+ attachmentRoot: URL = ServerAttachmentDirectory.root,
+ idleTimeout: TimeAmount = TurboFieldfareHTTPServer.idleTimeout,
group: MultiThreadedEventLoopGroup = .init(numberOfThreads: 1)) {
self.group = group
self.modelID = modelID
self.backend = backend
self.coordinator = ServerCoordinator(queueLimit: queueLimit)
self.heartbeatInterval = heartbeatInterval
+ self.visionCapability = visionCapability
+ self.attachmentRoot = attachmentRoot
+ self.idleTimeout = idleTimeout
+ ServerAttachmentDirectory.sweepAbandoned(in: attachmentRoot)
}
public func start(port: Int) async throws -> Channel {
@@ -35,20 +52,28 @@ public actor TurboFieldfareHTTPServer {
let coordinator = self.coordinator
let heartbeatInterval = self.heartbeatInterval
let childChannels = self.childChannels
+ let visionCapability = self.visionCapability
+ let attachmentRoot = self.attachmentRoot
+ let idleTimeout = self.idleTimeout
let bootstrap = ServerBootstrap(group: group)
.serverChannelOption(ChannelOptions.backlog, value: 16)
.serverChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)
.childChannelInitializer { channel in
childChannels.insert(channel)
- return channel.pipeline.configureHTTPServerPipeline(
- withPipeliningAssistance: true,
- withErrorHandling: true
+ return channel.pipeline.addHandler(
+ IdleStateHandler(readTimeout: idleTimeout)
).flatMap {
+ channel.pipeline.configureHTTPServerPipeline(
+ withPipeliningAssistance: true,
+ withErrorHandling: true)
+ }.flatMap {
channel.pipeline.addHandler(ServerHTTPHandler(
modelID: modelID,
backend: backend,
coordinator: coordinator,
heartbeatInterval: heartbeatInterval,
+ visionCapability: visionCapability,
+ attachmentRoot: attachmentRoot,
childChannels: childChannels))
}
}
@@ -118,70 +143,168 @@ private final class ServerHTTPHandler: ChannelInboundHandler, @unchecked Sendabl
private let coordinator: ServerCoordinator
private let heartbeatInterval: TimeAmount
private let childChannels: ChildChannelRegistry
+ private let visionCapability: String
+ private let attachmentRoot: URL
+ private var bodyParser: StreamingChatRequestBody?
+ private var bodyError: (any Error)?
+ private var receivedBodyBytes = 0
+ /// Past the wire cap the drain toward `.end` is unbounded - a chunked
+ /// stream may never send one - so the request is answered immediately
+ /// and everything after it dropped until the connection closes.
+ private var discardingUntilClose = false
+ /// Requests still producing an answer. A generation reads nothing for as
+ /// long as it runs, so the idle timeout must not close under it.
+ private var inFlightRequests = 0
private var head: HTTPRequestHead?
- private var body = ByteBuffer()
- private var oversized = false
private var activeTask: Task<Void, Never>?
init(modelID: String,
backend: any ServerInferenceBackend,
coordinator: ServerCoordinator,
heartbeatInterval: TimeAmount,
+ visionCapability: String,
+ attachmentRoot: URL,
childChannels: ChildChannelRegistry) {
self.modelID = modelID
self.backend = backend
self.coordinator = coordinator
self.heartbeatInterval = heartbeatInterval
+ self.visionCapability = visionCapability
+ self.attachmentRoot = attachmentRoot
self.childChannels = childChannels
}
+ static let chatCompletionsPath = "/v1/chat/completions"
+
+ static func requestPath(_ head: HTTPRequestHead) -> String {
+ head.uri.split(separator: "?", maxSplits: 1,
+ omittingEmptySubsequences: false)
+ .first.map(String.init) ?? head.uri
+ }
+
+ static func carriesChatBody(_ head: HTTPRequestHead) -> Bool {
+ head.method == .POST
+ && requestPath(head) == chatCompletionsPath
+ && head.headers.first(name: "content-type")?
+ .lowercased().hasPrefix("application/json") == true
+ }
+
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
switch unwrapInboundIn(data) {
case .head(let head):
+ guard !discardingUntilClose else { return }
self.head = head
- body.clear()
- oversized = false
+ // The parser stages inline images to disk, so it is created only
+ // once the request is known to carry a chat body. A body sent
+ // elsewhere is counted and dropped.
+ bodyParser = Self.carriesChatBody(head)
+ ? StreamingChatRequestBody(attachmentRoot: attachmentRoot,
+ visionCapability: visionCapability)
+ : nil
+ bodyError = nil
+ receivedBodyBytes = 0
case .body(var part):
- if body.readableBytes + part.readableBytes > TurboFieldfareHTTPServer.maximumBodyBytes {
- oversized = true
- } else {
- body.writeBuffer(&part)
+ guard !discardingUntilClose else { return }
+ receivedBodyBytes += part.readableBytes
+ if receivedBodyBytes > StreamingChatRequestBody.maximumWireBytes {
+ // A body already rejected for its own reason keeps it: telling a
+ // client its image was too large is more useful than telling it
+ // the request was, and the drain past the cap is what forces the
+ // answer now.
+ let capError = (bodyError as? ServerRequestError)
+ ?? ServerRequestError.invalid(
+ message: "request body is too large",
+ param: nil, code: "request_too_large")
+ bodyError = nil
+ bodyParser = nil
+ head = nil
+ discardingUntilClose = true
+ writeError(context, status: capError.httpStatus, capError.envelope,
+ closeAfter: true)
+ return
+ }
+ guard bodyError == nil else { return }
+ guard let parser = bodyParser else { return }
+ do { try parser.feed(&part) }
+ catch {
+ bodyError = error
+ // Rejection is already certain, so release the staged bytes now.
+ bodyParser = nil
}
case .end:
+ guard !discardingUntilClose else { return }
guard let head else { return }
self.head = nil
- if oversized {
- writeError(context, status: .payloadTooLarge,
- OpenAIErrorEnvelope(message: "request body is too large",
- code: "request_too_large"))
+ let parser = bodyParser
+ // Cleared on every path below: a retained parser pins its staged
+ // images until the connection closes.
+ bodyParser = nil
+ if let bodyError {
+ self.bodyError = nil
+ if let requestError = bodyError as? ServerRequestError {
+ writeError(context, status: requestError.httpStatus,
+ requestError.envelope)
+ } else {
+ writeError(context, status: .badRequest,
+ OpenAIErrorEnvelope(message: "malformed JSON request",
+ code: "invalid_json"))
+ }
return
}
- route(head: head, body: body, context: context)
+ do {
+ let parsed = try parser?.finish()
+ ?? ParsedChatRequestBody(json: Data(), stagedImages: [:], lease: nil)
+ route(head: head, body: parsed, context: context)
+ } catch let error as ServerRequestError {
+ writeError(context, status: error.httpStatus, error.envelope)
+ } catch {
+ writeError(context, status: .badRequest,
+ OpenAIErrorEnvelope(message: "malformed JSON request",
+ code: "invalid_json"))
+ }
+ }
+ }
+
+
+ func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {
+ if event is IdleStateHandler.IdleStateEvent, inFlightRequests == 0 {
+ context.close(promise: nil)
+ return
}
+ context.fireUserInboundEventTriggered(event)
}
func channelInactive(context: ChannelHandlerContext) {
activeTask?.cancel()
activeTask = nil
+ // Frees the staged images of a request abandoned mid-body.
+ bodyParser = nil
+ bodyError = nil
+ head = nil
childChannels.remove(context.channel)
context.fireChannelInactive()
}
private func route(head: HTTPRequestHead,
- body: ByteBuffer,
+ body: ParsedChatRequestBody,
context: ChannelHandlerContext) {
let path = head.uri.split(separator: "?", maxSplits: 1,
omittingEmptySubsequences: false).first.map(String.init) ?? head.uri
switch (head.method, path) {
case (.GET, "/health"):
- writeJSON(context, status: .ok, object: ["status": "ok"])
+ writeJSON(context, status: .ok, object: [
+ "status": "ok",
+ "vision": visionCapability,
+ ])
case (.GET, "/v1/models"):
let response = OpenAIModelList(
object: "list",
data: [.init(id: modelID,
object: "model",
created: 0,
- ownedBy: "turbofieldfare")])
+ ownedBy: "turbofieldfare",
+ capabilities: visionCapability == "ready"
+ ? ["text", "image"] : ["text"])])
writeCodable(context, status: .ok, response)
case (.POST, "/v1/chat/completions"):
guard head.headers.first(name: "content-type")?
@@ -203,12 +326,15 @@ private final class ServerHTTPHandler: ChannelInboundHandler, @unchecked Sendabl
}
}
- private func handleCompletion(body: ByteBuffer,
+ private func handleCompletion(body: ParsedChatRequestBody,
context: ChannelHandlerContext) {
do {
- let bytes = body.getBytes(at: body.readerIndex, length: body.readableBytes) ?? []
- let decoded = try JSONDecoder().decode(OpenAIChatRequest.self, from: Data(bytes))
- let request = try OpenAIRequestValidator.validate(decoded, modelID: modelID)
+ let decoded = try JSONDecoder().decode(OpenAIChatRequest.self, from: body.json)
+ let request = try OpenAIRequestValidator.validate(
+ decoded,
+ modelID: modelID,
+ preStagedImages: body.stagedImages,
+ attachmentLease: body.lease)
let responseID = "chatcmpl-" + UUID().uuidString.lowercased().replacingOccurrences(of: "-", with: "")
let created = Int(Date().timeIntervalSince1970)
let contextBox = SendableContext(context)
@@ -233,8 +359,17 @@ private final class ServerHTTPHandler: ChannelInboundHandler, @unchecked Sendabl
ServerLog.queued(id: responseID)
startStream()
}
+ inFlightRequests += 1
activeTask = childChannels.startTask {
defer { streamState.stop() }
+ // Back on the event loop, where `inFlightRequests` lives. The hop
+ // also orders this after the assignment above, which is still
+ // executing in this same event-loop tick.
+ defer {
+ contextBox.value.eventLoop.execute {
+ self.inFlightRequests -= 1
+ }
+ }
let started = ContinuousClock.now
ServerLog.accepted(id: responseID, streaming: request.stream)
do {
@@ -294,12 +429,13 @@ private final class ServerHTTPHandler: ChannelInboundHandler, @unchecked Sendabl
context: contextBox.value,
id: responseID,
phase: phaseState.value,
- stream: streamState.isStarted)
+ stream: streamState.isStarted,
+ started: started)
}
}
} catch let error as ServerRequestError {
writeError(context,
- status: error == .unknownModel ? .notFound : .badRequest,
+ status: error.httpStatus,
error.envelope)
} catch {
writeError(context, status: .badRequest,
@@ -463,11 +599,12 @@ private final class ServerHTTPHandler: ChannelInboundHandler, @unchecked Sendabl
context: ChannelHandlerContext,
id: String,
phase: String,
- stream: Bool) {
+ stream: Bool,
+ started: ContinuousClock.Instant) {
let envelope: OpenAIErrorEnvelope
let status: HTTPResponseStatus
if let requestError = error as? ServerRequestError {
- status = requestError == .queueFull ? .tooManyRequests : .badRequest
+ status = requestError.httpStatus
envelope = requestError.envelope
} else {
status = .internalServerError
@@ -476,7 +613,13 @@ private final class ServerHTTPHandler: ChannelInboundHandler, @unchecked Sendabl
code: "internal_error",
type: "server_error")
}
- if !(error is CancellationError) {
+ if error is CancellationError {
+ // Not a failure, and not silence either: without a terminal line the
+ // request's last record stayed `generating` forever, so a reader could
+ // not tell running from abandoned from crashed.
+ ServerLog.cancelled(id: id, phase: phase,
+ duration: started.duration(to: .now))
+ } else {
ServerLog.failed(id: id, phase: phase, status: status.code, error: error)
}
if stream {
@@ -506,15 +649,17 @@ private final class ServerHTTPHandler: ChannelInboundHandler, @unchecked Sendabl
private func writeCodable<T: Encodable>(_ context: ChannelHandlerContext,
status: HTTPResponseStatus,
- _ value: T) {
+ _ value: T,
+ closeAfter: Bool = false) {
guard let data = try? JSONEncoder().encode(value) else { return }
- writeData(context, status: status, data: data)
+ writeData(context, status: status, data: data, closeAfter: closeAfter)
}
private func writeError(_ context: ChannelHandlerContext,
status: HTTPResponseStatus,
- _ error: OpenAIErrorEnvelope) {
- writeCodable(context, status: status, error)
+ _ error: OpenAIErrorEnvelope,
+ closeAfter: Bool = false) {
+ writeCodable(context, status: status, error, closeAfter: closeAfter)
}
private func writeJSON(_ context: ChannelHandlerContext,
@@ -526,19 +671,39 @@ private final class ServerHTTPHandler: ChannelInboundHandler, @unchecked Sendabl
private func writeData(_ context: ChannelHandlerContext,
status: HTTPResponseStatus,
- data: Data) {
+ data: Data,
+ closeAfter: Bool = false) {
let contextBox = SendableContext(context)
context.eventLoop.execute {
var headers = HTTPHeaders()
headers.add(name: "content-type", value: "application/json")
headers.add(name: "content-length", value: "\(data.count)")
+ if closeAfter {
+ headers.add(name: "connection", value: "close")
+ }
contextBox.value.write(self.wrapOutboundOut(.head(
HTTPResponseHead(version: .http1_1, status: status, headers: headers))),
promise: nil)
var buffer = contextBox.value.channel.allocator.buffer(capacity: data.count)
buffer.writeBytes(data)
contextBox.value.write(self.wrapOutboundOut(.body(.byteBuffer(buffer))), promise: nil)
- contextBox.value.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil)
+ if closeAfter {
+ let promise = contextBox.value.eventLoop.makePromise(of: Void.self)
+ let channel = contextBox.value.channel
+ promise.futureResult.whenComplete { _ in
+ // Lingering close: an immediate close RSTs away the very
+ // response that explains the rejection while the client's
+ // remaining bytes are still in flight. The grace is a hard
+ // bound - a client that streams past it is cut off with its
+ // response undelivered, which is on the client.
+ _ = channel.eventLoop.scheduleTask(in: .seconds(2)) {
+ channel.close(promise: nil)
+ }
+ }
+ contextBox.value.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: promise)
+ } else {
+ contextBox.value.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil)
+ }
}
}
@@ -584,6 +749,27 @@ private final class ServerHTTPHandler: ChannelInboundHandler, @unchecked Sendabl
}
}
+/// The one mapping from a request rejection to its wire status. Every write
+/// site derives the status from here, so a new resource-limit code cannot
+/// return 400 at one site and 413 at another.
+private extension ServerRequestError {
+ var httpStatus: HTTPResponseStatus {
+ switch self {
+ case .unknownModel:
+ .notFound
+ case .queueFull:
+ .tooManyRequests
+ case .invalid(_, _, let code):
+ switch code {
+ case "request_too_large", "image_too_large", "too_many_images":
+ .payloadTooLarge
+ default:
+ .badRequest
+ }
+ }
+ }
+}
+
private final class ChildChannelRegistry: Sendable {
private struct State {
var channels: [ObjectIdentifier: Channel] = [:]
@@ -593,9 +779,13 @@ private final class ChildChannelRegistry: Sendable {
private let state = Mutex(State())
+ /// Registers a connection, or closes it because the server is shutting
+ /// down or already at its connection cap.
func insert(_ channel: Channel) {
let shouldClose = state.withLock {
- guard !$0.shuttingDown else { return true }
+ guard !$0.shuttingDown,
+ $0.channels.count < TurboFieldfareHTTPServer.maximumConnections
+ else { return true }
$0.channels[ObjectIdentifier(channel)] = channel
return false
}
diff --git a/Sources/TurboFieldfareServer/Core/OpenAIModels.swift b/Sources/TurboFieldfareServer/Core/OpenAIModels.swift
index 23b47a5d..0430585a 100644
--- a/Sources/TurboFieldfareServer/Core/OpenAIModels.swift
+++ b/Sources/TurboFieldfareServer/Core/OpenAIModels.swift
@@ -20,21 +20,34 @@ public struct OpenAIErrorEnvelope: Codable, Equatable, Sendable {
}
}
-public struct OpenAITextPart: Codable, Equatable, Sendable {
+public struct OpenAIImageURL: Codable, Equatable, Sendable {
+ public let url: String
+ public let detail: String?
+}
+
+public struct OpenAIContentPart: Codable, Equatable, Sendable {
public let type: String
public let text: String?
+ public let imageURL: OpenAIImageURL?
+
+ enum CodingKeys: String, CodingKey {
+ case type, text
+ case imageURL = "image_url"
+ }
}
+public typealias OpenAITextPart = OpenAIContentPart
+
public enum OpenAIMessageContent: Codable, Equatable, Sendable {
case text(String)
- case parts([OpenAITextPart])
+ case parts([OpenAIContentPart])
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let text = try? container.decode(String.self) {
self = .text(text)
} else {
- self = .parts(try container.decode([OpenAITextPart].self))
+ self = .parts(try container.decode([OpenAIContentPart].self))
}
}
@@ -46,20 +59,6 @@ public enum OpenAIMessageContent: Codable, Equatable, Sendable {
}
}
- func textValue() throws -> String {
- switch self {
- case .text(let text):
- return text
- case .parts(let parts):
- guard parts.allSatisfy({ $0.type == "text" && $0.text != nil }) else {
- throw ServerRequestError.invalid(
- message: "only text content parts are supported",
- param: "messages",
- code: "unsupported_content")
- }
- return parts.compactMap(\.text).joined()
- }
- }
}
public struct OpenAIFunctionCall: Codable, Equatable, Sendable {
@@ -213,11 +212,21 @@ public struct OpenAIModelList: Codable, Equatable, Sendable {
public let object: String
public let created: Int
public let ownedBy: String
+ public let capabilities: [String]?
enum CodingKeys: String, CodingKey {
- case id, object, created
+ case id, object, created, capabilities
case ownedBy = "owned_by"
}
+
+ public init(id: String, object: String, created: Int,
+ ownedBy: String, capabilities: [String]? = nil) {
+ self.id = id
+ self.object = object
+ self.created = created
+ self.ownedBy = ownedBy
+ self.capabilities = capabilities
+ }
}
public let object: String
@@ -245,11 +254,70 @@ public enum ServerRequestError: Error, Equatable, Sendable {
public struct ValidatedChatRequest: Sendable {
public let messages: [GFTokenizer.Message]
+ public let multimodalMessages: [MultimodalMessage]?
+ public let imageFiles: [UUID: URL]
+ /// Content SHA-256 of each message's images, in order, aligned with
+ /// `messages`. Staged image UUIDs are fresh per request, so they cannot
+ /// identify an image across turns; the content hash can. Empty for
+ /// text-only requests.
+ public let imageIdentities: [[String]]
public let tools: [GFTokenizer.FunctionDefinition]
public let stream: Bool
public let includeUsage: Bool
public let generationConfig: GenerationConfig
public let maximumCompletionTokens: Int
+ /// Every staging directory this request's image files live in. The parser
+ /// and the validator's store each stage under their own lease, and a
+ /// request may carry files from both, so dropping either would delete
+ /// files the other path staged before `generate` reads them.
+ fileprivate let attachmentLeases: [ServerAttachmentLease]
+
+ public init(
+ messages: [GFTokenizer.Message],
+ multimodalMessages: [MultimodalMessage]? = nil,
+ imageFiles: [UUID: URL] = [:],
+ imageIdentities: [[String]] = [],
+ tools: [GFTokenizer.FunctionDefinition],
+ stream: Bool,
+ includeUsage: Bool,
+ generationConfig: GenerationConfig,
+ maximumCompletionTokens: Int
+ ) {
+ self.messages = messages
+ self.multimodalMessages = multimodalMessages
+ self.imageFiles = imageFiles
+ self.imageIdentities = imageIdentities
+ self.tools = tools
+ self.stream = stream
+ self.includeUsage = includeUsage
+ self.generationConfig = generationConfig
+ self.maximumCompletionTokens = maximumCompletionTokens
+ self.attachmentLeases = []
+ }
+
+ fileprivate init(
+ messages: [GFTokenizer.Message],
+ multimodalMessages: [MultimodalMessage]?,
+ imageFiles: [UUID: URL],
+ imageIdentities: [[String]],
+ tools: [GFTokenizer.FunctionDefinition],
+ stream: Bool,
+ includeUsage: Bool,
+ generationConfig: GenerationConfig,
+ maximumCompletionTokens: Int,
+ attachmentLeases: [ServerAttachmentLease]
+ ) {
+ self.messages = messages
+ self.multimodalMessages = multimodalMessages
+ self.imageFiles = imageFiles
+ self.imageIdentities = imageIdentities
+ self.tools = tools
+ self.stream = stream
+ self.includeUsage = includeUsage
+ self.generationConfig = generationConfig
+ self.maximumCompletionTokens = maximumCompletionTokens
+ self.attachmentLeases = attachmentLeases
+ }
}
private enum OpenAIToolName {
@@ -279,6 +347,17 @@ private enum OpenAIToolName {
public enum OpenAIRequestValidator {
public static func validate(_ request: OpenAIChatRequest,
modelID: String) throws -> ValidatedChatRequest {
+ try validate(
+ request,
+ modelID: modelID,
+ preStagedImages: [:],
+ attachmentLease: nil)
+ }
+
+ static func validate(_ request: OpenAIChatRequest,
+ modelID: String,
+ preStagedImages: [String: ServerStagedImage],
+ attachmentLease: ServerAttachmentLease?) throws -> ValidatedChatRequest {
guard request.model == modelID else { throw ServerRequestError.unknownModel }
guard request.n == nil || request.n == 1 else {
throw invalid("only n=1 is supported", "n", "unsupported_value")
@@ -338,7 +417,10 @@ public enum OpenAIRequestValidator {
}
let tools = try (includeTools ? request.tools ?? [] : []).map(validateTool)
- let messages = try validateMessages(request.messages)
+ let validatedMessages = try validateMessages(
+ request.messages,
+ preStagedImages: preStagedImages,
+ attachmentLease: attachmentLease)
let config = GenerationConfig(maxNewTokens: maximum,
temperature: temperature,
topK: topK,
@@ -346,12 +428,16 @@ public enum OpenAIRequestValidator {
repetitionPenalty: repetitionPenalty,
seed: request.seed,
stopStrings: request.stop?.values ?? [])
- return ValidatedChatRequest(messages: messages,
+ return ValidatedChatRequest(messages: validatedMessages.messages,
+ multimodalMessages: validatedMessages.multimodal,
+ imageFiles: validatedMessages.imageFiles,
+ imageIdentities: validatedMessages.imageIdentities,
tools: tools,
stream: request.stream ?? false,
includeUsage: request.streamOptions?.includeUsage ?? false,
generationConfig: config,
- maximumCompletionTokens: maximum)
+ maximumCompletionTokens: maximum,
+ attachmentLeases: validatedMessages.leases)
}
private static func validateTool(_ tool: OpenAITool) throws -> GFTokenizer.FunctionDefinition {
@@ -370,9 +456,17 @@ public enum OpenAIRequestValidator {
try validateSchemaKeys(tool.function.parameters)
let parameters = try GemmaToolSchema.adapted(
tool.function.parameters, toolName: name)
- guard (try? parameters.jinjaSendableValue()) != nil else {
- throw invalid("tool schema contains a number that cannot be represented exactly",
- "tools", "invalid_tool_schema")
+ do {
+ guard (try? parameters.jinjaSendableValue()) != nil else {
+ throw invalid("tool schema contains a number that cannot be represented exactly",
+ "tools", "invalid_tool_schema")
+ }
+ } catch {
+ // Carry the underlying cause: "cannot be represented exactly" alone
+ // does not say which value, and this surfaces to a remote client.
+ throw invalid(
+ "tool schema cannot be represented exactly: \(error)",
+ "tools", "invalid_tool_schema")
}
return GFTokenizer.FunctionDefinition(name: name,
description: tool.function.description ?? "",
@@ -410,12 +504,29 @@ public enum OpenAIRequestValidator {
}
}
- private static func validateMessages(_ input: [OpenAIChatMessage]) throws -> [GFTokenizer.Message] {
+ private struct ValidatedMessages {
+ let messages: [GFTokenizer.Message]
+ let multimodal: [MultimodalMessage]?
+ let imageFiles: [UUID: URL]
+ let imageIdentities: [[String]]
+ let leases: [ServerAttachmentLease]
+ }
+
+ private static func validateMessages(
+ _ input: [OpenAIChatMessage],
+ preStagedImages: [String: ServerStagedImage],
+ attachmentLease: ServerAttachmentLease?
+ ) throws -> ValidatedMessages {
guard !input.isEmpty else {
throw invalid("messages must not be empty", "messages", "invalid_message")
}
var knownCalls: [String: (name: String, resolved: Bool)] = [:]
var result: [GFTokenizer.Message] = []
+ var multimodal: [MultimodalMessage] = []
+ var imageFiles: [UUID: URL] = [:]
+ var imageIdentities: [[String]] = []
+ var messageIdentities: [String] = []
+ var store: ServerAttachmentStore?
var sawConversationMessage = false
for message in input {
guard let role = GFTokenizer.Role(rawValue: message.role) else {
@@ -430,7 +541,67 @@ public enum OpenAIRequestValidator {
} else {
sawConversationMessage = true
}
- let content = try message.content?.textValue()
+ var orderedContent: [MultimodalContentPart] = []
+ let content: String?
+ switch message.content {
+ case nil:
+ content = nil
+ case .text(let text):
+ content = text
+ orderedContent = [.text(text)]
+ case .parts(let parts):
+ var joined = ""
+ for part in parts {
+ switch part.type {
+ case "text":
+ guard let text = part.text else {
+ throw invalid("text content part requires text",
+ "messages", "invalid_message")
+ }
+ joined += text
+ orderedContent.append(.text(text))
+ case "image_url":
+ guard role == .user else {
+ throw invalid("image_url is supported only in user messages",
+ "messages", "unsupported_content")
+ }
+ guard let image = part.imageURL else {
+ throw invalid("image_url content part requires an image_url object",
+ "messages", "invalid_message")
+ }
+ guard image.detail == nil || image.detail == "auto" else {
+ throw invalid("image detail must be absent or auto",
+ "messages", "unsupported_value")
+ }
+ let staged: ServerStagedImage
+ let prefix = "turbofieldfare-attachment:"
+ if image.url.hasPrefix(prefix) {
+ let token = String(image.url.dropFirst(prefix.count))
+ guard let existing = preStagedImages[token] else {
+ throw invalid("image attachment lease is missing",
+ "messages", "invalid_image")
+ }
+ staged = existing
+ } else {
+ if store == nil { store = try ServerAttachmentStore() }
+ staged = try store!.stage(dataURL: image.url)
+ }
+ imageFiles[staged.id] = staged.fileURL
+ messageIdentities.append(staged.sha256)
+ orderedContent.append(.image(id: staged.id))
+ default:
+ throw invalid("unsupported content part \(part.type)",
+ "messages", "unsupported_content")
+ }
+ }
+ content = joined
+ }
+ // The semantic bound on images is the context budget, checked
+ // against the model's actual context in `ServerModelSession.prepare`
+ // where the per-image token cost is known. Staging enforces its own
+ // per-file, per-request, and count resource caps; no further count
+ // check belongs here.
+
let calls: [GFTokenizer.HistoricalToolCall] = try (message.toolCalls ?? []).map { call in
guard role == .assistant, call.type == "function",
!call.id.isEmpty, knownCalls[call.id] == nil else {
@@ -447,10 +618,17 @@ public enum OpenAIRequestValidator {
throw invalid("historical tool arguments must be a JSON object",
"messages", "invalid_tool_arguments")
}
- guard (try? arguments.gemmaToolArgumentBody()) != nil,
- (try? arguments.jinjaSendableValue()) != nil else {
+ do {
+ guard (try? arguments.gemmaToolArgumentBody()) != nil,
+ (try? arguments.jinjaSendableValue()) != nil else {
+ throw invalid(
+ "historical tool arguments cannot be represented exactly",
+ "messages", "invalid_message")
+ }
+ } catch {
throw invalid(
- "historical tool arguments cannot be represented exactly",
+ "historical tool arguments cannot be represented exactly: "
+ + "\(error)",
"messages",
"invalid_tool_arguments")
}
@@ -478,8 +656,24 @@ public enum OpenAIRequestValidator {
toolCalls: calls,
toolCallID: message.toolCallID,
name: message.name))
+ if orderedContent.isEmpty, let content {
+ orderedContent = [.text(content)]
+ }
+ multimodal.append(MultimodalMessage(
+ role: role,
+ content: orderedContent,
+ toolCalls: calls,
+ toolCallID: message.toolCallID,
+ name: message.name))
+ imageIdentities.append(messageIdentities)
+ messageIdentities = []
}
- return result
+ return ValidatedMessages(
+ messages: result,
+ multimodal: imageFiles.isEmpty ? nil : multimodal,
+ imageFiles: imageFiles,
+ imageIdentities: imageFiles.isEmpty ? [] : imageIdentities,
+ leases: [attachmentLease, store?.lease].compactMap { $0 })
}
private static func invalid(_ message: String,
diff --git a/Sources/TurboFieldfareServer/Core/ServerArguments.swift b/Sources/TurboFieldfareServer/Core/ServerArguments.swift
index 574da2bd..6f21fd34 100644
--- a/Sources/TurboFieldfareServer/Core/ServerArguments.swift
+++ b/Sources/TurboFieldfareServer/Core/ServerArguments.swift
@@ -13,11 +13,16 @@ public struct ServerArguments: Equatable, Sendable {
public let prefillPolicy: RuntimePrefillPolicy
public let prefillChunkTokens: Int
public let rdadvisePolicy: RDAdvicePolicyMode
+ public let visionPack: String?
+ public let visionResidency: VisionResidencyPolicy
public static let usage = """
usage: TurboFieldfareServer --model <completed .gturbo directory> [options]
--model <dir> Required model directory.
+ --vision-pack <dir> Vision companion pack (default beside text model).
+ --vision-residency <on-demand|keep-ready>
+ Routed-expert residency during vision (default on-demand).
--port <1...65535> Loopback port (default 8080).
--model-id <id> API model identifier (default gemma-4-26b-a4b-it).
--max-context <tokens> 4096, 8192, 16384, 32768, or 65536 (default 16384).
@@ -28,7 +33,9 @@ public struct ServerArguments: Equatable, Sendable {
--expert-cache-policy <s> Expert-cache policy: lfu or lru (default lfu).
--prefill on|off Enable or disable chunked prompt prefill (default on).
Chunked prefill requires 16 or more cache slots.
- --prefill-chunk-tokens <n> Prefill chunk size: 32, 64, or 128 (default 128).
+ --prefill-chunk-tokens <n> Prefill chunk size: 32, 64, 128, or 256
+ (default 128). Each chunk re-reads the routed
+ expert pool, so larger chunks read less.
--rdadvise <s> Read-advice policy: off, default, bounded, or adaptive
(default off).
--help Show this help.
@@ -45,7 +52,10 @@ public struct ServerArguments: Equatable, Sendable {
throw ServerArgumentError.invalid("--expert-cache-slots must be 8, 16, 24, or 32")
}
guard RuntimeConfiguration.allowedPrefillChunkTokens.contains(prefillChunkTokens) else {
- throw ServerArgumentError.invalid("--prefill-chunk-tokens must be 32, 64, or 128")
+ throw ServerArgumentError.invalid(
+ "--prefill-chunk-tokens must be one of "
+ + RuntimeConfiguration.allowedPrefillChunkTokens
+ .map(String.init).joined(separator: ", "))
}
guard prefillPolicy == .off
|| expertCacheSlots >= RuntimeConfiguration.minimumExpertCacheSlotsForChunkedPrefill
@@ -69,6 +79,8 @@ public struct ServerArguments: Equatable, Sendable {
var maxContext = 16_384
var queueLimit = 4
var promptCacheMode: ServerPromptCacheMode = .singlePrefix
+ var visionPack: String?
+ var visionResidency: VisionResidencyPolicy = .onDemand
var expertCacheSlots = 16
var expertCachePolicy = RuntimeExpertCachePolicy.lfu
var prefillPolicy = RuntimePrefillPolicy.chunked
@@ -113,6 +125,14 @@ public struct ServerArguments: Equatable, Sendable {
"--prompt-cache-mode must be off or single-prefix")
}
promptCacheMode = parsed
+ case "--vision-pack":
+ visionPack = value
+ case "--vision-residency":
+ guard let parsed = VisionResidencyPolicy(rawValue: value) else {
+ throw ServerArgumentError.invalid(
+ "--vision-residency must be on-demand or keep-ready")
+ }
+ visionResidency = parsed
case "--expert-cache-slots":
guard let parsed = Int(value),
RuntimeConfiguration.allowedExpertCacheSlots.contains(parsed) else {
@@ -157,7 +177,9 @@ public struct ServerArguments: Equatable, Sendable {
expertCachePolicy: expertCachePolicy,
prefillPolicy: prefillPolicy,
prefillChunkTokens: prefillChunkTokens,
- rdadvisePolicy: rdadvisePolicy)
+ rdadvisePolicy: rdadvisePolicy,
+ visionPack: visionPack,
+ visionResidency: visionResidency)
}
}
diff --git a/Sources/TurboFieldfareServer/Core/ServerAttachmentStore.swift b/Sources/TurboFieldfareServer/Core/ServerAttachmentStore.swift
new file mode 100644
index 00000000..b7139e9f
--- /dev/null
+++ b/Sources/TurboFieldfareServer/Core/ServerAttachmentStore.swift
@@ -0,0 +1,263 @@
+import CryptoKit
+import Darwin
+import Foundation
+
+public final class ServerAttachmentLease: @unchecked Sendable {
+ let directoryURL: URL
+
+ init(directoryURL: URL) {
+ self.directoryURL = directoryURL
+ }
+
+ deinit {
+ try? FileManager.default.removeItem(at: directoryURL)
+ }
+}
+
+/// Where inline images are staged, and how directories orphaned by a crash are
+/// reclaimed.
+///
+/// A lease removes its own directory when it is released, but that only runs
+/// when the process lives long enough to release it. A crash or a `SIGKILL`
+/// mid-request leaves the staged bytes behind forever, so every run is scoped
+/// under its own `pid-<n>` directory and each start reclaims the directories
+/// whose process is gone. A live process — a second server sharing this
+/// `TMPDIR` — keeps its own directory, so the sweep never races a peer.
+public enum ServerAttachmentDirectory {
+ public static let rootName = "TurboFieldfare-Server-Attachments"
+
+ public static var root: URL {
+ FileManager.default.temporaryDirectory
+ .appendingPathComponent(rootName, isDirectory: true)
+ }
+
+ public static var processRoot: URL {
+ root.appendingPathComponent("pid-\(getpid())", isDirectory: true)
+ }
+
+ public static func makeLease(
+ in root: URL = ServerAttachmentDirectory.root
+ ) throws -> ServerAttachmentLease {
+ let directory = root
+ .appendingPathComponent("pid-\(getpid())", isDirectory: true)
+ .appendingPathComponent(UUID().uuidString, isDirectory: true)
+ try FileManager.default.createDirectory(
+ at: directory, withIntermediateDirectories: true)
+ return ServerAttachmentLease(directoryURL: directory)
+ }
+
+ /// Removes staging directories that no live process owns. Returns the names
+ /// it reclaimed so a caller can log or assert on them.
+ @discardableResult
+ public static func sweepAbandoned(
+ in root: URL = ServerAttachmentDirectory.root
+ ) -> [String] {
+ let manager = FileManager.default
+ guard let entries = try? manager.contentsOfDirectory(
+ at: root, includingPropertiesForKeys: nil) else { return [] }
+ var reclaimed: [String] = []
+ for entry in entries {
+ let name = entry.lastPathComponent
+ if let pid = ownerProcess(of: name), isAlive(pid) { continue }
+ guard (try? manager.removeItem(at: entry)) != nil else { continue }
+ reclaimed.append(name)
+ }
+ return reclaimed
+ }
+
+ private static func ownerProcess(of name: String) -> pid_t? {
+ guard name.hasPrefix("pid-"), let value = pid_t(name.dropFirst(4)),
+ value > 0 else { return nil }
+ return value
+ }
+
+ private static func isAlive(_ pid: pid_t) -> Bool {
+ // EPERM means the process exists but belongs to another user; only
+ // ESRCH proves it is gone.
+ kill(pid, 0) == 0 || errno == EPERM
+ }
+}
+
+struct ServerStagedImage: Sendable {
+ let id: UUID
+ let fileURL: URL
+ let encodedBytes: Int
+ let sha256: String
+}
+
+struct ServerAttachmentStore {
+ static let maximumImageBytes = 16 * 1_024 * 1_024
+ static let maximumRequestImageBytes = 64 * 1_024 * 1_024
+ /// Staging happens before the context budget can reject anything, so the
+ /// byte caps alone leave the file count unbounded: each image costs about
+ /// 105 JSON bytes, so 5 MiB of body can create tens of thousands of temp
+ /// files and stall the single event loop for seconds.
+ static let maximumRequestImages = 64
+ static let allowedDataURLHeaders: Set<String> = [
+ "data:image/jpeg;base64",
+ "data:image/png;base64",
+ "data:image/heic;base64",
+ "data:image/heif;base64",
+ ]
+
+ let lease: ServerAttachmentLease
+ private(set) var decodedBytes = 0
+ private(set) var stagedCount = 0
+
+ init(attachmentRoot: URL = ServerAttachmentDirectory.root) throws {
+ lease = try ServerAttachmentDirectory.makeLease(in: attachmentRoot)
+ }
+
+ /// Stages a data URL that reached the validator directly. Wire requests
+ /// never take this path — the streaming parser stages every acceptable
+ /// message image before the validator runs — so this exists for callers
+ /// of `OpenAIRequestValidator.validate` outside the HTTP server. The
+ /// policy pieces (allowlist, caps, writer) are shared with the parser so
+ /// the two entries cannot drift.
+ mutating func stage(dataURL: String) throws -> ServerStagedImage {
+ guard stagedCount < Self.maximumRequestImages else {
+ throw ServerRequestError.invalid(
+ message: "at most \(Self.maximumRequestImages) images per request",
+ param: "messages", code: "too_many_images")
+ }
+ guard let comma = dataURL.firstIndex(of: ",") else {
+ throw ServerRequestError.invalid(
+ message: "image_url must be a base64 data URL",
+ param: "messages", code: "invalid_image_url")
+ }
+ let header = String(dataURL[..<comma]).lowercased()
+ guard Self.allowedDataURLHeaders.contains(header) else {
+ throw ServerRequestError.invalid(
+ message: "image_url must be a JPEG, PNG, HEIC, or HEIF base64 data URL",
+ param: "messages", code: "unsupported_image")
+ }
+ let payload = dataURL[dataURL.index(after: comma)...].utf8
+ let writer = try StreamingBase64FileWriter(directoryURL: lease.directoryURL)
+ // Bounded spans, not the whole payload at once: the writer's pending
+ // buffer grows by what one feed hands it before it can flush.
+ let span = 64 * 1_024
+ let fed: Void? = try payload.withContiguousStorageIfAvailable { buffer in
+ var index = 0
+ while index < buffer.count {
+ let end = min(index + span, buffer.count)
+ try writer.feed(
+ contentsOf: UnsafeBufferPointer(rebasing: buffer[index..<end]))
+ index = end
+ }
+ }
+ if fed == nil {
+ var chunk: [UInt8] = []
+ chunk.reserveCapacity(span)
+ for byte in payload {
+ chunk.append(byte)
+ if chunk.count == span {
+ try writer.feed(contentsOf: chunk)
+ chunk.removeAll(keepingCapacity: true)
+ }
+ }
+ try writer.feed(contentsOf: chunk)
+ }
+ let staged = try writer.finish()
+ guard decodedBytes + staged.encodedBytes <= Self.maximumRequestImageBytes else {
+ try? FileManager.default.removeItem(at: staged.fileURL)
+ throw ServerRequestError.invalid(
+ message: "inline image bytes exceed the server limit",
+ param: "messages", code: "image_too_large")
+ }
+ decodedBytes += staged.encodedBytes
+ stagedCount += 1
+ return staged
+ }
+}
+
+final class StreamingBase64FileWriter {
+ private let id = UUID()
+ private let fileURL: URL
+ private let handle: FileHandle
+ private var pending: [UInt8] = []
+ private var hasher = SHA256()
+ private var decodedBytes = 0
+ /// Padding may only terminate the payload. Enforcing that here makes the
+ /// stream's validity independent of where flush boundaries fall: without
+ /// it, mid-stream padding decodes or fails depending on how the wire
+ /// happened to chunk the same bytes.
+ private var paddingBytes = 0
+ private var finished = false
+
+ init(directoryURL: URL) throws {
+ fileURL = directoryURL.appendingPathComponent(id.uuidString)
+ FileManager.default.createFile(
+ atPath: fileURL.path,
+ contents: nil,
+ attributes: [.posixPermissions: 0o600])
+ handle = try FileHandle(forWritingTo: fileURL)
+ pending.reserveCapacity(64 * 1_024)
+ }
+
+ deinit {
+ if !finished {
+ try? handle.close()
+ try? FileManager.default.removeItem(at: fileURL)
+ }
+ }
+
+ func feed(contentsOf bytes: some Sequence<UInt8>) throws {
+ for byte in bytes {
+ let padded = byte == UInt8(ascii: "=")
+ if padded { paddingBytes += 1 }
+ guard Self.isBase64(byte), paddingBytes <= 2,
+ padded || paddingBytes == 0 else {
+ throw ServerRequestError.invalid(
+ message: "image_url contains invalid base64",
+ param: "messages", code: "invalid_image")
+ }
+ }
+ pending.append(contentsOf: bytes)
+ if pending.count >= 64 * 1_024 { try flush(final: false) }
+ }
+
+ func finish() throws -> ServerStagedImage {
+ try flush(final: true)
+ try handle.close()
+ guard decodedBytes > 0, chmod(fileURL.path, S_IRUSR) == 0 else {
+ throw ServerRequestError.invalid(
+ message: "image_url contains no image bytes",
+ param: "messages", code: "invalid_image")
+ }
+ finished = true
+ return ServerStagedImage(
+ id: id,
+ fileURL: fileURL,
+ encodedBytes: decodedBytes,
+ sha256: hasher.finalize().map { String(format: "%02x", $0) }.joined())
+ }
+
+ private static func isBase64(_ byte: UInt8) -> Bool {
+ (65...90).contains(byte) || (97...122).contains(byte)
+ || (48...57).contains(byte) || byte == 43 || byte == 47 || byte == 61
+ }
+
+ private func flush(final: Bool) throws {
+ let count = final ? pending.count : pending.count - pending.count % 4
+ guard count > 0 else { return }
+ if final, count % 4 != 0 {
+ throw ServerRequestError.invalid(
+ message: "image_url contains invalid base64",
+ param: "messages", code: "invalid_image")
+ }
+ guard let decoded = Data(base64Encoded: Data(pending.prefix(count))) else {
+ throw ServerRequestError.invalid(
+ message: "image_url contains invalid base64",
+ param: "messages", code: "invalid_image")
+ }
+ decodedBytes += decoded.count
+ guard decodedBytes <= ServerAttachmentStore.maximumImageBytes else {
+ throw ServerRequestError.invalid(
+ message: "inline image bytes exceed the server limit",
+ param: "messages", code: "image_too_large")
+ }
+ try handle.write(contentsOf: decoded)
+ hasher.update(data: decoded)
+ pending.removeFirst(count)
+ }
+}
diff --git a/Sources/TurboFieldfareServer/Core/ServerImageTokenBudget.swift b/Sources/TurboFieldfareServer/Core/ServerImageTokenBudget.swift
new file mode 100644
index 00000000..27d17212
--- /dev/null
+++ b/Sources/TurboFieldfareServer/Core/ServerImageTokenBudget.swift
@@ -0,0 +1,45 @@
+import Foundation
+import TurboFieldfare
+
+/// The server's face of `VisionImageTokenBudget`: the shared arithmetic plus
+/// the OpenAI-shaped rejection. The rule itself lives in the runtime so the
+/// app and CLI cannot drift from it.
+enum ServerImageTokenBudget {
+ /// A rendered image placeholder becomes one BOI marker, the projected image
+ /// tokens, and one EOI marker.
+ static func imageTokens(softTokenCounts: [Int]) -> Int {
+ VisionImageTokenBudget.imageTokens(softTokenCounts: softTokenCounts)
+ }
+
+ /// Only the prompt is required to fit. The requested reply is deliberately
+ /// not counted: the text path clamps `max_tokens` to the remaining context
+ /// rather than refusing, and clients routinely ask for the whole context —
+ /// pinned Pi 0.82.1 sends `max_tokens: 16384`, the entire default
+ /// 16,384-token context, on every request. Counting it here rejected
+ /// requests the text path would have served.
+ static func fits(
+ softTokenCounts: [Int],
+ textTokens: Int,
+ maxContext: Int
+ ) -> Bool {
+ VisionImageTokenBudget.fits(
+ softTokenCounts: softTokenCounts,
+ textTokens: textTokens,
+ maxContext: maxContext)
+ }
+
+ static func rejection(
+ imageCount: Int,
+ softTokenCounts: [Int],
+ textTokens: Int,
+ maxContext: Int
+ ) -> ServerRequestError {
+ let images = imageTokens(softTokenCounts: softTokenCounts)
+ return ServerRequestError.invalid(
+ message: "\(imageCount) image(s) need \(images) tokens; with "
+ + "\(textTokens) text tokens that exceeds the "
+ + "\(maxContext)-token context",
+ param: "messages",
+ code: "context_length_exceeded")
+ }
+}
diff --git a/Sources/TurboFieldfareServer/Core/ServerInference.swift b/Sources/TurboFieldfareServer/Core/ServerInference.swift
index b96543ca..5dda235f 100644
--- a/Sources/TurboFieldfareServer/Core/ServerInference.swift
+++ b/Sources/TurboFieldfareServer/Core/ServerInference.swift
@@ -231,6 +231,7 @@ struct StructuredOutputFailureDiagnostics: Equatable, Sendable {
case .endOfTurn: "end_of_turn"
case .maxTokens: "max_tokens"
case .stopString: "stop_string"
+ case .cancelled: "cancelled"
case .toolCalls: "tool_calls"
}
}
@@ -374,6 +375,107 @@ public actor ServerCoordinator {
public var isActive: Bool { active }
}
+/// How the server reads the images of a request: one plan per image, and the
+/// encode reads the plan the count came from.
+///
+/// Planning opens the file, sniffs it, parses its metadata and — for a JPEG —
+/// walks its markers. Counting with a plan and then letting `encodeImage(at:)`
+/// re-plan internally did all of that a second time per image, and the two
+/// opens saw two files: one rewritten in between produced a count the laid-out
+/// span no longer matched, and the turn died on `placeholderMismatch` naming
+/// nothing the client did.
+///
+/// Both multimodal paths go through here so the pattern has one implementation
+/// to keep correct rather than one per path.
+enum ServerRequestImages {
+ /// An image planned once: the count that lays out its placeholder span,
+ /// and — while the plan behind that count is still open — the bytes the
+ /// count was taken from.
+ struct Planned {
+ let url: URL
+ let softTokenCount: Int
+ let plan: VisionImagePlan?
+ }
+
+ /// How many of a request's images keep their plan open at once.
+ ///
+ /// A plan owns the descriptor its ImageIO source reads through, and what
+ /// bounds a request's image count is the context budget alone — an
+ /// 8,192-token context admits some 2,700 single-token images. One
+ /// descriptor each would exhaust the process table and take the listening
+ /// socket down with it, so past this many the plan is released after
+ /// counting and remade at encode time. Real requests carry a handful of
+ /// images and never reach it.
+ static let maximumOpenPlans = 32
+
+ /// Plans every image before any of them is encoded.
+ ///
+ /// Two reasons for the order: the counts that lay out the placeholder spans
+ /// then come from the same open files the encodes read, and a request whose
+ /// last image cannot be read at all is refused before the tower has run on
+ /// the images ahead of it.
+ static func plans(
+ for urls: [URL],
+ with preprocessor: Gemma4ImagePreprocessor,
+ maximumOpenPlans: Int = ServerRequestImages.maximumOpenPlans,
+ checkCancellation: () throws -> Void = {}
+ ) throws -> [Planned] {
+ var planned: [Planned] = []
+ planned.reserveCapacity(urls.count)
+ for url in urls {
+ // Planning a JPEG walks its whole scan, so an abandoned request
+ // stops at the next image rather than reading all of them first.
+ try checkCancellation()
+ let plan = try preprocessor.plan(fileURL: url)
+ planned.append(Planned(
+ url: url,
+ softTokenCount: plan.geometry.softTokenCount,
+ plan: planned.count < maximumOpenPlans ? plan : nil))
+ }
+ return planned
+ }
+
+ /// Encodes an image from the plan its count was taken from. Only an image
+ /// whose plan the open bound released is read a second time.
+ static func encode<Features>(
+ _ image: Planned,
+ fromPlan: (VisionImagePlan) throws -> Features,
+ byReopening: (URL) throws -> Features
+ ) throws -> Features {
+ guard let plan = image.plan else { return try byReopening(image.url) }
+ return try fromPlan(plan)
+ }
+
+ /// Every image a full prefill needs, each read through one open file.
+ ///
+ /// A full prefill lays its spans out from the encoded features rather than
+ /// from a count, so it asked for no plan of its own and let
+ /// `encodeImage(at:)` make one per image internally — the third copy of the
+ /// pattern, and the one that also encoded its way through the images ahead
+ /// of one that could not be read at all.
+ static func encodeAll<Features>(
+ _ imageFiles: [UUID: URL],
+ with preprocessor: Gemma4ImagePreprocessor,
+ maximumOpenPlans: Int = ServerRequestImages.maximumOpenPlans,
+ checkCancellation: () throws -> Void = {},
+ encode: (Planned) throws -> Features
+ ) throws -> [UUID: Features] {
+ let entries = Array(imageFiles)
+ let planned = try plans(
+ for: entries.map { $0.value },
+ with: preprocessor,
+ maximumOpenPlans: maximumOpenPlans,
+ checkCancellation: checkCancellation)
+ var features: [UUID: Features] = [:]
+ features.reserveCapacity(entries.count)
+ for (entry, image) in zip(entries, planned) {
+ try checkCancellation()
+ features[entry.key] = try encode(image)
+ }
+ return features
+ }
+}
+
public actor ServerModelSession: ServerInferenceBackend {
private let context: MetalContext
private let model: Model
@@ -385,9 +487,39 @@ public actor ServerModelSession: ServerInferenceBackend {
private let promptCacheMode: ServerPromptCacheMode
private let promptCacheDomain: ServerPromptCacheDomain
private var promptCache = ServerPromptCache()
+ public nonisolated let visionCapability: String
+ private let visionRuntime: VisionRuntime?
+ private let visionResidencyPolicy: VisionResidencyPolicy
+
+ /// What the cached KV was actually produced by. Six configuration fields
+ /// plus every `TURBO_FIELDFARE_*` variable in the environment: those select
+ /// kernels - about nineteen vision switches alone - and one of them set to
+ /// `0` silently picks a different attention path. Leaving them out meant a
+ /// prefix built by one kernel set could be reused under another, with
+ /// nothing recording that anything had changed.
+ static func runtimeIdentityString(
+ runtime: RuntimeConfiguration,
+ environment: [String: String] = ProcessInfo.processInfo.environment
+ ) -> String {
+ let configuration = [
+ String(runtime.expertCacheSlots),
+ runtime.expertCachePolicy.rawValue,
+ runtime.rdadvisePolicy.rawValue,
+ runtime.prefillPolicy.rawValue,
+ String(runtime.prefillChunkTokens),
+ runtime.headPath.rawValue,
+ ]
+ let switches = environment
+ .filter { $0.key.hasPrefix("TURBO_FIELDFARE_") }
+ .map { "\($0.key)=\($0.value)" }
+ .sorted()
+ return (configuration + switches).joined(separator: ":")
+ }
public static func load(modelDirectory: URL,
maxContext: Int,
+ visionPackURL: URL? = nil,
+ visionResidencyPolicy: VisionResidencyPolicy = .onDemand,
promptCacheMode: ServerPromptCacheMode = .singlePrefix,
runtimeConfiguration: RuntimeConfiguration) async throws -> ServerModelSession {
let tokenizerFolder = GFTokenizer.tokenizerFolder(forModelDirectory: modelDirectory)
@@ -415,14 +547,7 @@ public actor ServerModelSession: ServerInferenceBackend {
let templateDigest = SHA256.hash(data: try Data(contentsOf: templateURL))
.map { String(format: "%02x", $0) }
.joined()
- let runtimeIdentity = [
- String(runtime.expertCacheSlots),
- runtime.expertCachePolicy.rawValue,
- runtime.rdadvisePolicy.rawValue,
- runtime.prefillPolicy.rawValue,
- String(runtime.prefillChunkTokens),
- runtime.headPath.rawValue,
- ].joined(separator: ":")
+ let runtimeIdentity = Self.runtimeIdentityString(runtime: runtime)
let runtimeDigest = SHA256.hash(data: Data(runtimeIdentity.utf8))
.map { String(format: "%02x", $0) }
.joined()
@@ -434,6 +559,47 @@ public actor ServerModelSession: ServerInferenceBackend {
kvStorage: PrefillKVStorageMode.fp16.rawValue,
fp16RingEnabled: runtime.fp16RingEnabled,
templateSHA256: templateDigest)
+ let visionRuntime: VisionRuntime?
+ let visionCapability: String
+ // An explicit pack path is an operator's statement that the pack is
+ // there; a typo must fail loudly at startup, not serve text with vision
+ // silently missing.
+ if let visionPackURL,
+ !FileManager.default.fileExists(atPath: visionPackURL.path) {
+ throw VisionPackError.packNotFound(visionPackURL.path)
+ }
+ // A model directory without the .gturbo suffix has no companion
+ // location; that only means vision is missing, never that a
+ // text-serving load must fail.
+ let resolvedVisionPackURL = visionPackURL
+ ?? (try? VisionPackLocation.companionURL(forTextModel: modelDirectory))
+ if let hardwareCapability = Self.hardwareVisionCapability(
+ supportsVisionRuntime: VisionRuntime.isSupported(on: context.device)) {
+ visionRuntime = nil
+ visionCapability = hardwareCapability
+ ServerLog.visionRuntimeUnsupported()
+ } else if let resolvedVisionPackURL,
+ FileManager.default.fileExists(atPath: resolvedVisionPackURL.path) {
+ do {
+ visionRuntime = try VisionRuntime.open(
+ textModelURL: modelDirectory,
+ context: context,
+ visionPackURL: resolvedVisionPackURL)
+ visionCapability = "ready"
+ } catch {
+ visionRuntime = nil
+ visionCapability = Self.unavailableVisionCapability(for: error)
+ if visionCapability == "unsupported" {
+ ServerLog.visionRuntimeUnsupported(
+ at: resolvedVisionPackURL, error: error)
+ } else {
+ ServerLog.visionPackInvalid(at: resolvedVisionPackURL, error: error)
+ }
+ }
+ } else {
+ visionRuntime = nil
+ visionCapability = "missing"
+ }
return ServerModelSession(context: context,
model: model,
tokenizer: tokenizer,
@@ -442,7 +608,26 @@ public actor ServerModelSession: ServerInferenceBackend {
prefillConfig: runtime.prefillConfig,
maxContext: maxContext,
promptCacheMode: promptCacheMode,
- promptCacheDomain: promptCacheDomain)
+ promptCacheDomain: promptCacheDomain,
+ visionRuntime: visionRuntime,
+ visionCapability: visionCapability,
+ visionResidencyPolicy: visionResidencyPolicy)
+ }
+
+ static func hardwareVisionCapability(
+ supportsVisionRuntime: Bool
+ ) -> String? {
+ supportsVisionRuntime ? nil : "unsupported"
+ }
+
+ static func unavailableVisionCapability(for error: Error) -> String {
+ guard let runtimeError = error as? VisionRuntimeError else {
+ return "invalid"
+ }
+ if case .unsupportedKernel = runtimeError {
+ return "unsupported"
+ }
+ return "invalid"
}
private init(context: MetalContext,
@@ -453,7 +638,10 @@ public actor ServerModelSession: ServerInferenceBackend {
prefillConfig: PrefillRuntimeConfig,
maxContext: Int,
promptCacheMode: ServerPromptCacheMode,
- promptCacheDomain: ServerPromptCacheDomain) {
+ promptCacheDomain: ServerPromptCacheDomain,
+ visionRuntime: VisionRuntime?,
+ visionCapability: String,
+ visionResidencyPolicy: VisionResidencyPolicy) {
self.context = context
self.model = model
self.tokenizer = tokenizer
@@ -463,6 +651,9 @@ public actor ServerModelSession: ServerInferenceBackend {
self.maxContext = maxContext
self.promptCacheMode = promptCacheMode
self.promptCacheDomain = promptCacheDomain
+ self.visionRuntime = visionRuntime
+ self.visionResidencyPolicy = visionResidencyPolicy
+ self.visionCapability = visionCapability
}
public func generate(
@@ -474,7 +665,183 @@ public actor ServerModelSession: ServerInferenceBackend {
}
public func prepare(_ request: ValidatedChatRequest) async throws -> ServerPreparedRequest {
- ServerPreparedRequest(request: request, promptIDs: try renderPrompt(request))
+ if !request.imageFiles.isEmpty {
+ let softTokens = try imageSoftTokenCounts(request)
+ try validateImageTokenBudget(request, softTokens: softTokens)
+ }
+ return ServerPreparedRequest(
+ request: request,
+ promptIDs: request.multimodalMessages == nil ? try renderPrompt(request) : nil)
+ }
+
+ private func imagePreprocessor(_ visionRuntime: VisionRuntime) -> Gemma4ImagePreprocessor {
+ Gemma4ImagePreprocessor(device: context.device, config: visionRuntime.config)
+ }
+
+ /// The encode side of a planned image, bound to this session's runtime.
+ private func encodeTurnImage(
+ _ image: ServerRequestImages.Planned, visionRuntime: VisionRuntime
+ ) throws -> VisionFeatures {
+ try ServerRequestImages.encode(
+ image,
+ fromPlan: {
+ try visionRuntime.encodeImage(
+ plan: $0,
+ languageModel: model,
+ residencyPolicy: visionResidencyPolicy,
+ checkCancellation: { try Task.checkCancellation() })
+ },
+ byReopening: {
+ try visionRuntime.encodeImage(
+ at: $0,
+ languageModel: model,
+ residencyPolicy: visionResidencyPolicy,
+ checkCancellation: { try Task.checkCancellation() })
+ })
+ }
+
+ /// Projected token count per image from headers alone; no pixel is decoded
+ /// and no scan is walked.
+ private func imageSoftTokenCounts(
+ _ request: ValidatedChatRequest
+ ) throws -> [Int] {
+ guard let visionRuntime else {
+ throw ServerRequestError.invalid(
+ message: "image support is unavailable",
+ param: "messages", code: "vision_unavailable")
+ }
+ let preprocessor = imagePreprocessor(visionRuntime)
+ var counts: [Int] = []
+ counts.reserveCapacity(request.imageFiles.count)
+ for url in request.imageFiles.values {
+ do {
+ let geometry = try preprocessor.admissionGeometry(fileURL: url)
+ counts.append(geometry.softTokenCount)
+ } catch let error as ServerRequestError {
+ throw error
+ } catch {
+ throw ServerRequestError.invalid(
+ message: "image could not be read: \(error)",
+ param: "messages", code: "invalid_image")
+ }
+ }
+ return counts
+ }
+
+ /// Rejects an image request that cannot fit the context before any pixel is
+ /// decoded or any tower runs.
+ private func validateImageTokenBudget(
+ _ request: ValidatedChatRequest, softTokens: [Int]
+ ) throws {
+ let textTokens = try renderPrompt(request).count
+ guard ServerImageTokenBudget.fits(
+ softTokenCounts: softTokens,
+ textTokens: textTokens,
+ maxContext: maxContext) else {
+ throw ServerImageTokenBudget.rejection(
+ imageCount: request.imageFiles.count,
+ softTokenCounts: softTokens,
+ textTokens: textTokens,
+ maxContext: maxContext)
+ }
+ }
+
+ /// The trailing user turn rendered as a continuation, with only its own
+ /// images encoded. Token counts come from geometry, so the turn's shape is
+ /// known before any encode.
+ private func multimodalContinuation(
+ request: ValidatedChatRequest,
+ cachedMessageCount: Int
+ ) async throws -> MultimodalPrefillInput {
+ guard let messages = request.multimodalMessages, let visionRuntime,
+ messages.count == cachedMessageCount + 2,
+ let turn = messages.last, turn.role == .user,
+ turn.toolCalls.isEmpty, turn.toolCallID == nil else {
+ throw MultimodalPromptRendererError.placeholderMismatch
+ }
+ var parts: [MultimodalContinuationPart] = []
+ var urls: [URL] = []
+ for part in turn.content {
+ switch part {
+ case .text(let value):
+ parts.append(.text(value))
+ case .image(let id):
+ guard let url = request.imageFiles[id] else {
+ throw MultimodalPromptRendererError.missingImage(id)
+ }
+ parts.append(.image)
+ urls.append(url)
+ }
+ }
+ let images = try ServerRequestImages.plans(
+ for: urls,
+ with: imagePreprocessor(visionRuntime),
+ checkCancellation: { try Task.checkCancellation() })
+ let bridge = try tokenizer.encodeMultimodalUserContinuation(
+ textAndImages: parts, imageTokenCounts: images.map(\.softTokenCount))
+ var spans: [MultimodalImageSpan] = []
+ for (range, image) in zip(bridge.imageTokenRanges, images) {
+ try Task.checkCancellation()
+ let features = try encodeTurnImage(image, visionRuntime: visionRuntime)
+ guard features.tokenCount == range.count else {
+ // Geometry disagreed with the encode; refuse rather than inject
+ // a span of the wrong length.
+ throw MultimodalPromptRendererError.placeholderMismatch
+ }
+ spans.append(MultimodalImageSpan(tokenRange: range, features: features))
+ }
+ return try MultimodalPrefillInput(
+ effectiveTokenIDs: bridge.effectiveTokenIDs,
+ embeddingTokenIDs: bridge.embeddingTokenIDs,
+ imageSpans: spans)
+ }
+
+ private func renderMultimodal(
+ _ request: ValidatedChatRequest
+ ) async throws -> MultimodalPrefillInput {
+ guard let messages = request.multimodalMessages, let visionRuntime else {
+ throw ServerRequestError.invalid(
+ message: "image support is unavailable",
+ param: "messages", code: "vision_unavailable")
+ }
+ do {
+ let features = try ServerRequestImages.encodeAll(
+ request.imageFiles,
+ with: imagePreprocessor(visionRuntime),
+ checkCancellation: { try Task.checkCancellation() },
+ encode: { try encodeTurnImage($0, visionRuntime: visionRuntime) })
+ return try MultimodalPromptRenderer.render(
+ messages: messages,
+ featuresByID: features,
+ tokenizer: tokenizer,
+ tools: request.tools)
+ } catch let error as MultimodalPromptRendererError {
+ throw Self.clientError(for: error) ?? error
+ }
+ }
+
+ /// Renderer failures a client can cause with its own message content are
+ /// request rejections, not server errors; the rest stay opaque and surface
+ /// as 500s because they mean the server's own layout went wrong.
+ private static func clientError(
+ for error: MultimodalPromptRendererError
+ ) -> ServerRequestError? {
+ switch error {
+ case .reservedImageMarker:
+ .invalid(
+ message: "message text contains a reserved image placeholder token",
+ param: "messages", code: "invalid_message")
+ case .placeholderMismatch:
+ .invalid(
+ message: "message content could not be aligned with its images",
+ param: "messages", code: "invalid_message")
+ case .emptyMessages, .emptyContent:
+ .invalid(
+ message: "multimodal messages must not be empty",
+ param: "messages", code: "invalid_message")
+ case .missingImage, .unexpectedImage:
+ nil
+ }
}
public func generate(
@@ -482,37 +849,90 @@ public actor ServerModelSession: ServerInferenceBackend {
onEvent: @escaping @Sendable (ServerInferenceEvent) -> Void
) async throws -> ServerCompletion {
let request = prepared.request
+ var completionStarted = false
var completed = false
defer {
- if !completed {
+ // Rendering, planning and image encoding touch no KV state, so a
+ // request that fails or is cancelled before the completion starts
+ // leaves the cache exactly as the last completed request left it.
+ // Image encoding is seconds long, so this window is not rare.
+ if completionStarted, !completed {
promptCache.invalidate()
runner.reset()
}
}
let needsToolTemplate = usesToolTemplate(request)
- let promptIDs = try prepared.promptIDs ?? renderPrompt(request)
+ let isMultimodal = request.multimodalMessages != nil
+ if isMultimodal, visionRuntime == nil {
+ throw ServerRequestError.invalid(
+ message: "image support is unavailable",
+ param: "messages", code: "vision_unavailable")
+ }
- let effectivePromptIDs: [Int32]
- let completionStart: RawCompletionStart
+ // Matched before any image is encoded. A multimodal hit continues from
+ // the cached KV, so the images already inside that prefix are never
+ // re-encoded; only a full-prefill miss needs them.
+ let renderedTextIDs: [Int32]? = isMultimodal
+ ? nil : try (prepared.promptIDs ?? renderPrompt(request))
+ var cacheMatch: ServerPromptCacheMatch = .miss
if promptCacheMode == .singlePrefix {
- switch promptCache.match(
+ cacheMatch = promptCache.match(
domain: promptCacheDomain,
request: request,
- renderedPromptIDs: promptIDs,
- tokenizer: tokenizer) {
- case .miss:
+ renderedPromptIDs: renderedTextIDs,
+ tokenizer: tokenizer)
+ }
+ let effectivePromptIDs: [Int32]
+ let completionStart: RawCompletionStart
+ var multimodalInput: MultimodalPrefillInput?
+ switch cacheMatch {
+ case .hit(let effective, let cached):
+ effectivePromptIDs = effective
+ completionStart = .resume(cachedPromptTokens: cached)
+ multimodalInput = nil
+ case .renderThenResume(let cached):
+ // Build the new turn as a continuation on the cached KV rather than
+ // re-rendering history: the KV holds tokens the model generated, and
+ // a fresh render re-tokenises that assistant text, so the two cannot
+ // be compared. Only this turn's images are encoded.
+ do {
+ let bridge = try await multimodalContinuation(
+ request: request,
+ cachedMessageCount: promptCache.inputMessageCount ?? 0)
+ effectivePromptIDs = (promptCache.kvBackedTokenIDs ?? [])
+ + bridge.effectiveTokenIDs
+ multimodalInput = bridge
+ completionStart = .resume(cachedPromptTokens: cached)
+ } catch is CancellationError {
+ // A disconnect mid-plan or mid-encode is not a bridge failure:
+ // the cached prefix is untouched and stays valid for the retry.
+ throw CancellationError()
+ } catch {
+ ServerLog.promptCacheBridgeFailed(error: error)
promptCache.invalidate()
- effectivePromptIDs = promptIDs
+ let rendered = try await renderMultimodal(request)
+ effectivePromptIDs = rendered.effectiveTokenIDs
+ multimodalInput = rendered
completionStart = .reset
- case .hit(let effective, let cached):
- effectivePromptIDs = effective
- completionStart = .resume(cachedPromptTokens: cached)
}
- } else {
+ case .miss:
promptCache.invalidate()
- effectivePromptIDs = promptIDs
+ if let renderedTextIDs {
+ effectivePromptIDs = renderedTextIDs
+ multimodalInput = nil
+ } else {
+ let rendered = try await renderMultimodal(request)
+ effectivePromptIDs = rendered.effectiveTokenIDs
+ multimodalInput = rendered
+ }
completionStart = .reset
}
+ // What the template renders versus what actually prefills: on a text
+ // cache hit the two genuinely differ, and that difference is the point
+ // of the rendered/effective split in the failure diagnostics. A
+ // multimodal resume has no full render to compare against, so the
+ // effective ids stand in.
+ let renderedPromptIDs = renderedTextIDs ?? effectivePromptIDs
guard effectivePromptIDs.count < maxContext else {
throw ServerRequestError.invalid(
message: "effective prompt exceeds the configured context",
@@ -537,10 +957,12 @@ public actor ServerModelSession: ServerInferenceBackend {
var decodingError: Error?
var shouldStop = false
+ completionStarted = true
let result = try await runRawCompletion(
producer: runner,
tokenizer: tokenizer,
promptIds: effectivePromptIDs,
+ multimodalInput: multimodalInput,
config: config,
context: context,
scratch: scratch,
@@ -600,7 +1022,7 @@ public actor ServerModelSession: ServerInferenceBackend {
kind: kind,
cause: cause,
diagnostics: StructuredOutputFailureDiagnostics(
- renderedPromptIDs: promptIDs,
+ renderedPromptIDs: renderedPromptIDs ?? effectivePromptIDs,
effectivePromptIDs: effectivePromptIDs,
result: result,
maxCompletionTokens: config.maxNewTokens,
@@ -640,6 +1062,10 @@ public actor ServerModelSession: ServerInferenceBackend {
} else {
reason = "stop"
}
+ // Publishing an image turn is safe now that the entry carries per-message
+ // image identity: a later turn whose images differ is refused by
+ // `imagesDiverged` rather than resumed onto a KV built from a different
+ // picture.
if promptCacheMode == .singlePrefix {
promptCache.publish(
domain: promptCacheDomain,
diff --git a/Sources/TurboFieldfareServer/Core/ServerLog.swift b/Sources/TurboFieldfareServer/Core/ServerLog.swift
index c29fdcb4..3e6d41eb 100644
--- a/Sources/TurboFieldfareServer/Core/ServerLog.swift
+++ b/Sources/TurboFieldfareServer/Core/ServerLog.swift
@@ -29,6 +29,47 @@ enum ServerLog {
+ "finish=\(completion.finishReason)")
}
+ /// The session is an actor, so generation is serialized: this line always
+ /// belongs to the request between the preceding `generating` and the
+ /// following `completed`. Carries a reason code only, never prompt content.
+
+ static func visionPackInvalid(at url: URL, error: Error) {
+ write("vision pack at \(url.path) is invalid: \(String(reflecting: error))")
+ }
+
+ static func visionRuntimeUnsupported(at url: URL, error: Error) {
+ write("vision runtime for pack at \(url.path) is unsupported: "
+ + String(reflecting: error))
+ }
+
+ static func visionRuntimeUnsupported() {
+ write("vision runtime is unsupported: the image tower requires an M2 or newer Mac")
+ }
+
+ /// A prefix that could not be continued because its bridge failed to
+ /// render. Carries the underlying error, because this miss means the
+ /// template and the cached turn disagree, which no other miss does.
+ static func promptCacheBridgeFailed(error: Error) {
+ write("prompt cache miss reason=bridge-render-failed "
+ + "error=\(String(reflecting: error))")
+ }
+
+ /// A request whose client stopped listening. Kept distinct from `failed`
+ /// because a cancel is not a server fault and should not read as one, and
+ /// added because excluding it from logging altogether left the request's last
+ /// line as `generating` forever: an operator could not tell a running request
+ /// from an abandoned one, or from a crashed one. Carries no content.
+ static func cancelled(id: String, phase: String, duration: Duration) {
+ write(cancelledMessage(id: id, phase: phase, duration: duration))
+ }
+
+ /// Split out so the wording can be checked without a log sink: this line
+ /// must stay distinguishable from `failed`, must name the phase, and must
+ /// carry no prompt or generated content.
+ static func cancelledMessage(id: String, phase: String, duration: Duration) -> String {
+ "request \(id) cancelled by client in \(format(duration)) phase=\(phase)"
+ }
+
static func failed(id: String,
phase: String,
status: UInt,
diff --git a/Sources/TurboFieldfareServer/Core/ServerPromptCache.swift b/Sources/TurboFieldfareServer/Core/ServerPromptCache.swift
index 70af208d..c5cc8f10 100644
--- a/Sources/TurboFieldfareServer/Core/ServerPromptCache.swift
+++ b/Sources/TurboFieldfareServer/Core/ServerPromptCache.swift
@@ -24,6 +24,11 @@ struct CachedAssistantTurn: Sendable, Equatable {
struct ServerPromptCacheEntry: Sendable, Equatable {
let domain: ServerPromptCacheDomain
let inputMessages: [GFTokenizer.Message]
+ /// Per-message image content hashes for `inputMessages`. Plain message
+ /// equality cannot see images - image parts contribute nothing to a
+ /// message's flattened text - so two prompts differing only in their image
+ /// would compare equal without this.
+ let inputImageIdentities: [[String]]
let tools: [GFTokenizer.FunctionDefinition]
let assistantTurn: CachedAssistantTurn
let kvBackedTokenIDs: [Int32]
@@ -31,18 +36,61 @@ struct ServerPromptCacheEntry: Sendable, Equatable {
let kvPosition: Int
}
+/// Why a prefix could not be reused. Carried so a miss is diagnosable rather
+/// than indistinguishable from every other miss: a bridge that fails to render
+/// is a defect worth seeing, and a history that simply diverged is not.
+enum ServerPromptCacheMissReason: String, Sendable, Equatable {
+ case noEntry = "no-entry"
+ case unusableEntry = "unusable-entry"
+ case historyDiverged = "history-diverged"
+ case unsupportedContinuation = "unsupported-continuation"
+ case boundaryMismatch = "boundary-mismatch"
+ case bridgeRenderFailed = "bridge-render-failed"
+ case missingImageIdentity = "missing-image-identity"
+ case imagesDiverged = "images-diverged"
+}
+
enum ServerPromptCacheMatch: Sendable, Equatable {
- case miss
+ case miss(ServerPromptCacheMissReason)
case hit(effectivePromptIDs: [Int32], cachedPromptTokens: Int)
+ /// The history and its images match, but the new turn carries its own
+ /// image, so the effective prompt can only be produced by rendering. The
+ /// caller renders just that turn as a continuation on the cached tokens;
+ /// history is never re-rendered, because the KV holds tokens the model
+ /// generated and a fresh render re-tokenises that assistant text.
+ case renderThenResume(cachedPromptTokens: Int)
+
+ static let miss: ServerPromptCacheMatch = .miss(.noEntry)
+
+ var missReason: ServerPromptCacheMissReason? {
+ if case .miss(let reason) = self { return reason }
+ return nil
+ }
}
struct ServerPromptCache: Sendable {
private(set) var entry: ServerPromptCacheEntry?
+ var kvBackedTokenIDs: [Int32]? { entry?.kvBackedTokenIDs }
+ var inputMessageCount: Int? { entry?.inputMessages.count }
+
mutating func invalidate() {
entry = nil
}
+ /// Per-message image identity, or nil when a multimodal request did not
+ /// carry one entry per message. Nil is fail-closed: without identity an
+ /// image-bearing prompt would be indistinguishable from one carrying a
+ /// different image, so it must neither publish nor match.
+ static func identities(for request: ValidatedChatRequest) -> [[String]]? {
+ let count = request.messages.count
+ if request.multimodalMessages == nil, request.imageIdentities.isEmpty {
+ return Array(repeating: [], count: count)
+ }
+ guard request.imageIdentities.count == count else { return nil }
+ return request.imageIdentities
+ }
+
mutating func publish(
domain: ServerPromptCacheDomain,
request: ValidatedChatRequest,
@@ -71,9 +119,14 @@ struct ServerPromptCache: Sendable {
role: .assistant,
content: calls.isEmpty ? content : nil,
toolCalls: historicalCalls)
+ guard let identities = Self.identities(for: request) else {
+ entry = nil
+ return
+ }
entry = ServerPromptCacheEntry(
domain: domain,
inputMessages: request.messages,
+ inputImageIdentities: identities,
tools: request.tools,
assistantTurn: CachedAssistantTurn(
message: assistant,
@@ -83,10 +136,13 @@ struct ServerPromptCache: Sendable {
kvPosition: result.kvPosition)
}
+ /// `renderedPromptIDs` is nil for multimodal requests, where the rendered
+ /// ids cannot establish identity: image placeholder tokens are the same
+ /// token repeated whichever image they stand for.
func match(
domain: ServerPromptCacheDomain,
request: ValidatedChatRequest,
- renderedPromptIDs: [Int32],
+ renderedPromptIDs: [Int32]?,
tokenizer: GFTokenizer
) -> ServerPromptCacheMatch {
guard let entry,
@@ -95,10 +151,20 @@ struct ServerPromptCache: Sendable {
entry.kvPosition == entry.kvBackedTokenIDs.count,
entry.kvPosition > 0,
entry.uncommittedBoundaryTokenIDs.count == 1 else {
- return .miss
+ return .miss(.unusableEntry)
+ }
+
+ guard let requestIdentities = Self.identities(for: request) else {
+ return .miss(.missingImageIdentity)
}
- if renderedPromptIDs.count > entry.kvPosition,
+ // Rendered ids cannot identify an image, so the cheap prefix path is
+ // refused whenever either side carries one. Keeping that decision here
+ // rather than in the caller means the invariant holds for every caller.
+ if let renderedPromptIDs,
+ requestIdentities.allSatisfy(\.isEmpty),
+ entry.inputImageIdentities.allSatisfy(\.isEmpty),
+ renderedPromptIDs.count > entry.kvPosition,
renderedPromptIDs.prefix(entry.kvPosition)
.elementsEqual(entry.kvBackedTokenIDs) {
return .hit(
@@ -113,7 +179,23 @@ struct ServerPromptCache: Sendable {
assistantMatches(
request.messages[inputCount],
entry.assistantTurn.message) else {
- return .miss
+ return .miss(.historyDiverged)
+ }
+ guard requestIdentities.prefix(inputCount)
+ .elementsEqual(entry.inputImageIdentities) else {
+ return .miss(.imagesDiverged)
+ }
+ // The text bridge encoders cannot render an image, so a continuation
+ // carrying one resumes by rendering just that turn - but only after a
+ // clean end of turn. A `.maxTokens` entry holds a generated token
+ // outside the KV that the bridge does not replay, and a `.toolCalls`
+ // entry's boundary is a tool-response marker it does not emit; both
+ // would resume onto a prompt the client never sent.
+ if !requestIdentities.dropFirst(inputCount).allSatisfy(\.isEmpty) {
+ guard entry.assistantTurn.rawStopReason == .endOfTurn else {
+ return .miss(.unsupportedContinuation)
+ }
+ return .renderThenResume(cachedPromptTokens: entry.kvPosition)
}
let continuation = Array(request.messages.dropFirst(inputCount + 1))
@@ -160,13 +242,13 @@ struct ServerPromptCache: Sendable {
continuation[0].toolCallID == nil,
entry.assistantTurn.rawStopReason == .endOfTurn
|| entry.assistantTurn.rawStopReason == .maxTokens else {
- return .miss
+ return .miss(.unsupportedContinuation)
}
var bridge = tokenizer.encodeTextContinuation(userContent: content)
if entry.assistantTurn.rawStopReason == .maxTokens {
bridge = entry.uncommittedBoundaryTokenIDs + bridge
} else if bridge.first != entry.uncommittedBoundaryTokenIDs.first {
- return .miss
+ return .miss(.boundaryMismatch)
}
return .hit(
effectivePromptIDs: entry.kvBackedTokenIDs + bridge,
@@ -189,15 +271,24 @@ struct ServerPromptCache: Sendable {
&& message.content != nil
&& message.toolCalls.isEmpty
}) else {
- return .miss
- }
- guard let bridge = try? tokenizer.encodeToolResultContinuation(
- cachedMessages: entry.inputMessages,
- assistant: entry.assistantTurn.message,
- incomingMessages: request.messages,
- tools: request.tools),
- bridge.first == entry.uncommittedBoundaryTokenIDs.first else {
- return .miss
+ return .miss(.unsupportedContinuation)
+ }
+ // Not `try?` discarded: a bridge that fails to render is a distinct and
+ // diagnosable condition, not the same as a history that simply
+ // diverged, and both would otherwise arrive as one anonymous miss.
+ let bridge: [Int32]
+ do {
+ bridge = try tokenizer.encodeToolResultContinuation(
+ cachedMessages: entry.inputMessages,
+ assistant: entry.assistantTurn.message,
+ incomingMessages: request.messages,
+ tools: request.tools)
+ } catch {
+ ServerLog.promptCacheBridgeFailed(error: error)
+ return .miss(.bridgeRenderFailed)
+ }
+ guard bridge.first == entry.uncommittedBoundaryTokenIDs.first else {
+ return .miss(.boundaryMismatch)
}
return .hit(
effectivePromptIDs: entry.kvBackedTokenIDs + bridge,
diff --git a/Sources/TurboFieldfareServer/Core/StreamingChatRequestBody.swift b/Sources/TurboFieldfareServer/Core/StreamingChatRequestBody.swift
new file mode 100644
index 00000000..059a0bc3
--- /dev/null
+++ b/Sources/TurboFieldfareServer/Core/StreamingChatRequestBody.swift
@@ -0,0 +1,442 @@
+import Foundation
+import NIOCore
+
+struct ParsedChatRequestBody {
+ let json: Data
+ let stagedImages: [String: ServerStagedImage]
+ let lease: ServerAttachmentLease?
+}
+
+final class StreamingChatRequestBody {
+ static let maximumWireBytes = 96 * 1_024 * 1_024
+ static let maximumSanitizedBytes = 5 * 1_024 * 1_024
+ /// JSON nesting is decoded recursively downstream, on the event-loop thread
+ /// whose stack is the 512 KiB pthread default, so deep nesting exhausts it
+ /// and kills the process rather than failing the request. Foundation only
+ /// rejects beyond 512, which is already past the crash threshold.
+ static let maximumContainerDepth = 64
+
+ private enum ContainerKind { case object, array }
+ private struct Container {
+ let kind: ContainerKind
+ let contextKey: String?
+ var currentKey: String?
+ }
+
+ private enum StringMode {
+ /// An object key: copied through and collected so the key can be
+ /// decoded when the string closes.
+ case key
+ /// Any other string: copied through untouched.
+ case plain
+ /// A messages[].content[].image_url.url value before its data-URL
+ /// header's comma has decided between staging and passthrough.
+ case urlPrefix
+ /// The base64 payload of an image data URL, streamed to disk.
+ case staging
+ }
+
+ private struct StringState {
+ var mode: StringMode
+ /// A backslash was seen in `key`/`plain` mode, where escapes are copied
+ /// through raw; the flag only stops an escaped quote from terminating
+ /// the string.
+ var escaped = false
+ var escape = JSONStringEscapeDecoder()
+ var keyBytes: [UInt8] = []
+ /// The exact wire bytes of a `urlPrefix` value, re-emitted verbatim if
+ /// the value turns out not to be an image data URL.
+ var rawPrefix: [UInt8] = []
+ /// The same prefix with JSON escapes decoded, which is what the header
+ /// match and the comma detection must run on.
+ var decodedPrefix: [UInt8] = []
+ var writer: StreamingBase64FileWriter?
+ var replacementToken: String?
+ }
+
+ private var wireBytes = 0
+ private var json = Data()
+ private var containers: [Container] = []
+ private var string: StringState?
+ private var stagedImages: [String: ServerStagedImage] = [:]
+ private var totalImageBytes = 0
+ private var lease: ServerAttachmentLease?
+ /// Where this request stages its images. Injectable so a test can own its
+ /// staging root instead of sharing one with every other server in the
+ /// process.
+ private let attachmentRoot: URL
+ /// Staging writes decoded image bytes to disk, so a server that cannot
+ /// serve images must refuse them here — before any byte is staged — not
+ /// after the request has queued behind a generation.
+ private let visionCapability: String
+
+ init(attachmentRoot: URL = ServerAttachmentDirectory.root,
+ visionCapability: String = "ready") {
+ self.attachmentRoot = attachmentRoot
+ self.visionCapability = visionCapability
+ }
+
+ func feed(_ buffer: inout ByteBuffer) throws {
+ guard let bytes = buffer.readBytes(length: buffer.readableBytes) else { return }
+ wireBytes += bytes.count
+ guard wireBytes <= Self.maximumWireBytes else {
+ throw ServerRequestError.invalid(
+ message: "request body is too large",
+ param: nil, code: "request_too_large")
+ }
+ var index = 0
+ while index < bytes.count {
+ if let mode = string?.mode {
+ switch mode {
+ case .key, .plain:
+ index = try consumeCopiedString(bytes, from: index)
+ case .urlPrefix:
+ index = try consumeURLPrefix(bytes, at: index)
+ case .staging:
+ index = try consumeStagingPayload(bytes, from: index)
+ }
+ } else {
+ index = try consumeStructural(bytes, at: index)
+ }
+ }
+ }
+
+ func finish() throws -> ParsedChatRequestBody {
+ guard string == nil else {
+ throw ServerRequestError.invalid(
+ message: "unterminated JSON string",
+ param: nil, code: "invalid_json")
+ }
+ guard json.count <= Self.maximumSanitizedBytes else {
+ throw ServerRequestError.invalid(
+ message: "non-image request content is too large",
+ param: nil, code: "request_too_large")
+ }
+ return ParsedChatRequestBody(
+ json: json,
+ stagedImages: stagedImages,
+ lease: lease)
+ }
+
+ /// Only a URL at exactly messages[].content[].image_url.url is intercepted.
+ /// An image_url-shaped object anywhere else — a tool schema, a text field —
+ /// is someone else's data and must pass through byte-identical.
+ private var isMessageImageURLValue: Bool {
+ containers.count == 6
+ && containers[0].kind == .object && containers[0].contextKey == nil
+ && containers[1].kind == .array && containers[1].contextKey == "messages"
+ && containers[2].kind == .object
+ && containers[3].kind == .array && containers[3].contextKey == "content"
+ && containers[4].kind == .object
+ && containers[5].kind == .object
+ && containers[5].contextKey == "image_url"
+ && containers[5].currentKey == "url"
+ }
+
+ private func consumeStructural(_ bytes: [UInt8], at index: Int) throws -> Int {
+ let byte = bytes[index]
+ if byte == UInt8(ascii: "\"") {
+ try append(byte)
+ if isMessageImageURLValue {
+ string = StringState(mode: .urlPrefix)
+ } else if containers.last?.kind == .object,
+ containers.last?.currentKey == nil {
+ string = StringState(mode: .key)
+ } else {
+ string = StringState(mode: .plain)
+ }
+ return index + 1
+ }
+ try append(byte)
+ switch byte {
+ case UInt8(ascii: "{"), UInt8(ascii: "["):
+ guard containers.count < Self.maximumContainerDepth else {
+ throw ServerRequestError.invalid(
+ message: "request JSON nests deeper than "
+ + "\(Self.maximumContainerDepth) levels",
+ param: nil, code: "invalid_request_body")
+ }
+ containers.append(Container(
+ kind: byte == UInt8(ascii: "{") ? .object : .array,
+ contextKey: containers.last?.kind == .object
+ ? containers.last?.currentKey : containers.last?.contextKey,
+ currentKey: nil))
+ case UInt8(ascii: "}"), UInt8(ascii: "]"):
+ if !containers.isEmpty { containers.removeLast() }
+ case UInt8(ascii: ","):
+ if !containers.isEmpty, containers[containers.count - 1].kind == .object {
+ containers[containers.count - 1].currentKey = nil
+ }
+ default:
+ break
+ }
+ return index + 1
+ }
+
+ /// A `key` or `plain` string: whole spans up to the next quote or backslash
+ /// are copied at once, so the sanitized body never pays a per-byte state
+ /// machine for its bulk.
+ private func consumeCopiedString(_ bytes: [UInt8], from start: Int) throws -> Int {
+ var state = string!
+ var index = start
+ if state.escaped {
+ state.escaped = false
+ if state.mode == .key { state.keyBytes.append(bytes[index]) }
+ try append(bytes[index])
+ string = state
+ return index + 1
+ }
+ let end = Self.nextQuoteOrBackslash(bytes, from: index)
+ if end > index {
+ try append(contentsOf: bytes[index..<end])
+ if state.mode == .key {
+ state.keyBytes.append(contentsOf: bytes[index..<end])
+ }
+ index = end
+ }
+ guard index < bytes.count else {
+ string = state
+ return index
+ }
+ let byte = bytes[index]
+ try append(byte)
+ if byte == UInt8(ascii: "\\") {
+ state.escaped = true
+ if state.mode == .key { state.keyBytes.append(byte) }
+ string = state
+ return index + 1
+ }
+ if state.mode == .key, !containers.isEmpty,
+ containers[containers.count - 1].kind == .object {
+ let quoted = Data([UInt8(ascii: "\"")] + state.keyBytes + [UInt8(ascii: "\"")])
+ containers[containers.count - 1].currentKey =
+ try JSONDecoder().decode(String.self, from: quoted)
+ }
+ string = nil
+ return index + 1
+ }
+
+ /// The head of an image URL, one byte at a time — it is at most 64 decoded
+ /// bytes before it either becomes a data-URL payload or passes through.
+ /// Escapes are decoded because a spec-valid serializer may write the same
+ /// URL as `data:image\/png;...`; the raw bytes are kept alongside so a
+ /// passthrough re-emits exactly what arrived.
+ private func consumeURLPrefix(_ bytes: [UInt8], at index: Int) throws -> Int {
+ var state = string!
+ let byte = bytes[index]
+ if state.escape.isActive {
+ state.rawPrefix.append(byte)
+ let decoded = try state.escape.consume(byte)
+ try acceptPrefix(decoded: decoded, state: &state)
+ return index + 1
+ }
+ if byte == UInt8(ascii: "\"") {
+ try append(contentsOf: state.rawPrefix)
+ try append(byte)
+ string = nil
+ return index + 1
+ }
+ if byte == UInt8(ascii: "\\") {
+ state.rawPrefix.append(byte)
+ state.escape.begin()
+ string = state
+ return index + 1
+ }
+ state.rawPrefix.append(byte)
+ try acceptPrefix(decoded: [byte], state: &state)
+ return index + 1
+ }
+
+ private func acceptPrefix(decoded: [UInt8], state: inout StringState) throws {
+ for byte in decoded where byte == UInt8(ascii: ",") {
+ let header = String(decoding: state.decodedPrefix, as: UTF8.self)
+ .lowercased()
+ if header.hasPrefix("data:image/") {
+ guard visionCapability == "ready" else {
+ throw ServerRequestError.invalid(
+ message: visionCapability == "disabled"
+ ? "image support is disabled"
+ : "image support is unavailable",
+ param: "messages", code: "vision_unavailable")
+ }
+ guard ServerAttachmentStore.allowedDataURLHeaders.contains(header) else {
+ throw ServerRequestError.invalid(
+ message: "image_url must be a JPEG, PNG, HEIC, or HEIF base64 data URL",
+ param: "messages", code: "unsupported_image")
+ }
+ guard stagedImages.count < ServerAttachmentStore.maximumRequestImages else {
+ throw ServerRequestError.invalid(
+ message: "at most \(ServerAttachmentStore.maximumRequestImages) images "
+ + "per request",
+ param: "messages", code: "too_many_images")
+ }
+ let lease = try attachmentLease()
+ let token = UUID().uuidString.lowercased()
+ let writer = try StreamingBase64FileWriter(
+ directoryURL: lease.directoryURL)
+ try append(contentsOf: Array("turbofieldfare-attachment:\(token)".utf8))
+ string = StringState(mode: .staging,
+ writer: writer,
+ replacementToken: token)
+ } else {
+ try append(contentsOf: state.rawPrefix)
+ string = StringState(mode: .plain)
+ }
+ return
+ }
+ state.decodedPrefix.append(contentsOf: decoded)
+ if state.decodedPrefix.count > 64 {
+ try append(contentsOf: state.rawPrefix)
+ string = StringState(mode: .plain)
+ return
+ }
+ string = state
+ }
+
+ /// The base64 payload: whole spans up to the next quote or backslash go to
+ /// the writer at once. Escaped payload bytes are decoded and fed
+ /// individually; anything that decodes outside the base64 alphabet fails in
+ /// the writer exactly as it would have arrived raw.
+ private func consumeStagingPayload(_ bytes: [UInt8], from start: Int) throws -> Int {
+ var state = string!
+ if state.escape.isActive {
+ let decoded = try state.escape.consume(bytes[start])
+ if !decoded.isEmpty { try state.writer!.feed(contentsOf: decoded) }
+ string = state
+ return start + 1
+ }
+ let byte = bytes[start]
+ if byte == UInt8(ascii: "\"") {
+ let staged = try state.writer!.finish()
+ totalImageBytes += staged.encodedBytes
+ guard totalImageBytes <= ServerAttachmentStore.maximumRequestImageBytes else {
+ throw ServerRequestError.invalid(
+ message: "inline image bytes exceed the server limit",
+ param: "messages", code: "image_too_large")
+ }
+ stagedImages[state.replacementToken!] = staged
+ try append(byte)
+ string = nil
+ return start + 1
+ }
+ if byte == UInt8(ascii: "\\") {
+ state.escape.begin()
+ string = state
+ return start + 1
+ }
+ let end = Self.nextQuoteOrBackslash(bytes, from: start + 1)
+ try state.writer!.feed(contentsOf: bytes[start..<end])
+ string = state
+ return end
+ }
+
+ private static func nextQuoteOrBackslash(_ bytes: [UInt8], from start: Int) -> Int {
+ var index = start
+ while index < bytes.count {
+ let byte = bytes[index]
+ if byte == UInt8(ascii: "\"") || byte == UInt8(ascii: "\\") { return index }
+ index += 1
+ }
+ return index
+ }
+
+ private func attachmentLease() throws -> ServerAttachmentLease {
+ if let lease { return lease }
+ let created = try ServerAttachmentDirectory.makeLease(in: attachmentRoot)
+ lease = created
+ return created
+ }
+
+ private func append(_ byte: UInt8) throws {
+ json.append(byte)
+ try checkSanitizedSize()
+ }
+
+ private func append(contentsOf bytes: some Sequence<UInt8>) throws {
+ json.append(contentsOf: bytes)
+ try checkSanitizedSize()
+ }
+
+ private func checkSanitizedSize() throws {
+ guard json.count <= Self.maximumSanitizedBytes else {
+ throw ServerRequestError.invalid(
+ message: "non-image request content is too large",
+ param: nil, code: "request_too_large")
+ }
+ }
+}
+
+/// Decodes JSON string escape sequences inside an intercepted image URL, where
+/// the sanitized body keeps a replacement token and the raw bytes are gone —
+/// the URL has to be matched and staged from what the escapes mean, not how
+/// they were written.
+private struct JSONStringEscapeDecoder {
+ private enum State {
+ case idle
+ case started
+ case unicode([UInt8])
+ }
+
+ private var state = State.idle
+
+ var isActive: Bool {
+ if case .idle = state { return false }
+ return true
+ }
+
+ /// Enters the sequence; the caller has just consumed the backslash.
+ mutating func begin() {
+ state = .started
+ }
+
+ /// Feeds the next raw byte of the sequence. Returns the decoded bytes once
+ /// the sequence completes, and an empty array while it is still open.
+ mutating func consume(_ byte: UInt8) throws -> [UInt8] {
+ switch state {
+ case .idle:
+ preconditionFailure("consume called outside an escape sequence")
+ case .started:
+ switch byte {
+ case UInt8(ascii: "\""), UInt8(ascii: "\\"), UInt8(ascii: "/"):
+ state = .idle
+ return [byte]
+ case UInt8(ascii: "b"): state = .idle; return [8]
+ case UInt8(ascii: "f"): state = .idle; return [12]
+ case UInt8(ascii: "n"): state = .idle; return [10]
+ case UInt8(ascii: "r"): state = .idle; return [13]
+ case UInt8(ascii: "t"): state = .idle; return [9]
+ case UInt8(ascii: "u"):
+ state = .unicode([])
+ return []
+ default:
+ throw Self.invalidEscape
+ }
+ case .unicode(var digits):
+ guard Self.hexValue(byte) != nil else { throw Self.invalidEscape }
+ digits.append(byte)
+ guard digits.count == 4 else {
+ state = .unicode(digits)
+ return []
+ }
+ state = .idle
+ let value = digits.reduce(UInt32(0)) { $0 << 4 | UInt32(Self.hexValue($1)!) }
+ // Surrogate pairs only encode characters no data URL may contain,
+ // so they are refused rather than paired across two sequences.
+ guard let scalar = Unicode.Scalar(value) else { throw Self.invalidEscape }
+ return Array(String(scalar).utf8)
+ }
+ }
+
+ private static let invalidEscape = ServerRequestError.invalid(
+ message: "image_url contains an unsupported escape sequence",
+ param: "messages", code: "invalid_image_url")
+
+ private static func hexValue(_ byte: UInt8) -> UInt8? {
+ switch byte {
+ case UInt8(ascii: "0")...UInt8(ascii: "9"): byte - UInt8(ascii: "0")
+ case UInt8(ascii: "a")...UInt8(ascii: "f"): byte - UInt8(ascii: "a") + 10
+ case UInt8(ascii: "A")...UInt8(ascii: "F"): byte - UInt8(ascii: "A") + 10
+ default: nil
+ }
+ }
+}
diff --git a/Tests/TurboFieldfare/Core/CLI/CLIArgumentsTests.swift b/Tests/TurboFieldfare/Core/CLI/CLIArgumentsTests.swift
index 08455a82..9f12369b 100644
--- a/Tests/TurboFieldfare/Core/CLI/CLIArgumentsTests.swift
+++ b/Tests/TurboFieldfare/Core/CLI/CLIArgumentsTests.swift
@@ -9,7 +9,9 @@ import TurboFieldfare
#expect(arguments.prompt == "hi")
#expect(arguments.messagesFile == nil)
#expect(arguments.maxNew == 1_024)
- #expect(arguments.maxContext == 4096)
+ // 8K as of 2026-08-17, so an image and its prompt fit without anyone
+ // passing --max-context.
+ #expect(arguments.maxContext == 8192)
#expect(arguments.temperature == 0.2)
#expect(arguments.topK == 64)
#expect(arguments.topP == 0.95)
@@ -71,6 +73,7 @@ import TurboFieldfare
"--seed", "--stop", "--quiet", "--expert-cache-slots",
"--expert-cache-policy", "--prefill", "--prefill-chunk-tokens",
"--rdadvise", "--help",
+ "--chat-prompt", "--image", "--vision-pack", "--vision-residency",
]
let words = Args.usage.split { $0.isWhitespace || $0 == "(" || $0 == ")" }
let options = Set(words.map(String.init).filter { $0.hasPrefix("--") })
@@ -146,7 +149,7 @@ import TurboFieldfare
("--expert-cache-slots", "7"),
("--expert-cache-policy", "fifo"),
("--prefill", "yes"),
- ("--prefill-chunk-tokens", "256"),
+ ("--prefill-chunk-tokens", "512"),
("--rdadvise", "automatic"),
]
for (flag, value) in invalidValues {
@@ -175,9 +178,9 @@ import TurboFieldfare
}
arguments.expertCacheSlots = RuntimeConfiguration.production.expertCacheSlots
- arguments.prefillChunkTokens = 256
+ arguments.prefillChunkTokens = 512
#expect(throws: ArgsError.invalidValue(
- flag: "--prefill-chunk-tokens", value: "256")) {
+ flag: "--prefill-chunk-tokens", value: "512")) {
_ = try arguments.resolvedRuntimeConfiguration(forceLogitsHead: false)
}
@@ -222,4 +225,72 @@ import TurboFieldfare
])
}
}
+ @Test func imageChatOptionsPreserveOrderAndResidency() throws {
+ let a = try Args.parse([
+ "--model", "m.gturbo",
+ "--image", "first.png",
+ "--chat-prompt", "compare",
+ "--image", "second.jpg",
+ "--vision-pack", "vision.gturbo",
+ "--vision-residency", "keep-ready",
+ ])
+ #expect(a.chatPrompt == "compare")
+ #expect(a.images == ["first.png", "second.jpg"])
+ #expect(a.visionPack == "vision.gturbo")
+ #expect(a.visionResidency == .keepReady)
+ }
+
+ @Test func imagesRejectRawAndMessagesModesButNotACount() {
+ #expect(throws: ArgsError.self) {
+ _ = try Args.parse([
+ "--model", "m.gturbo", "--prompt", "raw", "--image", "x.png",
+ ])
+ }
+ #expect(throws: ArgsError.self) {
+ _ = try Args.parse([
+ "--model", "m.gturbo", "--messages-file", "m.json",
+ "--image", "x.png",
+ ])
+ }
+ // No fixed image count: what bounds a request is the context, checked
+ // against the rendered prompt once token costs are known. The server
+ // moved to a context-derived budget and the CLI follows.
+ let many = try? Args.parse([
+ "--model", "m.gturbo", "--chat-prompt", "x",
+ "--image", "1", "--image", "2", "--image", "3",
+ "--image", "4", "--image", "5", "--image", "6",
+ ])
+ #expect(many?.images.count == 6)
+ }
+
+ @Test func mutual_exclusion_chatPromptVsMessagesFile() {
+ do {
+ _ = try Args.parse([
+ "--model", "m.gturbo",
+ "--chat-prompt", "X",
+ "--messages-file", "Y.json",
+ ])
+ Issue.record("expected ArgsError.mutuallyExclusive")
+ } catch let e as ArgsError {
+ #expect(e == .mutuallyExclusive("--chat-prompt", "--messages-file"))
+ } catch {
+ Issue.record("unexpected error: \(error)")
+ }
+ }
+
+ @Test func mutual_exclusion_promptVsChatPrompt() {
+ do {
+ _ = try Args.parse([
+ "--model", "m.gturbo",
+ "--prompt", "X",
+ "--chat-prompt", "Y",
+ ])
+ Issue.record("expected ArgsError.mutuallyExclusive")
+ } catch let e as ArgsError {
+ #expect(e == .mutuallyExclusive("--prompt", "--chat-prompt"))
+ } catch {
+ Issue.record("unexpected error: \(error)")
+ }
+ }
+
}
diff --git a/Tests/TurboFieldfare/Core/CLI/CLIImageOrderTests.swift b/Tests/TurboFieldfare/Core/CLI/CLIImageOrderTests.swift
new file mode 100644
index 00000000..249f334e
--- /dev/null
+++ b/Tests/TurboFieldfare/Core/CLI/CLIImageOrderTests.swift
@@ -0,0 +1,33 @@
+import Foundation
+import Testing
+import TurboFieldfare
+@testable import TurboFieldfareCLICore
+
+/// The CLI plans and encodes images in dictionary order, which Swift derives
+/// from a per-process hash seed — so the same command line did the work in a
+/// different order on every run, and a failure named a different image each
+/// time.
+@Suite struct CLIImageOrderTests {
+ @Test func imagesAreProcessedInPromptOrder() {
+ let ids = (0..<6).map { _ in UUID() }
+ var images: [UUID: URL] = [:]
+ for (index, id) in ids.enumerated() {
+ images[id] = URL(fileURLWithPath: "/tmp/image-\(index).png")
+ }
+ let parts: [MultimodalContentPart] = ids.map { .image(id: $0) }
+ let messages = [MultimodalMessage(role: .user, content: parts)]
+
+ // Stable across repeated calls, and equal to the prompt's own order.
+ let first = orderedImageIDs(messages: messages, images: images)
+ #expect(first == ids, "images were not planned in the order the prompt lists them")
+ #expect(orderedImageIDs(messages: messages, images: images) == first)
+
+ // An image the parts never mention is still processed, not dropped.
+ let orphan = UUID()
+ images[orphan] = URL(fileURLWithPath: "/tmp/orphan.png")
+ let withOrphan = orderedImageIDs(messages: messages, images: images)
+ #expect(withOrphan.count == ids.count + 1)
+ #expect(withOrphan.last == orphan)
+ #expect(Set(withOrphan) == Set(images.keys))
+ }
+}
diff --git a/Tests/TurboFieldfare/Core/CLI/CLIPromptInputTests.swift b/Tests/TurboFieldfare/Core/CLI/CLIPromptInputTests.swift
new file mode 100644
index 00000000..2f71030f
--- /dev/null
+++ b/Tests/TurboFieldfare/Core/CLI/CLIPromptInputTests.swift
@@ -0,0 +1,217 @@
+import Testing
+import Foundation
+import Metal
+import TurboFieldfare
+@testable import TurboFieldfareCLICore
+
+/// The messages-file image path and the pre-load size check. Both were review
+/// findings, and neither had a test: the path resolution was dead code that
+/// looked live, and the size check is only worth anything if it runs before the
+/// model load.
+@Suite struct CLIPromptInputTests {
+ private func makeMessagesFile(
+ _ json: String, in directory: URL
+ ) throws -> URL {
+ let url = directory.appendingPathComponent("messages.json")
+ try Data(json.utf8).write(to: url)
+ return url
+ }
+
+ /// A relative `image_file` belongs to the messages file's directory. The old
+ /// code branched on `URL(fileURLWithPath:).path`, which resolves against the
+ /// *process* directory and is therefore always absolute — so the relative
+ /// branch never ran and every relative path silently resolved against
+ /// wherever the CLI happened to be started.
+ @Test func aRelativeImagePathResolvesAgainstTheMessagesFile() throws {
+ let manager = FileManager.default
+ let root = manager.temporaryDirectory
+ .appendingPathComponent("cli-messages-\(UUID().uuidString)", isDirectory: true)
+ let nested = root.appendingPathComponent("pictures", isDirectory: true)
+ try manager.createDirectory(at: nested, withIntermediateDirectories: true)
+ defer { try? manager.removeItem(at: root) }
+
+ let absolute = root.appendingPathComponent("absolute.png")
+ let messages = try makeMessagesFile("""
+ [{"role":"user","content":[
+ {"type":"image_file","path":"pictures/relative.png"},
+ {"type":"image_file","path":"\(absolute.path)"},
+ {"type":"text","text":"what is this?"}]}]
+ """, in: root)
+
+ var args = try Args.parse(["--model", "m.gturbo", "--messages-file", messages.path])
+ args.messagesFile = messages.path
+ let input = try parseInput(args: args)
+ guard case .multimodal(_, let images) = input else {
+ Issue.record("expected a multimodal input, got \(input)")
+ return
+ }
+
+ let paths = Set(images.values.map(\.standardizedFileURL.path))
+ #expect(paths.contains(nested.appendingPathComponent("relative.png")
+ .standardizedFileURL.path),
+ "a relative image path did not resolve against the messages file: \(paths)")
+ #expect(paths.contains(absolute.standardizedFileURL.path),
+ "an absolute image path was rewritten: \(paths)")
+ // Nothing may resolve against the process directory.
+ let cwd = manager.currentDirectoryPath
+ #expect(!paths.contains { $0.hasPrefix(cwd + "/relative") },
+ "an image resolved against the working directory")
+ }
+
+ /// A path that merely *contains* a slash is still relative. This is the case
+ /// the old `hasPrefix` on a `URL.path` could never distinguish.
+ @Test func aDotSlashPathIsTreatedAsRelative() throws {
+ let manager = FileManager.default
+ let root = manager.temporaryDirectory
+ .appendingPathComponent("cli-messages-\(UUID().uuidString)", isDirectory: true)
+ try manager.createDirectory(at: root, withIntermediateDirectories: true)
+ defer { try? manager.removeItem(at: root) }
+ let messages = try makeMessagesFile("""
+ [{"role":"user","content":[{"type":"image_file","path":"./a.png"}]}]
+ """, in: root)
+
+ var args = try Args.parse(["--model", "m.gturbo", "--messages-file", messages.path])
+ args.messagesFile = messages.path
+ guard case .multimodal(_, let images) = try parseInput(args: args) else {
+ Issue.record("expected a multimodal input")
+ return
+ }
+ let resolved = try #require(images.values.first).standardizedFileURL.path
+ #expect(resolved == root.appendingPathComponent("a.png").standardizedFileURL.path,
+ "./a.png resolved to \(resolved)")
+ }
+
+ /// The size half of the prompt check, which the image path calls before the
+ /// model load. An oversized image used to cost a full load and a GPU encode
+ /// before anything refused it.
+ @Test func anOversizedPromptIsRefusedByTheSizeCheckAlone() throws {
+ let pipe = Pipe()
+ var args = try Args.parse(["--model", "m.gturbo", "--prompt", "hi"])
+ args.maxContext = 512
+ args.maxNew = 64
+
+ let fits = validatePromptSize(
+ tokens: 400, args: args, stderr: pipe.fileHandleForWriting)
+ #expect(fits == nil, "a prompt inside the context was refused")
+
+ let overflows = validatePromptSize(
+ tokens: 449, args: args, stderr: pipe.fileHandleForWriting)
+ #expect(overflows?.exitCode == 2,
+ "prompt 449 + maxNew 64 exceeds maxContext 512 and was accepted")
+
+ // The boundary itself fits: 448 + 64 == 512.
+ #expect(validatePromptSize(
+ tokens: 448, args: args, stderr: pipe.fileHandleForWriting) == nil,
+ "an exactly-fitting prompt was refused")
+
+ pipe.fileHandleForWriting.closeFile()
+ let message = String(decoding: pipe.fileHandleForReading.readDataToEndOfFile(),
+ as: UTF8.self)
+ #expect(message.contains("context overflow"),
+ "the refusal did not say why: \(message)")
+ }
+
+ /// The CLI must reach the same residency default as the runtime and the
+ /// conversation, which is why there is one constant rather than four
+ /// literals — one of the four had drifted to `keepReady`.
+ /// `--image` with no prompt flag used to be reported as a conflict with
+ /// `--messages-file`, which the user had not passed. The missing flag is
+ /// `--chat-prompt`, and `--help` already says so.
+ @Test func aBareImageNamesTheMissingChatPromptRatherThanAConflict() {
+ #expect(throws: ArgsError.requiredMissing("--chat-prompt")) {
+ _ = try Args.parse(["--model", "m.gturbo", "--image", "/tmp/a.png"])
+ }
+ // The conflict message is still right when the conflict is real.
+ #expect(throws: ArgsError.mutuallyExclusive("--image", "--messages-file")) {
+ _ = try Args.parse([
+ "--model", "m.gturbo", "--image", "/tmp/a.png",
+ "--messages-file", "/tmp/m.json",
+ ])
+ }
+ }
+
+ /// The slot pre-flight reads `args.images`, which only `--image` fills, so
+ /// an image arriving through `--messages-file` used to survive validation
+ /// and fail inside the routed tile scheduler - after the model load and
+ /// after every image had been encoded on the GPU.
+ @Test func aMessagesFileImageIsRefusedBeforeTheModelLoadToo() throws {
+ let manager = FileManager.default
+ let directory = manager.temporaryDirectory
+ .appendingPathComponent("slots-preflight-\(UUID().uuidString)", isDirectory: true)
+ try manager.createDirectory(at: directory, withIntermediateDirectories: true)
+ defer { try? manager.removeItem(at: directory) }
+ let image = directory.appendingPathComponent("shot.png")
+ try Data([0x89, 0x50, 0x4E, 0x47]).write(to: image)
+ let messages = directory.appendingPathComponent("messages.json")
+ try Data("""
+ [{"role":"user","content":[{"type":"image_file","path":"shot.png"},
+ {"type":"text","text":"describe"}]}]
+ """.utf8).write(to: messages)
+
+ let arguments = try Args.parse([
+ "--model", "m.gturbo",
+ "--messages-file", messages.path,
+ "--expert-cache-slots", "8",
+ "--prefill", "off",
+ ])
+ let input = try parseInput(args: arguments)
+ #expect(input.hasImages)
+ let need = RuntimeConfiguration.minimumExpertCacheSlotsForChunkedPrefill
+ #expect(throws: ArgsError.imagePromptNeedsExpertCacheSlots(have: 8, need: need)) {
+ _ = try arguments.resolvedRuntimeConfiguration(
+ forceLogitsHead: false, imagePrompt: input.hasImages)
+ }
+ // The same arguments without an image stay valid.
+ #expect(throws: Never.self) {
+ _ = try arguments.resolvedRuntimeConfiguration(
+ forceLogitsHead: false, imagePrompt: false)
+ }
+ }
+
+ /// `--prefill off` with an image is silently coerced back to chunked deep in
+ /// the runtime, while the docs say off disables that path. The run is
+ /// correct; saying nothing about it is what made the flag look honoured.
+ @Test func anImagePromptSaysWhenItOverridesTheRequestedPrefill() {
+ #expect(prefillCoercionNotice(hasImages: true, config: .off)
+ == "[prefill coerced to chunked: image prompts require it]")
+ // Nothing to say when the request already matches what will run.
+ #expect(prefillCoercionNotice(
+ hasImages: true, config: .production(chunkTokens: 128)) == nil)
+ // And nothing at all for a text prompt, whatever the prefill mode.
+ #expect(prefillCoercionNotice(hasImages: false, config: .off) == nil)
+ }
+
+ @Test func theCLIDefaultsToTheSharedResidencyPolicy() throws {
+ let args = try Args.parse(["--model", "m.gturbo", "--prompt", "hi"])
+ #expect(args.visionResidency == VisionResidencyPolicy.defaultPolicy)
+ #expect(args.visionResidency == .onDemand)
+ let explicit = try Args.parse(
+ ["--model", "m.gturbo", "--prompt", "hi", "--vision-residency", "keep-ready"])
+ #expect(explicit.visionResidency == .keepReady,
+ "the opt-in is still reachable")
+ }
+
+ @Test(.enabled(
+ if: MTLCreateSystemDefaultDevice()?.supportsFamily(.apple8) == false,
+ "requires an Apple7 or older Metal device"))
+ func apple7ImageRunRejectsHardwareBeforeReadingTheModel() async throws {
+ let missing = FileManager.default.temporaryDirectory
+ .appendingPathComponent("missing-cli-model-\(UUID().uuidString).gturbo")
+ let arguments = try Args.parse([
+ "--model", missing.path,
+ "--chat-prompt", "describe",
+ "--image", missing.appendingPathComponent("missing.png").path,
+ ])
+ let errors = Pipe()
+
+ let result = await run(args: arguments, stderr: errors.fileHandleForWriting)
+ errors.fileHandleForWriting.closeFile()
+ let message = String(
+ decoding: errors.fileHandleForReading.readDataToEndOfFile(),
+ as: UTF8.self)
+
+ #expect(result.exitCode == 1)
+ #expect(message.contains("M2 or newer"),
+ "model IO masked the unsupported-hardware error: \(message)")
+ }
+}
diff --git a/Tests/TurboFieldfare/Core/Infrastructure/ModelIO/ModelLoaderPreadTests.swift b/Tests/TurboFieldfare/Core/Infrastructure/ModelIO/ModelLoaderPreadTests.swift
index 1e57fdbc..5dfc223d 100644
--- a/Tests/TurboFieldfare/Core/Infrastructure/ModelIO/ModelLoaderPreadTests.swift
+++ b/Tests/TurboFieldfare/Core/Infrastructure/ModelIO/ModelLoaderPreadTests.swift
@@ -64,4 +64,34 @@ import Metal
#expect(b[1] == 4)
}
+ @Test func visionResidencyModesReleaseOrRetainExpertStreamers() throws {
+ let dir = try ModelLoaderTests.writeToySynthetic()
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let device = try #require(MTLCreateSystemDefaultDevice())
+ let model = try Model.load(directoryURL: dir, device: device,
+ expecting: .gemma4Toy(),
+ streamingMode: .pread(slotCount: 2))
+ _ = try model.routedExpert(layer: 1, expert: 4)
+ let expectedScratch = UInt64(2 * Int(getpagesize()))
+
+ let retained = model.prepareExpertResidencyForVision(.keepReady)
+ #expect(retained.releasedLayerCount == 0)
+ #expect(retained.releasedSlotScratchBytes == 0)
+ #expect(retained.remainingOpenLayerCount == 1)
+ #expect(retained.remainingSlotScratchBytes == expectedScratch)
+
+ let released = model.prepareExpertResidencyForVision(
+ .onDemand, gpuDrainNanoseconds: 123)
+ #expect(released.gpuDrainNanoseconds == 123)
+ #expect(released.releasedLayerCount == 1)
+ #expect(released.releasedSlotScratchBytes == expectedScratch)
+ #expect(released.remainingOpenLayerCount == 0)
+ #expect(released.remainingSlotScratchBytes == 0)
+ #expect(model.openLayerFileCount() == 0)
+
+ let view = try model.routedExpert(layer: 1, expert: 4)
+ #expect(model.openLayerFileCount() == 1)
+ #expect(Self.readBytes(view)[1] == 4)
+ }
+
}
diff --git a/Tests/TurboFieldfare/Core/Kernels/Attention/PrefillAttentionTests.swift b/Tests/TurboFieldfare/Core/Kernels/Attention/PrefillAttentionTests.swift
index 92edb3d4..6e4ed304 100644
--- a/Tests/TurboFieldfare/Core/Kernels/Attention/PrefillAttentionTests.swift
+++ b/Tests/TurboFieldfare/Core/Kernels/Attention/PrefillAttentionTests.swift
@@ -20,6 +20,7 @@ import TurboFieldfareValidationSupport
var kvValid: Int
var window: Int
var scale: Float
+ var bidirectionalBlock: Range<Int>?
}
@Test func prefillAttentionMatchesCPUReferenceFullAndSWA() throws {
@@ -230,6 +231,78 @@ import TurboFieldfareValidationSupport
window: window, scale: 1.0)
}
+ @Test func prefillAttentionParamsLayoutMatchesMSL() throws {
+ #expect(MemoryLayout<PrefillAttentionParams>.size == 52)
+ #expect(MemoryLayout<PrefillAttentionParams>.stride == 52)
+
+ let params = PrefillAttentionParams(startPosition: 3,
+ queryCount: 5,
+ headDim: 7,
+ numQHeads: 11,
+ numKVHeads: 1,
+ kvValidCount: 17,
+ slidingWindow: 19,
+ kvTokenStrideElements: 23,
+ qTokenStrideElements: 29,
+ oTokenStrideElements: 31,
+ scale: 1.25,
+ bidirectionalBlockStart: 37,
+ bidirectionalBlockEnd: 41)
+ let ctx = try MetalContext()
+ let prefill = try PrefillAttention(context: ctx)
+ guard let out = ctx.device.makeBuffer(length: 13 * MemoryLayout<UInt32>.size,
+ options: .storageModeShared) else {
+ Issue.record("alloc failed")
+ return
+ }
+
+ let cb = ctx.queue.makeCommandBuffer()!
+ prefill.encodeParamsSmoke(commandBuffer: cb, params: params, out: out)
+ cb.commit()
+ cb.waitUntilCompleted()
+
+ let ptr = out.contents().bindMemory(to: UInt32.self, capacity: 11)
+ let fields = (0..<13).map { ptr[$0] }
+ #expect(fields[0] == params.startPosition)
+ #expect(fields[1] == params.queryCount)
+ #expect(fields[2] == params.headDim)
+ #expect(fields[3] == params.numQHeads)
+ #expect(fields[4] == params.numKVHeads)
+ #expect(fields[5] == params.kvValidCount)
+ #expect(fields[6] == params.slidingWindow)
+ #expect(fields[7] == params.kvTokenStrideElements)
+ #expect(fields[8] == params.qTokenStrideElements)
+ #expect(fields[9] == params.oTokenStrideElements)
+ #expect(fields[10] == params.scale.bitPattern)
+ #expect(fields[11] == params.bidirectionalBlockStart)
+ #expect(fields[12] == params.bidirectionalBlockEnd)
+ }
+
+ @Test func slidingAttentionMakesImageBlockBidirectionalWithinWindow() throws {
+ var fixture = Self.makeFixture(start: 4, chunk: 6, window: 5, seed: 0xA621)
+ fixture.bidirectionalBlock = 5..<9
+
+ let actual = try Self.runKernel(fixture)
+ let reference = Self.reference(fixture)
+ let maxAbs = RelError.maxAbsDiff(actual, reference)
+ let rel = RelError.compute(actual: actual, reference: reference)
+ #expect(maxAbs <= 2e-2, "image block maxAbs=\(maxAbs) rel=\(rel)")
+ #expect(rel <= 2e-2, "image block rel=\(rel) maxAbs=\(maxAbs)")
+ }
+
+ @Test func fullAttentionRemainsCausalForImageBlock() throws {
+ var fixture = Self.makeFixture(start: 4, chunk: 6, window: 0, seed: 0xA622)
+ fixture.bidirectionalBlock = 5..<9
+
+ let actual = try Self.runKernel(fixture)
+ fixture.bidirectionalBlock = nil
+ let reference = Self.reference(fixture)
+ let maxAbs = RelError.maxAbsDiff(actual, reference)
+ let rel = RelError.compute(actual: actual, reference: reference)
+ #expect(maxAbs <= 2e-2, "full image mask maxAbs=\(maxAbs) rel=\(rel)")
+ #expect(rel <= 2e-2, "full image mask rel=\(rel) maxAbs=\(maxAbs)")
+ }
+
private static func runAndCompare(_ fixture: Fixture, label: String) throws {
let actual = try Self.runKernel(fixture)
let reference = Self.reference(fixture)
@@ -274,7 +347,9 @@ import TurboFieldfareValidationSupport
kvTokenStrideElements: UInt32(fixture.kvStride),
qTokenStrideElements: UInt32(fixture.qStride),
oTokenStrideElements: UInt32(fixture.oStride),
- scale: fixture.scale)
+ scale: fixture.scale,
+ bidirectionalBlockStart: UInt32(fixture.bidirectionalBlock?.lowerBound ?? 0),
+ bidirectionalBlockEnd: UInt32(fixture.bidirectionalBlock?.upperBound ?? 0))
let cb = ctx.queue.makeCommandBuffer()!
prefill.encodeCausal(commandBuffer: cb,
@@ -288,6 +363,7 @@ import TurboFieldfareValidationSupport
outOffset: oPrefix * MemoryLayout<Float16>.size,
params: params,
kvRingCapacity: kvRingCapacity,
+ layerKind: fixture.window == 0 ? .full : .slidingWindow,
path: path)
cb.commit()
cb.waitUntilCompleted()
@@ -318,7 +394,10 @@ import TurboFieldfareValidationSupport
} else {
first = max(0, absQ + 1 - fixture.window)
}
- let last = min(fixture.kvValid, absQ + 1)
+ let isBidirectional = fixture.bidirectionalBlock?.contains(absQ) == true
+ let last = min(
+ fixture.kvValid,
+ isBidirectional ? fixture.bidirectionalBlock!.upperBound : absQ + 1)
for qh in 0..<fixture.qHeads {
let kvh = qh / qPerKV
var scores: [Float] = []
diff --git a/Tests/TurboFieldfare/Core/Kernels/Sampling/SampleTopK64Tests.swift b/Tests/TurboFieldfare/Core/Kernels/Sampling/SampleTopK64Tests.swift
index 619a4ed1..df87bb4c 100644
--- a/Tests/TurboFieldfare/Core/Kernels/Sampling/SampleTopK64Tests.swift
+++ b/Tests/TurboFieldfare/Core/Kernels/Sampling/SampleTopK64Tests.swift
@@ -18,6 +18,27 @@ import Testing
try GenerationConfig(temperature: 0, topK: nil, topP: 0.95).validate()
}
+ /// `validate()` checked temperature for finiteness from the start and never
+ /// checked the penalty beside it, so `--repetition-penalty inf` parsed, passed
+ /// validation, reached the kernel and quietly degraded the output rather than
+ /// being refused: a prompt that counts to eight broke into another language
+ /// mid-count and then apologised for itself. Every CLI float guard without an
+ /// upper bound admits infinity, which is how it got that far.
+ @Test func generationConfigRejectsAPenaltyThatCannotBeApplied() throws {
+ #expect(throws: GeneratorError.self) {
+ try GenerationConfig(temperature: 0, repetitionPenalty: .infinity).validate()
+ }
+ #expect(throws: GeneratorError.self) {
+ try GenerationConfig(temperature: 0, repetitionPenalty: 0).validate()
+ }
+ #expect(throws: GeneratorError.self) {
+ try GenerationConfig(temperature: 0, repetitionPenalty: .nan).validate()
+ }
+ // The default, and an ordinary setting, both stay valid.
+ try GenerationConfig(temperature: 0).validate()
+ try GenerationConfig(temperature: 0, repetitionPenalty: 1.1).validate()
+ }
+
private final class Rig {
let context: MetalContext
let current: Sample
diff --git a/Tests/TurboFieldfare/Core/Kernels/TensorCore/MPPPrefillInt4QMMTests.swift b/Tests/TurboFieldfare/Core/Kernels/TensorCore/MPPPrefillInt4QMMTests.swift
index bf431457..a75ad860 100644
--- a/Tests/TurboFieldfare/Core/Kernels/TensorCore/MPPPrefillInt4QMMTests.swift
+++ b/Tests/TurboFieldfare/Core/Kernels/TensorCore/MPPPrefillInt4QMMTests.swift
@@ -115,8 +115,9 @@ private let mppTensorOpsAvailable: Bool = {
weightOffset: Int = 0,
scaleOffset: Int = 0,
biasOffset: Int = 0,
- compareCPUReference: Bool = false) throws
- -> MPPPrefillInt4QMM.Path {
+ compareCPUReference: Bool = false,
+ expectedPath: MPPPrefillInt4QMM.Path = .affineThreadgroupF16) throws
+ -> MPPPrefillInt4QMM.PathMetadata {
let inputs = makeInputs(m: m, n: n, k: k,
adversarialAffine: adversarialAffine)
guard let weights = makeBuffer(device: context.device,
@@ -148,22 +149,29 @@ private let mppTensorOpsAvailable: Bool = {
t: m,
n: n,
k: k)
- let path = candidate.encode(commandBuffer: commandBuffer,
- weights: weights,
- weightsOffset: weightOffset,
- scales: scaleBuffer,
- scalesOffset: scaleOffset,
- biases: biasBuffer,
- biasesOffset: biasOffset,
- x: input,
- y: actualBuffer,
- m: m,
- n: n,
- k: k)
+ let metadata = candidate.encode(commandBuffer: commandBuffer,
+ weights: weights,
+ weightsOffset: weightOffset,
+ scales: scaleBuffer,
+ scalesOffset: scaleOffset,
+ biases: biasBuffer,
+ biasesOffset: biasOffset,
+ x: input,
+ y: actualBuffer,
+ m: m,
+ n: n,
+ k: k)
commandBuffer.commit()
commandBuffer.waitUntilCompleted()
#expect(commandBuffer.error == nil)
- #expect(path == .affineThreadgroupF16)
+ #expect(metadata.path == expectedPath)
+ #expect(metadata.modelDerivedCPUHeapScratchBytes == 0)
+ #expect(metadata.expandedWeightBufferBytes == 0)
+ #expect(metadata.threadgroupBytes == (expectedPath == .affineThreadgroupF16Apple10V1
+ ? 16_384 : 4096))
+ #expect(metadata.cooperativeValueBytesEstimate ==
+ (expectedPath == .affineThreadgroupF16Apple10V1 ? 32_768 : 16_384))
+ #expect(metadata.simultaneousWeightTiles == 1)
let baselineOutput = Fp16Buffer.read(expectedBuffer, count: m * n)
let actual = Fp16Buffer.read(actualBuffer, count: m * n)
@@ -184,7 +192,7 @@ private let mppTensorOpsAvailable: Bool = {
#expect(relative <= 1e-3,
"CPU reference M=\(m) N=\(n) K=\(k) maxAbs=\(maxAbs) rel=\(relative)")
}
- return path
+ return metadata
}
@Test(.enabled(if: mppTensorOpsAvailable,
@@ -193,6 +201,7 @@ private let mppTensorOpsAvailable: Bool = {
let context = try MetalContext()
let candidate = MPPPrefillInt4QMM(context: context)
let baseline = try PrefillInt4QMM(context: context)
+ #expect(candidate.isAvailable, "\(candidate.unavailableReason ?? "unknown error")")
try Self.runShape(context: context, candidate: candidate, baseline: baseline,
m: 64, n: 32, k: 64, compareCPUReference: true)
@@ -201,11 +210,101 @@ private let mppTensorOpsAvailable: Bool = {
compareCPUReference: true)
try Self.runShape(context: context, candidate: candidate, baseline: baseline,
m: 17, n: 35, k: 64, compareCPUReference: true)
- try Self.runShape(
+ let metadata = try Self.runShape(
context: context, candidate: candidate, baseline: baseline,
m: 17, n: 35, k: 128, adversarialAffine: true,
weightOffset: 13, scaleOffset: 2, biasOffset: 6,
compareCPUReference: true)
+ #expect(metadata.weightBufferOffsetRemainder128 == 13)
+ }
+
+ @Test func apple10GeometryPreservesAffineReferenceAndFallsBackForShortM() throws {
+ let context = try MetalContext()
+ guard context.device.supportsFamily(.apple10) else { return }
+ let candidate = MPPPrefillInt4QMM(context: context, variant: .apple10V1)
+ let baseline = try PrefillInt4QMM(context: context)
+ #expect(candidate.isAvailable, "\(candidate.unavailableReason ?? "unknown error")")
+
+ let selected = try Self.runShape(
+ context: context, candidate: candidate, baseline: baseline,
+ m: 64, n: 64, k: 128, adversarialAffine: true,
+ compareCPUReference: true,
+ expectedPath: .affineThreadgroupF16Apple10V1)
+ #expect(selected.tileM == 64)
+ #expect(selected.tileN == 64)
+ #expect(selected.tileK == 128)
+ #expect(selected.fallbackCount == 0)
+
+ let fallback = try Self.runShape(
+ context: context, candidate: candidate, baseline: baseline,
+ m: 17, n: 35, k: 128, adversarialAffine: true,
+ compareCPUReference: true)
+ #expect(fallback.fallbackCount == 1)
+ }
+
+ @Test func apple10BF16ProjectorPreservesBF16AffineSemantics() throws {
+ let context = try MetalContext()
+ guard context.device.supportsFamily(.apple10) else { return }
+ let m = 64, n = 64, k = 128
+ let inputs = Self.makeInputs(m: m, n: n, k: k, adversarialAffine: true)
+ let activations = inputs.x.map { Quantization.bf16Bits(Float($0)) }
+ guard let weights = Self.makeBuffer(device: context.device, values: inputs.packed),
+ let scales = Self.makeBuffer(device: context.device, values: inputs.scales),
+ let biases = Self.makeBuffer(device: context.device, values: inputs.biases),
+ let x = Self.makeBuffer(device: context.device, values: activations),
+ let y = Fp16Buffer.make(context.device, count: m * n),
+ let commandBuffer = context.queue.makeCommandBuffer() else {
+ Issue.record("buffer allocation failed")
+ return
+ }
+ let candidate = MPPPrefillInt4QMM(context: context, variant: .apple10BF16)
+ #expect(candidate.isAvailable, "\(candidate.unavailableReason ?? "unknown error")")
+ // A short output must still project. The BF16 variant is the vision
+ // projector and has no control kernel, so falling back here meant not
+ // projecting at all — a 3x3 patch grid pools to a single row and failed
+ // outright. The Apple10 kernel bound-checks against M, so a partial tile
+ // is correct.
+ let shortOutput = candidate.encode(
+ commandBuffer: commandBuffer,
+ weights: weights, scales: scales, biases: biases,
+ x: x, y: y, m: 17, n: 35, k: k)
+ #expect(shortOutput.path == .affineThreadgroupBF16Apple10)
+ #expect(shortOutput.fallbackCount == 0)
+ let singleRow = candidate.encode(
+ commandBuffer: commandBuffer,
+ weights: weights, scales: scales, biases: biases,
+ x: x, y: y, m: 1, n: 35, k: k)
+ #expect(singleRow.path == .affineThreadgroupBF16Apple10)
+ let metadata = candidate.encode(
+ commandBuffer: commandBuffer,
+ weights: weights, scales: scales, biases: biases,
+ x: x, y: y, m: m, n: n, k: k)
+ commandBuffer.commit()
+ commandBuffer.waitUntilCompleted()
+ #expect(commandBuffer.error == nil)
+ #expect(metadata.path == .affineThreadgroupBF16Apple10)
+
+ var reference = [Float](repeating: 0, count: m * n)
+ let groups = k / Quantization.groupSize
+ for token in 0..<m {
+ for row in 0..<n {
+ var accumulator: Float = 0
+ for column in 0..<k {
+ let byte = inputs.packed[row * k / 2 + column / 2]
+ let q = column.isMultiple(of: 2) ? byte & 0x0f : byte >> 4
+ let group = row * groups + column / Quantization.groupSize
+ let weight = Quantization.bf16ToFloat(Quantization.bf16Bits(
+ Float(q) * Quantization.bf16ToFloat(inputs.scales[group])
+ + Quantization.bf16ToFloat(inputs.biases[group])))
+ accumulator.addProduct(
+ weight, Quantization.bf16ToFloat(activations[token * k + column]))
+ }
+ reference[token * n + row] = Float(Float16(accumulator))
+ }
+ }
+ let actual = Fp16Buffer.read(y, count: m * n)
+ #expect(RelError.maxAbsDiff(actual, reference) <= 0.03)
+ #expect(RelError.compute(actual: actual, reference: reference) <= 1e-3)
}
@Test(.enabled(if: mppTensorOpsAvailable,
@@ -224,10 +323,10 @@ private let mppTensorOpsAvailable: Bool = {
]
for m in [32, 128] {
for shape in shapes {
- let path = try Self.runShape(
+ let metadata = try Self.runShape(
context: context, candidate: candidate, baseline: baseline,
m: m, n: shape.n, k: shape.k)
- #expect(path == .affineThreadgroupF16,
+ #expect(metadata.path == .affineThreadgroupF16,
"\(shape.name) M=\(m) unexpectedly fell back")
}
}
@@ -255,17 +354,17 @@ private let mppTensorOpsAvailable: Bool = {
return
}
for run in 0..<32 {
- let path = candidate.encode(commandBuffer: commandBuffer,
- weights: weights,
- scales: scales,
- biases: biases,
- x: input,
- y: outputs,
- yOffset: run * outputBytes,
- m: m,
- n: n,
- k: k)
- #expect(path == .affineThreadgroupF16)
+ let metadata = candidate.encode(commandBuffer: commandBuffer,
+ weights: weights,
+ scales: scales,
+ biases: biases,
+ x: input,
+ y: outputs,
+ yOffset: run * outputBytes,
+ m: m,
+ n: n,
+ k: k)
+ #expect(metadata.path == .affineThreadgroupF16)
}
commandBuffer.commit()
commandBuffer.waitUntilCompleted()
@@ -314,7 +413,46 @@ private let mppTensorOpsAvailable: Bool = {
m: 1,
n: 1,
k: 64)
- #expect(unsupportedShape == .unavailable)
- #expect(unalignedScale == .unavailable)
+ #expect(unsupportedShape.path == .fallback)
+ #expect(unsupportedShape.fallbackCount == 1)
+ #expect(unalignedScale.path == .fallback)
+ #expect(unalignedScale.fallbackCount == 1)
+ }
+
+ /// When a variant cannot come up it must name the function it actually
+ /// needed. The BF16 variant — the vision projector — used to report the f16
+ /// symbol as missing: a symbol that is present, on a device that may simply
+ /// be too old. The failure held whichever way it went, so it sent whoever
+ /// read it looking in the wrong place.
+ ///
+ /// Holds on both device classes: on an Apple10 GPU the variant comes up and
+ /// there is no message to get wrong.
+ @Test func anUnavailableVariantNamesItsOwnFunction() throws {
+ let context = try MetalContext()
+ let apple10 = context.device.supportsFamily(.apple10)
+
+ for (variant, symbol) in [
+ (MPPPrefillInt4QMM.Variant.apple10BF16,
+ "mpp_prefill_affine_threadgroup_bf16_apple10_v1"),
+ (MPPPrefillInt4QMM.Variant.apple10V1,
+ "mpp_prefill_affine_threadgroup_f16_apple10_v1"),
+ ] {
+ let candidate = MPPPrefillInt4QMM(context: context, variant: variant)
+ guard let reason = candidate.unavailableReason else {
+ #expect(candidate.isAvailable,
+ "\(variant.rawValue) reported no reason and is not available")
+ continue
+ }
+ #expect(reason.contains(symbol),
+ "\(variant.rawValue) failed without naming \(symbol): \(reason)")
+ if variant == .apple10BF16 {
+ #expect(!reason.contains("mpp_prefill_affine_threadgroup_f16 "),
+ "the BF16 variant blamed the f16 symbol: \(reason)")
+ }
+ if !apple10 {
+ #expect(reason.contains("Apple10"),
+ "an old device was not named as the cause: \(reason)")
+ }
+ }
}
}
diff --git a/Tests/TurboFieldfare/Core/Kernels/Vision/VisionAttentionTests.swift b/Tests/TurboFieldfare/Core/Kernels/Vision/VisionAttentionTests.swift
new file mode 100644
index 00000000..ac045c5b
--- /dev/null
+++ b/Tests/TurboFieldfare/Core/Kernels/Vision/VisionAttentionTests.swift
@@ -0,0 +1,347 @@
+import Metal
+import Testing
+@testable import TurboFieldfare
+
+private let visionMPPTensorOpsAvailable = MTLCreateSystemDefaultDevice()?
+ .supportsFamily(.apple8) == true
+
+@Suite struct VisionAttentionTests {
+ /// The layout is the caller's decision, signalled by the row stride: the
+ /// runtime fuses only when the linear path can also write the padded
+ /// head-major store, so an attention that *could* fuse still receives
+ /// row-major Q/K/V when it cannot. Reading those as 80-stride head-major
+ /// used to fail a precondition on every image whenever the register MLP or
+ /// the MLX GEMM override was set on its own.
+ @Test(.enabled(if: visionMPPTensorOpsAvailable,
+ "vision MPP tensor shapes require Apple8 or newer"))
+ func rowMajorInputsAreHonouredEvenWhenTheFusedLayoutIsAvailable() throws {
+ let context = try MetalContext()
+ let attention = try VisionAttention(
+ context: context,
+ environment: ["TURBO_FIELDFARE_VISION_ATTENTION_MPP": "1"])
+ try #require(attention.usesFusedPaddedLayout,
+ "this configuration does not fuse, so there is nothing to test")
+
+ // 200 spans four 64-key tiles; the reference test validates both paths
+ // against FP32 at this length, so any divergence here is the layout.
+ let length = 200
+ let heads = 2
+ let dimension = VisionAttention.headDimension
+ var q = [Float](repeating: 0, count: length * heads * dimension)
+ var k = q
+ var v = q
+ for index in q.indices {
+ q[index] = Float((index * 13) % 17 - 8) / 32
+ k[index] = Float((index * 7) % 19 - 9) / 32
+ v[index] = Float((index * 5) % 23 - 11) / 16
+ }
+ func make(_ values: [Float]) throws -> MTLBuffer {
+ let bits = values.map(Quantization.bf16Bits)
+ return try #require(context.device.makeBuffer(
+ bytes: bits, length: bits.count * MemoryLayout<UInt16>.stride,
+ options: .storageModeShared))
+ }
+ // The same values laid out head-major with the 80-lane stride, which is
+ // what the fused branch expects.
+ let padded = VisionAttention.paddedHeadDimension
+ func makePadded(_ values: [Float]) throws -> MTLBuffer {
+ var laid = [Float](repeating: 0, count: heads * length * padded)
+ for row in 0..<length {
+ for head in 0..<heads {
+ for d in 0..<dimension {
+ laid[(head * length + row) * padded + d] =
+ values[(row * heads + head) * dimension + d]
+ }
+ }
+ }
+ return try make(laid)
+ }
+
+ func run(rowMajor: Bool) throws -> [Float] {
+ let output = try #require(context.device.makeBuffer(
+ length: q.count * MemoryLayout<UInt16>.stride,
+ options: .storageModeShared))
+ let commandBuffer = try #require(context.queue.makeCommandBuffer())
+ attention.encode(
+ commandBuffer: commandBuffer,
+ q: rowMajor ? try make(q) : try makePadded(q),
+ k: rowMajor ? try make(k) : try makePadded(k),
+ v: rowMajor ? try make(v) : try makePadded(v),
+ output: output,
+ sequenceLength: length, numHeads: heads,
+ inputRowStride: rowMajor ? 0 : length)
+ commandBuffer.commit()
+ commandBuffer.waitUntilCompleted()
+ #expect(commandBuffer.error == nil)
+ let bits = output.contents().bindMemory(to: UInt16.self, capacity: q.count)
+ return (0..<q.count).map { Quantization.bf16ToFloat(bits[$0]) }
+ }
+
+ // Same attention, same values, two layouts. A layout misread is a gross
+ // error, so this compares the two paths against each other rather than
+ // against a tolerance on an FP32 reference.
+ let fallback = try run(rowMajor: true)
+ let fused = try run(rowMajor: false)
+ // The tolerance below is wider than the signal in this fixture, so it
+ // cannot tell a correct output from an empty one. It let a fallback
+ // that wrote only half its rows pass. Every row must be written.
+ for row in 0..<length {
+ let start = row * heads * dimension
+ let slice = fallback[start..<(start + heads * dimension)]
+ #expect(slice.contains { $0 != 0 },
+ "row \(row) of the fallback output was never written")
+ }
+ for index in fallback.indices {
+ let detail = "row-major fallback diverged at \(index): "
+ + "\(fallback[index]) vs fused \(fused[index])"
+ #expect(abs(fallback[index] - fused[index]) <= 0.02, "\(detail)")
+ }
+ }
+
+ /// When the linear path cannot write the padded head-major store, the
+ /// runtime constructs attention with `allowFusedPaddedLayout: false`. The
+ /// MPP kernel the environment asked for must still run — through the
+ /// pad/unpad roundtrip — rather than silently degrading to the native
+ /// kernel while `variant` reported otherwise.
+ @Test(.enabled(if: visionMPPTensorOpsAvailable,
+ "vision MPP tensor shapes require Apple8 or newer"))
+ func mppWithoutThePaddedStoreStillRunsTheMPPKernel() throws {
+ let context = try MetalContext()
+ let attention = try VisionAttention(
+ context: context,
+ environment: ["TURBO_FIELDFARE_VISION_ATTENTION_MPP": "1"],
+ allowFusedPaddedLayout: false)
+ #expect(attention.variant == .mppTensorOps72)
+ #expect(!attention.usesFusedPaddedLayout)
+ #expect(attention.fusedQ == nil,
+ "a row-major caller must not be handed fused destination buffers")
+
+ let length = 200
+ let heads = 2
+ let dimension = VisionAttention.headDimension
+ var q = [Float](repeating: 0, count: length * heads * dimension)
+ var k = q
+ var v = q
+ for index in q.indices {
+ q[index] = Float((index * 13) % 17 - 8) / 32
+ k[index] = Float((index * 7) % 19 - 9) / 32
+ v[index] = Float((index * 5) % 23 - 11) / 16
+ }
+ func make(_ values: [Float]) throws -> MTLBuffer {
+ let bits = values.map(Quantization.bf16Bits)
+ return try #require(context.device.makeBuffer(
+ bytes: bits, length: bits.count * MemoryLayout<UInt16>.stride,
+ options: .storageModeShared))
+ }
+ let qBuffer = try make(q), kBuffer = try make(k), vBuffer = try make(v)
+
+ func run(_ attention: VisionAttention) throws -> ([Float], [VisionAttention.Phase]) {
+ let output = try #require(context.device.makeBuffer(
+ length: q.count * MemoryLayout<UInt16>.stride,
+ options: .storageModeShared))
+ var phases: [VisionAttention.Phase] = []
+ let commandBuffer = try #require(context.queue.makeCommandBuffer())
+ attention.encodePhased(
+ q: qBuffer, k: kBuffer, v: vBuffer, output: output,
+ sequenceLength: length, numHeads: heads,
+ inputRowStride: 0) { phase, body in
+ phases.append(phase)
+ body(commandBuffer)
+ }
+ commandBuffer.commit()
+ commandBuffer.waitUntilCompleted()
+ #expect(commandBuffer.error == nil)
+ let bits = output.contents().bindMemory(to: UInt16.self, capacity: q.count)
+ return ((0..<q.count).map { Quantization.bf16ToFloat(bits[$0]) }, phases)
+ }
+
+ // Pad and unpad running is the proof the padded MPP kernel executed;
+ // the native fallback this used to hit runs `.core` alone.
+ let (roundtrip, phases) = try run(attention)
+ #expect(phases == [.pad, .core, .unpad],
+ "the MPP roundtrip did not run; phases were \(phases)")
+
+ // Cross-checked against the native kernel, which shares no layout code.
+ let (native, nativePhases) = try run(
+ try VisionAttention(context: context, environment: [:]))
+ #expect(nativePhases == [.core])
+ for index in roundtrip.indices {
+ #expect(abs(roundtrip[index] - native[index]) <= 0.02,
+ "roundtrip diverged at \(index): \(roundtrip[index]) vs native \(native[index])")
+ }
+ }
+
+ /// 5 fits one 64-key tile; 200 spans four tiles and is the only case that
+ /// exercises the online rescale between tiles.
+ @Test(arguments: [5, 200])
+ func onlineAttentionMatchesFP32Reference(length: Int) throws {
+ let context = try MetalContext()
+ let heads = 2
+ let dimension = VisionAttention.headDimension
+ var q = [Float](repeating: 0, count: length * heads * dimension)
+ var k = q
+ var v = q
+ for index in q.indices {
+ q[index] = Float((index * 13) % 17 - 8) / 32
+ k[index] = Float((index * 7) % 19 - 9) / 32
+ v[index] = Float((index * 5) % 23 - 11) / 16
+ }
+ func make(_ values: [Float]) throws -> MTLBuffer {
+ let bits = values.map(Quantization.bf16Bits)
+ return try #require(context.device.makeBuffer(
+ bytes: bits, length: bits.count * MemoryLayout<UInt16>.stride,
+ options: .storageModeShared))
+ }
+ let qBuffer = try make(q)
+ let kBuffer = try make(k)
+ let vBuffer = try make(v)
+ // Head-major [head][row][80] copies for the fused layout, which reads the
+ // padding the projections would otherwise have written.
+ let padded = VisionAttention.paddedHeadDimension
+ func makePadded(_ values: [Float]) throws -> MTLBuffer {
+ var laid = [Float](repeating: 0, count: heads * length * padded)
+ for row in 0..<length {
+ for head in 0..<heads {
+ for d in 0..<dimension {
+ laid[(head * length + row) * padded + d] =
+ values[(row * heads + head) * dimension + d]
+ }
+ }
+ }
+ return try make(laid)
+ }
+ let paddedQBuffer = try makePadded(q)
+ let paddedKBuffer = try makePadded(k)
+ let paddedVBuffer = try makePadded(v)
+ let output = try #require(context.device.makeBuffer(
+ length: q.count * MemoryLayout<UInt16>.stride,
+ options: .storageModeShared))
+
+ var environments: [[String: String]] = [
+ ["TURBO_FIELDFARE_VISION_ATTENTION_Q8": "1"],
+ [:],
+ ["TURBO_FIELDFARE_VISION_ATTENTION_PAD80": "1"],
+ ]
+ if visionMPPTensorOpsAvailable {
+ environments.append(contentsOf: [
+ ["TURBO_FIELDFARE_VISION_ATTENTION_MPP": "1"],
+ ["TURBO_FIELDFARE_VISION_ATTENTION_MPP": "1",
+ "TURBO_FIELDFARE_VISION_PAD_ROUNDTRIP": "1"],
+ ["TURBO_FIELDFARE_VISION_ATTENTION_MPP": "1",
+ "TURBO_FIELDFARE_VISION_ATTENTION_PARALLEL_SOFTMAX": "1"],
+ ["TURBO_FIELDFARE_VISION_ATTENTION_MPP": "1",
+ "TURBO_FIELDFARE_VISION_ATTENTION_SERIAL_SOFTMAX": "1"],
+ ])
+ }
+ for environment in environments {
+ let attention = try VisionAttention(
+ context: context,
+ environment: environment)
+ let fused = attention.usesFusedPaddedLayout
+ let commandBuffer = try #require(context.queue.makeCommandBuffer())
+ attention.encode(commandBuffer: commandBuffer,
+ q: fused ? paddedQBuffer : qBuffer,
+ k: fused ? paddedKBuffer : kBuffer,
+ v: fused ? paddedVBuffer : vBuffer,
+ output: output,
+ sequenceLength: length, numHeads: heads,
+ inputRowStride: fused ? length : 0)
+ commandBuffer.commit()
+ commandBuffer.waitUntilCompleted()
+ #expect(commandBuffer.error == nil)
+
+ let actualBits = output.contents().bindMemory(
+ to: UInt16.self, capacity: q.count)
+ for query in 0..<length {
+ for head in 0..<heads {
+ var scores = [Float](repeating: 0, count: length)
+ for key in 0..<length {
+ for d in 0..<dimension {
+ scores[key] += q[(query * heads + head) * dimension + d]
+ * k[(key * heads + head) * dimension + d]
+ }
+ }
+ let maximum = scores.max()!
+ let weights = scores.map { exp($0 - maximum) }
+ let denominator = weights.reduce(0, +)
+ for d in 0..<dimension {
+ var expected: Float = 0
+ for key in 0..<length {
+ expected += weights[key]
+ * v[(key * heads + head) * dimension + d]
+ }
+ expected /= denominator
+ let index = (query * heads + head) * dimension + d
+ let actual = Quantization.bf16ToFloat(actualBits[index])
+ #expect(abs(actual - expected) <= 0.02,
+ "variant=\(attention.variant) index=\(index) actual=\(actual) expected=\(expected)")
+ }
+ }
+ }
+ }
+ }
+
+ /// The parallel softmax phase changes only the tile-sum reduction order, so at
+ /// production shape it must stay within BF16 rounding of the serial phase.
+ /// A layout or lane-grouping mistake would show here as a gross difference.
+ @Test(.enabled(if: visionMPPTensorOpsAvailable,
+ "vision MPP tensor shapes require Apple8 or newer"))
+ func parallelSoftmaxStaysWithinRoundingOfSerialPhase() throws {
+ let context = try MetalContext()
+ let length = 512
+ let heads = 4
+ let dimension = VisionAttention.headDimension
+ let padded = VisionAttention.paddedHeadDimension
+ var values = [Float](repeating: 0, count: heads * length * padded)
+ var state: UInt64 = 0x9E3779B97F4A7C15
+ for head in 0..<heads {
+ for row in 0..<length {
+ for d in 0..<dimension {
+ state = state &* 6_364_136_223_846_793_005 &+ 1_442_695_040_888_963_407
+ let unit = Float(state >> 40) / Float(1 << 24) - 0.5
+ values[(head * length + row) * padded + d] = unit
+ }
+ }
+ }
+ func make() throws -> MTLBuffer {
+ let bits = values.map(Quantization.bf16Bits)
+ return try #require(context.device.makeBuffer(
+ bytes: bits, length: bits.count * MemoryLayout<UInt16>.stride,
+ options: .storageModeShared))
+ }
+ let q = try make(), k = try make(), v = try make()
+
+ func run(parallel: Bool) throws -> [Float] {
+ var environment = ["TURBO_FIELDFARE_VISION_ATTENTION_MPP": "1"]
+ environment[parallel
+ ? "TURBO_FIELDFARE_VISION_ATTENTION_PARALLEL_SOFTMAX"
+ : "TURBO_FIELDFARE_VISION_ATTENTION_SERIAL_SOFTMAX"] = "1"
+ let attention = try VisionAttention(context: context, environment: environment)
+ #expect(attention.usesParallelSoftmax == parallel)
+ let count = length * heads * dimension
+ let output = try #require(context.device.makeBuffer(
+ length: count * MemoryLayout<UInt16>.stride, options: .storageModeShared))
+ let commandBuffer = try #require(context.queue.makeCommandBuffer())
+ attention.encode(commandBuffer: commandBuffer, q: q, k: k, v: v,
+ output: output, sequenceLength: length, numHeads: heads,
+ inputRowStride: length)
+ commandBuffer.commit()
+ commandBuffer.waitUntilCompleted()
+ #expect(commandBuffer.error == nil)
+ let bits = output.contents().bindMemory(to: UInt16.self, capacity: count)
+ return (0..<count).map { Quantization.bf16ToFloat(bits[$0]) }
+ }
+
+ let serial = try run(parallel: false)
+ let parallel = try run(parallel: true)
+ var maximumDifference: Float = 0
+ var magnitude: Float = 0
+ for index in serial.indices {
+ maximumDifference = max(maximumDifference, abs(serial[index] - parallel[index]))
+ magnitude = max(magnitude, abs(serial[index]))
+ }
+ #expect(magnitude > 0)
+ #expect(maximumDifference <= 0.01 * magnitude,
+ "max difference \(maximumDifference) against magnitude \(magnitude)")
+ }
+}
diff --git a/Tests/TurboFieldfare/Core/Kernels/Vision/VisionLinearBF16Tests.swift b/Tests/TurboFieldfare/Core/Kernels/Vision/VisionLinearBF16Tests.swift
new file mode 100644
index 00000000..f5e8beea
--- /dev/null
+++ b/Tests/TurboFieldfare/Core/Kernels/Vision/VisionLinearBF16Tests.swift
@@ -0,0 +1,145 @@
+import Foundation
+import Metal
+import Testing
+@testable import TurboFieldfare
+
+private let visionMPPTensorOpsAvailable = MTLCreateSystemDefaultDevice()?
+ .supportsFamily(.apple8) == true
+
+@Suite struct VisionLinearBF16Tests {
+ @Test(.enabled(if: visionMPPTensorOpsAvailable,
+ "vision linear kernels require Apple8 or newer"))
+ func nativePathsProduceExpectedConstantProduct() throws {
+ let context = try MetalContext()
+ let m = 128, n = 256, k = 1_152
+ func buffer(count: Int, value: Float) throws -> MTLBuffer {
+ let bits = [UInt16](repeating: Quantization.bf16Bits(value), count: count)
+ return try #require(context.device.makeBuffer(
+ bytes: bits, length: bits.count * MemoryLayout<UInt16>.stride,
+ options: .storageModeShared))
+ }
+ let input = try buffer(count: m * k, value: 0.125)
+ let weights = try buffer(count: n * k, value: 0.25)
+
+ for environment in [
+ [String: String](),
+ ["TURBO_FIELDFARE_VISION_REGISTER_GEMM": "1"],
+ ] {
+ // A fresh output per variant, poisoned rather than zeroed: sharing
+ // one buffer meant the second variant was compared against what the
+ // first had written, so a kernel that dispatched nothing passed.
+ let output = try buffer(count: m * n, value: -1)
+ let linear = try VisionLinearBF16(context: context, environment: environment)
+ let commandBuffer = try #require(context.queue.makeCommandBuffer())
+ linear.encode(commandBuffer: commandBuffer,
+ input: input, weights: weights, output: output,
+ m: m, n: n, k: k)
+ commandBuffer.commit()
+ commandBuffer.waitUntilCompleted()
+ #expect(commandBuffer.error == nil)
+ let values = output.contents().bindMemory(to: UInt16.self, capacity: m * n)
+ var maximumError: Float = 0
+ for index in 0..<(m * n) {
+ maximumError = max(
+ maximumError,
+ abs(Quantization.bf16ToFloat(values[index]) - 36))
+ }
+ #expect(maximumError == 0, "environment: \(environment)")
+ }
+ }
+
+ @Test(.enabled(if: visionMPPTensorOpsAvailable,
+ "vision linear kernels require Apple8 or newer"))
+ func registerPathHandlesNonconstantTailShape() throws {
+ let context = try MetalContext()
+ let m = 79, n = 272, k = 23
+ let inputBits = (0..<(m * k)).map { index in
+ Quantization.bf16Bits(Float((index * 17) % 31 - 15) / 32)
+ }
+ let weightBits = (0..<(n * k)).map { index in
+ Quantization.bf16Bits(Float((index * 13) % 29 - 14) / 64)
+ }
+ let inputValues = inputBits.map(Quantization.bf16ToFloat)
+ let weightValues = weightBits.map(Quantization.bf16ToFloat)
+ let input = try #require(context.device.makeBuffer(
+ bytes: inputBits,
+ length: inputBits.count * MemoryLayout<UInt16>.stride,
+ options: .storageModeShared))
+ let weights = try #require(context.device.makeBuffer(
+ bytes: weightBits,
+ length: weightBits.count * MemoryLayout<UInt16>.stride,
+ options: .storageModeShared))
+ let output = try #require(context.device.makeBuffer(
+ length: m * n * MemoryLayout<UInt16>.stride,
+ options: .storageModeShared))
+ let linear = try VisionLinearBF16(
+ context: context,
+ environment: ["TURBO_FIELDFARE_VISION_REGISTER_GEMM": "1"])
+ let commandBuffer = try #require(context.queue.makeCommandBuffer())
+ linear.encode(commandBuffer: commandBuffer,
+ input: input, weights: weights, output: output,
+ m: m, n: n, k: k)
+ commandBuffer.commit()
+ commandBuffer.waitUntilCompleted()
+ #expect(commandBuffer.error == nil)
+
+ let actual = output.contents().bindMemory(to: UInt16.self, capacity: m * n)
+ var maximumWideError: Float = 0
+ var maximumTailError: Float = 0
+ for row in 0..<m {
+ for column in 0..<n {
+ var expected: Float = 0
+ for inner in 0..<k {
+ expected += inputValues[row * k + inner] * weightValues[column * k + inner]
+ }
+ let error = abs(
+ Quantization.bf16ToFloat(actual[row * n + column]) - expected)
+ if column < 256 {
+ maximumWideError = max(maximumWideError, error)
+ } else {
+ maximumTailError = max(maximumTailError, error)
+ }
+ }
+ }
+ #expect(maximumWideError < 0.016)
+ #expect(maximumTailError < 0.016)
+ }
+
+ @Test(.enabled(if: visionMPPTensorOpsAvailable,
+ "vision linear kernels require Apple8 or newer"))
+ func registerMatchesMPPReductionAtProductionK() throws {
+ let context = try MetalContext()
+ let m = 64, n = 32, k = 1_152
+ let inputBits = (0..<(m * k)).map {
+ Quantization.bf16Bits(Float(($0 * 17) % 127 - 63) / 64)
+ }
+ let weightBits = (0..<(n * k)).map {
+ Quantization.bf16Bits(Float(($0 * 29) % 113 - 56) / 128)
+ }
+ let input = try #require(context.device.makeBuffer(
+ bytes: inputBits, length: inputBits.count * 2, options: .storageModeShared))
+ let weights = try #require(context.device.makeBuffer(
+ bytes: weightBits, length: weightBits.count * 2, options: .storageModeShared))
+ let baseline = try #require(context.device.makeBuffer(
+ length: m * n * 2, options: .storageModeShared))
+ let register = try #require(context.device.makeBuffer(
+ length: m * n * 2, options: .storageModeShared))
+
+ for (environment, output) in [
+ ([String: String](), baseline),
+ (["TURBO_FIELDFARE_VISION_REGISTER_GEMM": "1"], register),
+ ] {
+ let linear = try VisionLinearBF16(context: context, environment: environment)
+ let commandBuffer = try #require(context.queue.makeCommandBuffer())
+ linear.encode(commandBuffer: commandBuffer,
+ input: input, weights: weights, output: output,
+ m: m, n: n, k: k)
+ commandBuffer.commit()
+ commandBuffer.waitUntilCompleted()
+ #expect(commandBuffer.error == nil)
+ }
+
+ #expect(Data(bytes: baseline.contents(), count: m * n * 2)
+ == Data(bytes: register.contents(), count: m * n * 2))
+ }
+}
diff --git a/Tests/TurboFieldfare/Core/Runtime/Generation/MultimodalPrefillProgressTests.swift b/Tests/TurboFieldfare/Core/Runtime/Generation/MultimodalPrefillProgressTests.swift
new file mode 100644
index 00000000..c18210b1
--- /dev/null
+++ b/Tests/TurboFieldfare/Core/Runtime/Generation/MultimodalPrefillProgressTests.swift
@@ -0,0 +1,137 @@
+import Metal
+import Testing
+@testable import TurboFieldfare
+
+/// Progress reporting for a resumed multimodal prefill, and the two defaults it
+/// travels with. All three are review findings whose only previous evidence was
+/// that the build succeeded.
+@Suite struct MultimodalPrefillProgressTests {
+ /// A producer that prefills a multimodal suffix and reports suffix-local
+ /// progress, exactly as `RealForwardRunner` does.
+ final class MultimodalProducer: MultimodalPrefillRunner, ContinuableLogitProducer,
+ @unchecked Sendable
+ {
+ let vocabSize: Int
+ private let terminalToken: Int32
+ private(set) var continuationPosition: Int
+
+ init(vocabSize: Int, terminalToken: Int32, position: Int) {
+ self.vocabSize = vocabSize
+ self.terminalToken = terminalToken
+ self.continuationPosition = position
+ }
+
+ func reset() { continuationPosition = 0 }
+
+ func prepareForContinuation(expectedPosition: Int) throws {
+ guard continuationPosition == expectedPosition else {
+ throw PrefillError.prefillCursorMismatch("test cursor mismatch")
+ }
+ }
+
+ func produce(token: Int32, position: Int, into logits: MTLBuffer) async throws {
+ guard continuationPosition == position else {
+ throw PrefillError.prefillCursorMismatch("test scalar cursor mismatch")
+ }
+ continuationPosition += 1
+ writeTerminal(to: logits)
+ }
+
+ func prefillMultimodal(input: MultimodalPrefillInput,
+ startPosition: Int,
+ outputMode: PrefillOutputMode,
+ config: PrefillRuntimeConfig,
+ into logits: MTLBuffer,
+ onProgress: (Int) -> Void) async throws -> PrefillResult {
+ guard continuationPosition == startPosition else {
+ throw PrefillError.prefillCursorMismatch("test multimodal cursor mismatch")
+ }
+ // Suffix-local counts, one per token, as the chunked runner reports.
+ for done in 1...input.effectiveTokenIDs.count { onProgress(done) }
+ continuationPosition += input.effectiveTokenIDs.count
+ writeTerminal(to: logits)
+ return PrefillResult(newPosition: continuationPosition, seed: .logitsWritten)
+ }
+
+ private func writeTerminal(to logits: MTLBuffer) {
+ let pointer = logits.contents().bindMemory(to: Float16.self, capacity: vocabSize)
+ for index in 0..<vocabSize { pointer[index] = -30 }
+ pointer[Int(terminalToken)] = 30
+ }
+ }
+
+ private func makeInput(context: MetalContext,
+ tokenIDs: [Int32]) throws -> MultimodalPrefillInput {
+ let hidden = VisionConfig().textHiddenSize
+ let buffer = try #require(context.device.makeBuffer(
+ length: 2 * hidden * MemoryLayout<Float16>.stride,
+ options: .storageModeShared))
+ let features = VisionFeatures(
+ buffer: buffer, tokenCount: 2, hiddenSize: hidden,
+ gpuNanoseconds: 0, scratchBytes: 0,
+ attentionVariant: .native72Q16, projectorPath: .fallback,
+ expertResidencyTransition: nil, preprocessing: nil)
+ var embedding = tokenIDs
+ embedding[1] = 0
+ embedding[2] = 0
+ return try MultimodalPrefillInput(
+ effectiveTokenIDs: tokenIDs,
+ embeddingTokenIDs: embedding,
+ imageSpans: [MultimodalImageSpan(tokenRange: 1..<3, features: features)])
+ }
+
+ /// A resumed image turn must report progress against the whole prompt. The
+ /// producer counts only the suffix it prefills, so without the cached offset
+ /// a 4-token image turn on a 5,000-token KV reported "1 of 5,004" and the
+ /// bar restarted from zero on every turn.
+ @Test func resumedMultimodalProgressCountsTheCachedPrefix() async throws {
+ let context = try MetalContext()
+ let tokenizer = try await GFTokenizer.load()
+ let cached = 6
+ let suffix: [Int32] = [40, 41, 42, 43]
+ let promptIds: [Int32] = Array(repeating: 7, count: cached) + suffix
+ let terminal = tokenizer.eosID
+ let producer = MultimodalProducer(
+ vocabSize: 64, terminalToken: terminal, position: cached)
+ let scratch = try RawCompletionScratch(context: context, vocab: 64)
+ var config = GenerationConfig(maxNewTokens: 2, temperature: 0)
+ config.stopStrings = []
+
+ var prefillProgress: [(done: Int, total: Int)] = []
+ _ = try await runRawCompletion(
+ producer: producer,
+ tokenizer: tokenizer,
+ promptIds: promptIds,
+ multimodalInput: try makeInput(context: context, tokenIDs: suffix),
+ config: config,
+ context: context,
+ scratch: scratch,
+ prefillConfig: .production(chunkTokens: 32),
+ start: .resume(cachedPromptTokens: cached)
+ ) { progress in
+ if case .prefill(let done, let total) = progress {
+ prefillProgress.append((done, total))
+ }
+ }
+
+ #expect(prefillProgress.map(\.done) == [7, 8, 9, 10],
+ "progress ignored the \(cached) cached tokens: \(prefillProgress.map(\.done))")
+ #expect(prefillProgress.allSatisfy { $0.total == promptIds.count })
+ #expect(prefillProgress.last?.done == promptIds.count,
+ "prefill finished below its own total")
+ // Monotonic, and never above the total — a bar that goes backwards or
+ // past the end is what the user actually sees.
+ #expect(zip(prefillProgress, prefillProgress.dropFirst())
+ .allSatisfy { $0.done < $1.done })
+ #expect(prefillProgress.allSatisfy { $0.done <= $0.total })
+ }
+
+ /// Every entry point must default to the same residency. The conversation's
+ /// default had drifted to `keepReady`, which pins ~1.1 GB of tower mappings
+ /// for the life of the process while the CLI released them.
+ @Test func everyEntryPointDefaultsToTheSameResidency() {
+ #expect(VisionResidencyPolicy.defaultPolicy == .onDemand)
+ #expect(VisionResidencyPolicy(rawValue: "keep-ready") == .keepReady,
+ "the opt-in policy is still spelled keep-ready")
+ }
+}
diff --git a/Tests/TurboFieldfare/Core/Runtime/Generation/RawCompletionLoopTests+Cancellation.swift b/Tests/TurboFieldfare/Core/Runtime/Generation/RawCompletionLoopTests+Cancellation.swift
index bb6b3691..6a418eca 100644
--- a/Tests/TurboFieldfare/Core/Runtime/Generation/RawCompletionLoopTests+Cancellation.swift
+++ b/Tests/TurboFieldfare/Core/Runtime/Generation/RawCompletionLoopTests+Cancellation.swift
@@ -33,4 +33,46 @@ extension RawCompletionLoopTests {
_ = try await task.value
}
}
+
+ /// A caller that asks the loop to stop is not a stop-string match. Reporting
+ /// it as one made a user pressing Stop indistinguishable from a configured
+ /// stop string, and it disagreed with `stopStringFiltered`, which the server
+ /// computes from the matcher rather than from the reason.
+ @Test func askingTheLoopToStopIsReportedAsCancelledNotAsAStopString() async throws {
+ let ctx = try MetalContext()
+ let tok = try await GFTokenizer.load()
+ let idA = tok.encode("a", addBOS: false).first!
+ let scratch = try RawCompletionScratch(context: ctx, vocab: tok.vocabSize)
+ let promptIds = tok.encode("go", addBOS: true)
+
+ var produced = 0
+ let cancelled = try await runRawCompletion(
+ producer: ScriptedLogitProducer(
+ vocabSize: tok.vocabSize, step: automaton([idA, idA, idA], end: idA)),
+ tokenizer: tok,
+ promptIds: promptIds,
+ config: GenerationConfig(maxNewTokens: 100_000, temperature: 0),
+ context: ctx, scratch: scratch, prefillConfig: .off,
+ shouldStop: { produced >= 2 }
+ ) { progress in
+ if case .token = progress { produced += 1 }
+ }
+ #expect(cancelled.reason == .cancelled)
+ #expect(cancelled.newTokens >= 2)
+
+ // A real stop string still reports itself, so the two stay distinguishable.
+ var config = GenerationConfig(maxNewTokens: 100_000, temperature: 0)
+ config = GenerationConfig(
+ maxNewTokens: 100_000, temperature: 0, stopStrings: ["a"])
+ let stopped = try await runRawCompletion(
+ producer: ScriptedLogitProducer(
+ vocabSize: tok.vocabSize, step: automaton([idA, idA, idA], end: idA)),
+ tokenizer: tok,
+ promptIds: promptIds,
+ config: config,
+ context: ctx, scratch: try RawCompletionScratch(context: ctx, vocab: tok.vocabSize),
+ prefillConfig: .off
+ ) { _ in }
+ #expect(stopped.reason == .stopString)
+ }
}
diff --git a/Tests/TurboFieldfare/Core/Runtime/Prefill/PrefillChunkScratchTests.swift b/Tests/TurboFieldfare/Core/Runtime/Prefill/PrefillChunkScratchTests.swift
index d977ec46..b3205e56 100644
--- a/Tests/TurboFieldfare/Core/Runtime/Prefill/PrefillChunkScratchTests.swift
+++ b/Tests/TurboFieldfare/Core/Runtime/Prefill/PrefillChunkScratchTests.swift
@@ -32,7 +32,36 @@ import Metal
@Test func layoutClampsChunkSizeToRuntimeBounds() {
#expect(PrefillChunkScratchLayout(config: .gemma4_26B_A4B, chunkTokens: 0).chunkTokens == 1)
- #expect(PrefillChunkScratchLayout(config: .gemma4_26B_A4B, chunkTokens: 512).chunkTokens == 128)
+ // The ceiling is 256: every size up to the 280-token pooled image span
+ // produces identical ring geometry, so 256 costs nothing the image path
+ // was not already paying. 512 is the first size that would.
+ #expect(PrefillChunkScratchLayout(config: .gemma4_26B_A4B, chunkTokens: 512).chunkTokens
+ == PrefillRuntimeConfig.maxChunkTokens)
+ #expect(PrefillRuntimeConfig.maxChunkTokens == 256)
+ #expect(PrefillChunkScratchLayout(config: .gemma4_26B_A4B, chunkTokens: 256).chunkTokens == 256)
+ }
+
+ /// `auto` asks for the smallest allowed chunk that covers the prompt,
+ /// because one chunk means each layer's experts are read once - the floor.
+ @Test func autoPicksTheSmallestChunkThatCoversThePrompt() {
+ #expect(PrefillRuntimeConfig.autoChunkTokens(promptTokens: 20) == 32)
+ #expect(PrefillRuntimeConfig.autoChunkTokens(promptTokens: 32) == 32)
+ #expect(PrefillRuntimeConfig.autoChunkTokens(promptTokens: 33) == 64)
+ #expect(PrefillRuntimeConfig.autoChunkTokens(promptTokens: 200) == 256)
+ // Beyond the ceiling it saturates rather than inventing a size.
+ #expect(PrefillRuntimeConfig.autoChunkTokens(promptTokens: 7_019) == 256)
+ // A cap below the ceiling is honoured, so a caller can stay smaller.
+ #expect(PrefillRuntimeConfig.autoChunkTokens(promptTokens: 7_019, cap: 64) == 64)
+ }
+
+ /// The env door and the flag door have to agree on what is legal.
+ @Test func requestedChunkSizesSnapToTheAllowedList() {
+ #expect(PrefillRuntimeConfig.supportedChunkTokens(999) == 256)
+ #expect(PrefillRuntimeConfig.supportedChunkTokens(200) == 128)
+ #expect(PrefillRuntimeConfig.supportedChunkTokens(64) == 64)
+ // Below the smallest allowed size there is nothing to snap to, so it
+ // floors at one token rather than inventing 32.
+ #expect(PrefillRuntimeConfig.supportedChunkTokens(0) == 1)
}
@Test func allocationUsesPrivateScratchAndSharedRouteMetadata() throws {
@@ -81,4 +110,16 @@ import Metal
#expect(scratch.routeIDs.storageMode == MTLStorageMode.shared)
#expect(scratch.routeWeights.storageMode == MTLStorageMode.shared)
}
+
+ @Test func multimodalBlockScratchStaysInsideBoundedBudget() {
+ let tokens = VisionConfig().maximumPooledTokens
+ let layout = PrefillChunkScratchLayout(
+ config: .gemma4_26B_A4B,
+ chunkTokens: tokens,
+ chunkTokenLimit: tokens)
+
+ #expect(layout.chunkTokens == 280)
+ #expect(layout.totalPersistentBytes < 100 * 1_048_576)
+ }
+
}
diff --git a/Tests/TurboFieldfare/Core/Runtime/Prefill/PrefillSpanIterationTests.swift b/Tests/TurboFieldfare/Core/Runtime/Prefill/PrefillSpanIterationTests.swift
new file mode 100644
index 00000000..ca85e2a6
--- /dev/null
+++ b/Tests/TurboFieldfare/Core/Runtime/Prefill/PrefillSpanIterationTests.swift
@@ -0,0 +1,51 @@
+import Synchronization
+import Testing
+@testable import TurboFieldfare
+
+/// The cancellation guard for chunked text prefill. It lives here rather than
+/// inline in `RealForwardRunner` because the runner's protocol seam is
+/// `prefillChunked` itself, so every test double replaces the loop under test and
+/// nothing in the suite could reach it. The defect this pins was found by timing
+/// an interrupt by hand.
+@Suite struct PrefillSpanIterationTests {
+ private func spans(_ count: Int) -> [PrefillChunkSpan] {
+ (0..<count).map {
+ PrefillChunkSpan(tokenOffset: $0 * 128,
+ tokenCount: 128,
+ startPosition: $0 * 128,
+ completedCount: $0 * 128)
+ }
+ }
+
+ @Test func everySpanRunsWhenNothingCancels() async throws {
+ var seen: [Int] = []
+ try await PrefillSpanIteration.forEachSpan(spans(5)) { index, _ in
+ seen.append(index)
+ }
+ #expect(seen == [0, 1, 2, 3, 4])
+ }
+
+ /// The poll happens *before* a span, never during one. A chunk's GPU work
+ /// does not observe cancellation, so the loop must not be expected to abandon
+ /// it midway - which is why the measured latency after the fix is one chunk
+ /// rather than zero. Modelled with a body that ignores cancellation, because
+ /// `Task.sleep` does not: an earlier version of this test used `sleep` and so
+ /// asserted a property of the body rather than of the loop.
+ @Test func cancellationStopsTheLoopAndLetsTheSpanInFlightFinish() async throws {
+ let finished = Mutex(0)
+ let task = Task {
+ try await PrefillSpanIteration.forEachSpan(spans(50)) { _, _ in
+ var sink = 0
+ for i in 0..<2_000_000 { sink &+= i }
+ finished.withLock { $0 += 1 &+ (sink & 0) }
+ }
+ }
+ try await Task.sleep(nanoseconds: 5_000_000)
+ task.cancel()
+ _ = try? await task.value
+
+ let completed = finished.withLock { $0 }
+ #expect(completed > 0, "no span completed, so the loop bailed before doing work")
+ #expect(completed < 50, "cancellation did not stop the loop")
+ }
+}
diff --git a/Tests/TurboFieldfare/Core/Runtime/Vision/Fixtures/images/corpus.json b/Tests/TurboFieldfare/Core/Runtime/Vision/Fixtures/images/corpus.json
new file mode 100644
index 00000000..b8f3ebb3
--- /dev/null
+++ b/Tests/TurboFieldfare/Core/Runtime/Vision/Fixtures/images/corpus.json
@@ -0,0 +1,271 @@
+{
+ "cases": [
+ {
+ "encoded_bytes": 469012,
+ "encoded_height": 641,
+ "encoded_mode": "RGB",
+ "encoded_width": 641,
+ "file": "natural-square.png",
+ "grid_height": 48,
+ "grid_width": 48,
+ "id": "natural-square",
+ "orientation": 1,
+ "patches": 2304,
+ "processed_height": 768,
+ "processed_width": 768,
+ "quality_endpoint": true,
+ "sha256": "509868e60adbf510f3f8ca0707cf800923046763e267dd780fcb21d04ed377d5",
+ "tokens": 256
+ },
+ {
+ "encoded_bytes": 87680,
+ "encoded_height": 479,
+ "encoded_mode": "RGB",
+ "encoded_width": 641,
+ "file": "natural-odd-4x3.jpg",
+ "grid_height": 42,
+ "grid_width": 57,
+ "id": "natural-odd-4x3",
+ "orientation": 1,
+ "patches": 2394,
+ "processed_height": 672,
+ "processed_width": 912,
+ "quality_endpoint": true,
+ "sha256": "74de788bb77c1909b1d23fcda393e3dec0758cd4b5d1f04aff69045f1a323532",
+ "tokens": 266
+ },
+ {
+ "encoded_bytes": 95541,
+ "encoded_height": 853,
+ "encoded_mode": "RGB",
+ "encoded_width": 479,
+ "file": "natural-portrait.jpg",
+ "grid_height": 66,
+ "grid_width": 36,
+ "id": "natural-portrait",
+ "orientation": 1,
+ "patches": 2376,
+ "processed_height": 1056,
+ "processed_width": 576,
+ "quality_endpoint": true,
+ "sha256": "a0a90043b8888e8b33f3120b69627c6417e260ba60dc6df9ce1b3aebda4d5ef7",
+ "tokens": 264
+ },
+ {
+ "encoded_bytes": 83644,
+ "encoded_height": 257,
+ "encoded_mode": "RGB",
+ "encoded_width": 1537,
+ "file": "natural-panorama.jpg",
+ "grid_height": 18,
+ "grid_width": 120,
+ "id": "natural-panorama",
+ "orientation": 1,
+ "patches": 2160,
+ "processed_height": 288,
+ "processed_width": 1920,
+ "quality_endpoint": true,
+ "sha256": "a2af57b570d402b5c0f956fa3b7401aa060c4d2b882f02d27c716982e8356fae",
+ "tokens": 240
+ },
+ {
+ "encoded_bytes": 512412,
+ "encoded_height": 641,
+ "encoded_mode": "RGBA",
+ "encoded_width": 641,
+ "file": "natural-alpha.png",
+ "grid_height": 48,
+ "grid_width": 48,
+ "id": "natural-alpha",
+ "orientation": 1,
+ "patches": 2304,
+ "processed_height": 768,
+ "processed_width": 768,
+ "quality_endpoint": true,
+ "sha256": "ef4a3a43e6b7537e8961f5ece897e3cfce628fb0982de80a2a7d7fa555791095",
+ "tokens": 256
+ },
+ {
+ "encoded_bytes": 203500,
+ "encoded_height": 641,
+ "encoded_mode": "L",
+ "encoded_width": 641,
+ "file": "natural-grayscale.png",
+ "grid_height": 48,
+ "grid_width": 48,
+ "id": "natural-grayscale",
+ "orientation": 1,
+ "patches": 2304,
+ "processed_height": 768,
+ "processed_width": 768,
+ "quality_endpoint": true,
+ "sha256": "e752e557d3d9e6aabce96d069230258d3b4d2088ba928e5c21ff266b039f6f79",
+ "tokens": 256
+ },
+ {
+ "encoded_bytes": 110946,
+ "encoded_height": 641,
+ "encoded_mode": "RGB",
+ "encoded_width": 641,
+ "file": "natural-display-p3.jpg",
+ "grid_height": 48,
+ "grid_width": 48,
+ "id": "natural-display-p3",
+ "orientation": 1,
+ "patches": 2304,
+ "processed_height": 768,
+ "processed_width": 768,
+ "quality_endpoint": true,
+ "sha256": "a97a6049d3261096072fa948c58cc96e85684b408f4dbc81f496642717dae99b",
+ "tokens": 256
+ },
+ {
+ "encoded_bytes": 22059,
+ "encoded_height": 193,
+ "encoded_mode": "RGB",
+ "encoded_width": 321,
+ "file": "natural-exif-1.jpg",
+ "grid_height": 36,
+ "grid_width": 63,
+ "id": "natural-exif-1",
+ "orientation": 1,
+ "patches": 2268,
+ "processed_height": 576,
+ "processed_width": 1008,
+ "quality_endpoint": false,
+ "sha256": "50544c966213a137ac1de2c4faebc2a2dd3b6431fb6d1c6162724ac9718fb989",
+ "tokens": 252
+ },
+ {
+ "encoded_bytes": 22018,
+ "encoded_height": 193,
+ "encoded_mode": "RGB",
+ "encoded_width": 321,
+ "file": "natural-exif-2.jpg",
+ "grid_height": 36,
+ "grid_width": 63,
+ "id": "natural-exif-2",
+ "orientation": 2,
+ "patches": 2268,
+ "processed_height": 576,
+ "processed_width": 1008,
+ "quality_endpoint": false,
+ "sha256": "ab67e43b8b5b6ecf530475d883353eef41d07173d72650a1511914de7701e7a1",
+ "tokens": 252
+ },
+ {
+ "encoded_bytes": 21953,
+ "encoded_height": 193,
+ "encoded_mode": "RGB",
+ "encoded_width": 321,
+ "file": "natural-exif-3.jpg",
+ "grid_height": 36,
+ "grid_width": 63,
+ "id": "natural-exif-3",
+ "orientation": 3,
+ "patches": 2268,
+ "processed_height": 576,
+ "processed_width": 1008,
+ "quality_endpoint": false,
+ "sha256": "3bac20e081ee62456c9970f8c82b6bae653febdba9955df3ab0756ea12c2403d",
+ "tokens": 252
+ },
+ {
+ "encoded_bytes": 22053,
+ "encoded_height": 193,
+ "encoded_mode": "RGB",
+ "encoded_width": 321,
+ "file": "natural-exif-4.jpg",
+ "grid_height": 36,
+ "grid_width": 63,
+ "id": "natural-exif-4",
+ "orientation": 4,
+ "patches": 2268,
+ "processed_height": 576,
+ "processed_width": 1008,
+ "quality_endpoint": false,
+ "sha256": "2881d3e7077c9435d54a1c0e792d5f57adc7e3526dfbd6f59dd1ca5a34a70611",
+ "tokens": 252
+ },
+ {
+ "encoded_bytes": 22030,
+ "encoded_height": 321,
+ "encoded_mode": "RGB",
+ "encoded_width": 193,
+ "file": "natural-exif-5.jpg",
+ "grid_height": 36,
+ "grid_width": 63,
+ "id": "natural-exif-5",
+ "orientation": 5,
+ "patches": 2268,
+ "processed_height": 576,
+ "processed_width": 1008,
+ "quality_endpoint": false,
+ "sha256": "50186ad8cf2a2ceb4c22576e2ca395dbfc97c574e950e763083a5d3d891a1a69",
+ "tokens": 252
+ },
+ {
+ "encoded_bytes": 21974,
+ "encoded_height": 321,
+ "encoded_mode": "RGB",
+ "encoded_width": 193,
+ "file": "natural-exif-6.jpg",
+ "grid_height": 36,
+ "grid_width": 63,
+ "id": "natural-exif-6",
+ "orientation": 6,
+ "patches": 2268,
+ "processed_height": 576,
+ "processed_width": 1008,
+ "quality_endpoint": false,
+ "sha256": "25233efe3547a9ae99b96ce210c6dde16223dde47adfa2ca6dd211da9f6cd143",
+ "tokens": 252
+ },
+ {
+ "encoded_bytes": 21858,
+ "encoded_height": 321,
+ "encoded_mode": "RGB",
+ "encoded_width": 193,
+ "file": "natural-exif-7.jpg",
+ "grid_height": 36,
+ "grid_width": 63,
+ "id": "natural-exif-7",
+ "orientation": 7,
+ "patches": 2268,
+ "processed_height": 576,
+ "processed_width": 1008,
+ "quality_endpoint": false,
+ "sha256": "4284eb6e38704148dfd230d6f65ddeb323e1b5b66faf51a65aaee27dbd3ce480",
+ "tokens": 252
+ },
+ {
+ "encoded_bytes": 21944,
+ "encoded_height": 321,
+ "encoded_mode": "RGB",
+ "encoded_width": 193,
+ "file": "natural-exif-8.jpg",
+ "grid_height": 36,
+ "grid_width": 63,
+ "id": "natural-exif-8",
+ "orientation": 8,
+ "patches": 2268,
+ "processed_height": 576,
+ "processed_width": 1008,
+ "quality_endpoint": false,
+ "sha256": "a856424b997b0ba0163b94e1381a9739263221b2ad83e517f6d6c50ed6128703",
+ "tokens": 252
+ }
+ ],
+ "generator": "Scripts/Vision/generate_quality_images.py",
+ "pillow_version": "11.3.0",
+ "policy": "EXIF-transpose, ICC-to-sRGB, opaque-white alpha composite",
+ "schema_version": 1,
+ "source": {
+ "file": "nasa-pia21216.jpg",
+ "license_note": "NASA imagery; see NASA Media Usage Guidelines",
+ "license_url": "https://www.nasa.gov/nasa-brand-center/images-and-media/",
+ "sha256": "02cb3b3c6abb95fe379d474dfba3b4c577e2ed5c871b3f16003b2a7c9d019e29",
+ "url": "https://images-assets.nasa.gov/image/PIA21216/PIA21216~medium.jpg"
+ },
+ "transformers_revision": "d09f53a801f45ad73ec3510e17972024234bc0fd"
+}
diff --git a/Tests/TurboFieldfare/Core/Runtime/Vision/Fixtures/images/nasa-pia21216.jpg b/Tests/TurboFieldfare/Core/Runtime/Vision/Fixtures/images/nasa-pia21216.jpg
new file mode 100644
index 00000000..fd67f865
Binary files /dev/null and b/Tests/TurboFieldfare/Core/Runtime/Vision/Fixtures/images/nasa-pia21216.jpg differ
diff --git a/Tests/TurboFieldfare/Core/Runtime/Vision/Fixtures/images/natural-alpha.png b/Tests/TurboFieldfare/Core/Runtime/Vision/Fixtures/images/natural-alpha.png
new file mode 100644
index 00000000..d3691aac
Binary files /dev/null and b/Tests/TurboFieldfare/Core/Runtime/Vision/Fixtures/images/natural-alpha.png differ
diff --git a/Tests/TurboFieldfare/Core/Runtime/Vision/Fixtures/images/natural-display-p3.jpg b/Tests/TurboFieldfare/Core/Runtime/Vision/Fixtures/images/natural-display-p3.jpg
new file mode 100644
index 00000000..d84d24e7
Binary files /dev/null and b/Tests/TurboFieldfare/Core/Runtime/Vision/Fixtures/images/natural-display-p3.jpg differ
diff --git a/Tests/TurboFieldfare/Core/Runtime/Vision/Fixtures/images/natural-exif-1.jpg b/Tests/TurboFieldfare/Core/Runtime/Vision/Fixtures/images/natural-exif-1.jpg
new file mode 100644
index 00000000..670ed675
Binary files /dev/null and b/Tests/TurboFieldfare/Core/Runtime/Vision/Fixtures/images/natural-exif-1.jpg differ
diff --git a/Tests/TurboFieldfare/Core/Runtime/Vision/Fixtures/images/natural-exif-2.jpg b/Tests/TurboFieldfare/Core/Runtime/Vision/Fixtures/images/natural-exif-2.jpg
new file mode 100644
index 00000000..d99ef25e
Binary files /dev/null and b/Tests/TurboFieldfare/Core/Runtime/Vision/Fixtures/images/natural-exif-2.jpg differ
diff --git a/Tests/TurboFieldfare/Core/Runtime/Vision/Fixtures/images/natural-exif-3.jpg b/Tests/TurboFieldfare/Core/Runtime/Vision/Fixtures/images/natural-exif-3.jpg
new file mode 100644
index 00000000..bd1fd4c2
Binary files /dev/null and b/Tests/TurboFieldfare/Core/Runtime/Vision/Fixtures/images/natural-exif-3.jpg differ
diff --git a/Tests/TurboFieldfare/Core/Runtime/Vision/Fixtures/images/natural-exif-4.jpg b/Tests/TurboFieldfare/Core/Runtime/Vision/Fixtures/images/natural-exif-4.jpg
new file mode 100644
index 00000000..003a178e
Binary files /dev/null and b/Tests/TurboFieldfare/Core/Runtime/Vision/Fixtures/images/natural-exif-4.jpg differ
diff --git a/Tests/TurboFieldfare/Core/Runtime/Vision/Fixtures/images/natural-exif-5.jpg b/Tests/TurboFieldfare/Core/Runtime/Vision/Fixtures/images/natural-exif-5.jpg
new file mode 100644
index 00000000..948d2db7
Binary files /dev/null and b/Tests/TurboFieldfare/Core/Runtime/Vision/Fixtures/images/natural-exif-5.jpg differ
diff --git a/Tests/TurboFieldfare/Core/Runtime/Vision/Fixtures/images/natural-exif-6.jpg b/Tests/TurboFieldfare/Core/Runtime/Vision/Fixtures/images/natural-exif-6.jpg
new file mode 100644
index 00000000..facc9f2a
Binary files /dev/null and b/Tests/TurboFieldfare/Core/Runtime/Vision/Fixtures/images/natural-exif-6.jpg differ
diff --git a/Tests/TurboFieldfare/Core/Runtime/Vision/Fixtures/images/natural-exif-7.jpg b/Tests/TurboFieldfare/Core/Runtime/Vision/Fixtures/images/natural-exif-7.jpg
new file mode 100644
index 00000000..fb2e6ed4
Binary files /dev/null and b/Tests/TurboFieldfare/Core/Runtime/Vision/Fixtures/images/natural-exif-7.jpg differ
diff --git a/Tests/TurboFieldfare/Core/Runtime/Vision/Fixtures/images/natural-exif-8.jpg b/Tests/TurboFieldfare/Core/Runtime/Vision/Fixtures/images/natural-exif-8.jpg
new file mode 100644
index 00000000..338adc24
Binary files /dev/null and b/Tests/TurboFieldfare/Core/Runtime/Vision/Fixtures/images/natural-exif-8.jpg differ
diff --git a/Tests/TurboFieldfare/Core/Runtime/Vision/Fixtures/images/natural-grayscale.png b/Tests/TurboFieldfare/Core/Runtime/Vision/Fixtures/images/natural-grayscale.png
new file mode 100644
index 00000000..f6c3c25e
Binary files /dev/null and b/Tests/TurboFieldfare/Core/Runtime/Vision/Fixtures/images/natural-grayscale.png differ
diff --git a/Tests/TurboFieldfare/Core/Runtime/Vision/Fixtures/images/natural-odd-4x3.jpg b/Tests/TurboFieldfare/Core/Runtime/Vision/Fixtures/images/natural-odd-4x3.jpg
new file mode 100644
index 00000000..f7d1ced3
Binary files /dev/null and b/Tests/TurboFieldfare/Core/Runtime/Vision/Fixtures/images/natural-odd-4x3.jpg differ
diff --git a/Tests/TurboFieldfare/Core/Runtime/Vision/Fixtures/images/natural-panorama.jpg b/Tests/TurboFieldfare/Core/Runtime/Vision/Fixtures/images/natural-panorama.jpg
new file mode 100644
index 00000000..482332a5
Binary files /dev/null and b/Tests/TurboFieldfare/Core/Runtime/Vision/Fixtures/images/natural-panorama.jpg differ
diff --git a/Tests/TurboFieldfare/Core/Runtime/Vision/Fixtures/images/natural-portrait.jpg b/Tests/TurboFieldfare/Core/Runtime/Vision/Fixtures/images/natural-portrait.jpg
new file mode 100644
index 00000000..5d552054
Binary files /dev/null and b/Tests/TurboFieldfare/Core/Runtime/Vision/Fixtures/images/natural-portrait.jpg differ
diff --git a/Tests/TurboFieldfare/Core/Runtime/Vision/Fixtures/images/natural-square.png b/Tests/TurboFieldfare/Core/Runtime/Vision/Fixtures/images/natural-square.png
new file mode 100644
index 00000000..d351e40b
Binary files /dev/null and b/Tests/TurboFieldfare/Core/Runtime/Vision/Fixtures/images/natural-square.png differ
diff --git a/Tests/TurboFieldfare/Core/Runtime/Vision/ImagePrefillCoercionTests.swift b/Tests/TurboFieldfare/Core/Runtime/Vision/ImagePrefillCoercionTests.swift
new file mode 100644
index 00000000..ab5ed4dc
--- /dev/null
+++ b/Tests/TurboFieldfare/Core/Runtime/Vision/ImagePrefillCoercionTests.swift
@@ -0,0 +1,71 @@
+import Testing
+
+@testable import TurboFieldfare
+
+/// Image spans are only served by the chunked multimodal path. Prefill mode is
+/// a performance choice; whether images work at all is not, so an image turn is
+/// coerced rather than refused after every image has already been encoded.
+@Suite struct ImagePrefillCoercionTests {
+ @Test func anImagePromptCoercesPrefillOffToChunked() {
+ let off = PrefillRuntimeConfig.off
+ #expect(!off.servesImagePrompt)
+
+ let coerced = try? #require(off.coercedForImagePrompt())
+ #expect(coerced?.mode == .chunked)
+ #expect(coerced?.servesImagePrompt == true)
+ }
+
+ @Test func aChunkedConfigIsAlreadyFineAndIsNotRewritten() {
+ let chunked = PrefillRuntimeConfig.defaultChunked
+ #expect(chunked.servesImagePrompt)
+ // nil means "already runs", not "cannot run".
+ #expect(chunked.coercedForImagePrompt() == nil)
+ }
+
+ @Test func everySelectableChunkSizeStillServesImages() {
+ for tokens in RuntimeConfiguration.allowedPrefillChunkTokens {
+ let config = PrefillRuntimeConfig.production(chunkTokens: tokens)
+ #expect(config.servesImagePrompt,
+ "chunk size \(tokens) must serve an image prompt")
+ #expect(config.coercedForImagePrompt() == nil)
+ }
+ }
+
+ /// The planner cuts text at the same clamp the scratch layout applies. A
+ /// caller that asks for more must not hand the buffer a larger chunk than
+ /// it was sized for.
+ @Test func multimodalTextChunksNeverExceedTheScratchClamp() {
+ let work = PrefillChunkPlanner.multimodalWork(
+ tokenCount: 1_000,
+ imageRanges: [400..<680],
+ chunkTokens: 4_096)
+ let textItems = work.filter { !$0.isImage }
+ #expect(!textItems.isEmpty)
+ for item in textItems {
+ #expect(item.range.count <= PrefillRuntimeConfig.maxChunkTokens)
+ }
+ }
+
+ /// An image span is one indivisible block: its features are projected as a
+ /// unit, so the planner must never split it even when it exceeds the clamp.
+ @Test func anImageSpanPassesThroughWholeEvenWhenItExceedsTheClamp() {
+ let span = 400..<680
+ let work = PrefillChunkPlanner.multimodalWork(
+ tokenCount: 1_000, imageRanges: [span], chunkTokens: 128)
+ let images = work.filter(\.isImage)
+ #expect(images.count == 1)
+ #expect(images.first?.range == span)
+ #expect(span.count > PrefillRuntimeConfig.maxChunkTokens)
+ }
+
+ @Test func workItemsCoverTheWholePromptInOrder() {
+ let work = PrefillChunkPlanner.multimodalWork(
+ tokenCount: 500, imageRanges: [10..<40, 200..<260], chunkTokens: 64)
+ #expect(work.first?.range.lowerBound == 0)
+ #expect(work.last?.range.upperBound == 500)
+ for (previous, next) in zip(work, work.dropFirst()) {
+ #expect(previous.range.upperBound == next.range.lowerBound)
+ }
+ #expect(work.filter(\.isImage).map(\.range) == [10..<40, 200..<260])
+ }
+}
diff --git a/Tests/TurboFieldfare/Core/Runtime/Vision/MultimodalPrefillInputTests.swift b/Tests/TurboFieldfare/Core/Runtime/Vision/MultimodalPrefillInputTests.swift
new file mode 100644
index 00000000..94c3e0be
--- /dev/null
+++ b/Tests/TurboFieldfare/Core/Runtime/Vision/MultimodalPrefillInputTests.swift
@@ -0,0 +1,83 @@
+import Metal
+import Testing
+@testable import TurboFieldfare
+
+@Suite struct MultimodalPrefillInputTests {
+ @Test func validatesProjectedFeatureShapeAndDualTokenStreams() throws {
+ let context = try MetalContext()
+ let rows = 4
+ let bytes = rows * VisionConfig().textHiddenSize * MemoryLayout<Float16>.stride
+ let buffer = try #require(context.device.makeBuffer(
+ length: bytes,
+ options: .storageModePrivate))
+ let features = VisionFeatures(
+ buffer: buffer,
+ tokenCount: rows,
+ hiddenSize: VisionConfig().textHiddenSize,
+ gpuNanoseconds: 0,
+ scratchBytes: bytes,
+ attentionVariant: .native72Q16,
+ projectorPath: .affineThreadgroupF16,
+ expertResidencyTransition: nil,
+ preprocessing: nil)
+
+ let input = try MultimodalPrefillInput(
+ effectiveTokenIDs: [10, 20, 20, 20, 20, 30],
+ embeddingTokenIDs: [10, 0, 0, 0, 0, 30],
+ imageTokenRange: 1..<5,
+ imageFeatures: features)
+
+ #expect(input.imageTokenRange == 1..<5)
+ #expect(input.effectiveTokenIDs[1] == 20)
+ #expect(input.embeddingTokenIDs[1] == 0)
+ }
+
+ @Test func rejectsFeatureTokenCountMismatch() throws {
+ let context = try MetalContext()
+ let buffer = try #require(context.device.makeBuffer(
+ length: 3 * VisionConfig().textHiddenSize * MemoryLayout<Float16>.stride,
+ options: .storageModePrivate))
+ let features = VisionFeatures(
+ buffer: buffer,
+ tokenCount: 3,
+ hiddenSize: VisionConfig().textHiddenSize,
+ gpuNanoseconds: 0,
+ scratchBytes: buffer.length,
+ attentionVariant: .native72Q16,
+ projectorPath: .affineThreadgroupF16,
+ expertResidencyTransition: nil,
+ preprocessing: nil)
+
+ #expect(throws: MultimodalPrefillInputError.featureShapeMismatch) {
+ try MultimodalPrefillInput(
+ effectiveTokenIDs: [10, 20, 20, 30],
+ embeddingTokenIDs: [10, 0, 0, 30],
+ imageTokenRange: 1..<3,
+ imageFeatures: features)
+ }
+ }
+
+ @Test func acceptsOrderedNonOverlappingImageSpans() throws {
+ let context = try MetalContext()
+ func features(_ rows: Int) throws -> VisionFeatures {
+ let bytes = rows * VisionConfig().textHiddenSize * MemoryLayout<Float16>.stride
+ let buffer = try #require(context.device.makeBuffer(
+ length: bytes, options: .storageModePrivate))
+ return VisionFeatures(
+ buffer: buffer, tokenCount: rows,
+ hiddenSize: VisionConfig().textHiddenSize,
+ gpuNanoseconds: 0, scratchBytes: bytes,
+ attentionVariant: .native72Q16,
+ projectorPath: .affineThreadgroupF16,
+ expertResidencyTransition: nil, preprocessing: nil)
+ }
+ let input = try MultimodalPrefillInput(
+ effectiveTokenIDs: [1, 2, 2, 3, 4, 4, 4, 5],
+ embeddingTokenIDs: [1, 0, 0, 3, 0, 0, 0, 5],
+ imageSpans: [
+ MultimodalImageSpan(tokenRange: 1..<3, features: try features(2)),
+ MultimodalImageSpan(tokenRange: 4..<7, features: try features(3)),
+ ])
+ #expect(input.imageSpans.map(\.tokenRange) == [1..<3, 4..<7])
+ }
+}
diff --git a/Tests/TurboFieldfare/Core/Runtime/Vision/MultimodalPrefillRegressionTests.swift b/Tests/TurboFieldfare/Core/Runtime/Vision/MultimodalPrefillRegressionTests.swift
new file mode 100644
index 00000000..318ddbb0
--- /dev/null
+++ b/Tests/TurboFieldfare/Core/Runtime/Vision/MultimodalPrefillRegressionTests.swift
@@ -0,0 +1,299 @@
+import Foundation
+import CoreGraphics
+import ImageIO
+import UniformTypeIdentifiers
+import Testing
+@testable import TurboFieldfare
+
+/// Regressions from the PR review of this branch. Every one of them is a
+/// second call, a resumed turn, or a shape the fixtures never had — which is
+/// exactly what the suite did not cover.
+@Suite struct MultimodalPrefillRegressionTests {
+ let tok: GFTokenizer
+
+ init() async throws {
+ self.tok = try await GFTokenizer.load()
+ }
+
+ /// A turn that has to replay a boundary token must keep its image spans,
+ /// shifted to match. The old code passed no multimodal input at all when a
+ /// boundary was present, so the image tokens embedded as ordinary vocab and
+ /// the model answered about an image it never saw.
+ @Test func prependingShiftsSpansAndKeepsThem() throws {
+ let context = try MetalContext()
+ // The initializer checks the features match the span exactly, so this
+ // has to be a real two-token slab at the model's hidden size.
+ let hidden = VisionConfig().textHiddenSize
+ let buffer = try #require(context.device.makeBuffer(
+ length: 2 * hidden * MemoryLayout<Float16>.stride,
+ options: .storageModeShared))
+ let features = VisionFeatures(
+ buffer: buffer, tokenCount: 2, hiddenSize: hidden,
+ gpuNanoseconds: 0, scratchBytes: 0,
+ attentionVariant: .native72Q16, projectorPath: .fallback,
+ expertResidencyTransition: nil, preprocessing: nil)
+ // <boi> image image <eoi>: the span covers the two image tokens.
+ let input = try MultimodalPrefillInput(
+ effectiveTokenIDs: [10, 11, 12, 13],
+ embeddingTokenIDs: [10, 0, 0, 13],
+ imageSpans: [MultimodalImageSpan(tokenRange: 1..<3, features: features)])
+
+ let shifted = try input.prepending([7, 8])
+ #expect(shifted.effectiveTokenIDs == [7, 8, 10, 11, 12, 13])
+ #expect(shifted.embeddingTokenIDs == [7, 8, 10, 0, 0, 13])
+ #expect(shifted.imageSpans.first?.tokenRange == 3..<5,
+ "the span did not move with its tokens, so features land on the wrong positions")
+
+ // Prepending nothing is the identity, so the common path is unchanged.
+ let same = try input.prepending([])
+ #expect(same.effectiveTokenIDs == input.effectiveTokenIDs)
+ #expect(same.imageSpans.first?.tokenRange == 1..<3)
+ }
+
+ /// The first turn of a conversation needs the chat template's opening,
+ /// including BOS. The image branch used the continuation form regardless,
+ /// so a session's first image question began with a dangling end-of-turn.
+ @Test func aFirstImageTurnOpensLikeAFirstTextTurn() throws {
+ let tokenizer = tok
+ let parts: [MultimodalContinuationPart] = [
+ .image, .text("what is this?"),
+ ]
+ let opening = try tokenizer.encodeMultimodalUserContinuation(
+ textAndImages: parts, imageTokenCounts: [4],
+ openingConversation: true)
+ let continuing = try tokenizer.encodeMultimodalUserContinuation(
+ textAndImages: parts, imageTokenCounts: [4])
+
+ let textOpening = tokenizer.encode(
+ try tokenizer.applyChatTemplate(
+ [GFTokenizer.Message(role: .user, content: "what is this?")]),
+ addBOS: false)
+ #expect(opening.effectiveTokenIDs.first == textOpening.first,
+ "the first image turn did not open the way a first text turn does")
+ #expect(opening.effectiveTokenIDs != continuing.effectiveTokenIDs,
+ "opening and continuing produced the same tokens")
+ // Both must still carry the image span.
+ #expect(opening.imageTokenRanges.count == 1)
+ #expect(continuing.imageTokenRanges.count == 1)
+ }
+
+ /// Truncation is ImageIO's question to answer, not a byte scan's.
+ ///
+ /// The scan could not get this right in either direction: a truncated photo
+ /// still carries the EOI of its EXIF thumbnail near the front, so it passed
+ /// and was decoded with gray filler, while a Motion Photo with more than
+ /// 4 MB of appended video pushed its real EOI past the search window and was
+ /// rejected. Both cases are pinned here.
+ @Test func truncatedImagesAreRejectedAndTrailingDataIsAccepted() throws {
+ let manager = FileManager.default
+ let directory = manager.temporaryDirectory
+ .appendingPathComponent("jpeg-\(UUID().uuidString)", isDirectory: true)
+ try manager.createDirectory(at: directory, withIntermediateDirectories: true)
+ defer { try? manager.removeItem(at: directory) }
+
+ // A real JPEG, encoded by ImageIO so the entropy-coded stream is valid.
+ let colorSpace = try #require(CGColorSpace(name: CGColorSpace.sRGB))
+ let bitmap = try #require(CGContext(
+ data: nil, width: 640, height: 480, bitsPerComponent: 8,
+ bytesPerRow: 640 * 4, space: colorSpace,
+ bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue))
+ bitmap.setFillColor(CGColor(red: 0.2, green: 0.6, blue: 0.9, alpha: 1))
+ bitmap.fill(CGRect(x: 0, y: 0, width: 640, height: 480))
+ let image = try #require(bitmap.makeImage())
+ let whole = directory.appendingPathComponent("whole.jpg")
+ let destination = try #require(CGImageDestinationCreateWithURL(
+ whole as CFURL, UTType.jpeg.identifier as CFString, 1, nil))
+ CGImageDestinationAddImage(destination, image, nil)
+ #expect(CGImageDestinationFinalize(destination))
+ let encoded = try Data(contentsOf: whole)
+
+ let reader = ImageMetadataReader(limits: VisionImageLimits())
+ func read(_ url: URL) throws -> VisionImageMetadata {
+ let opened = try VisionImageSource(fileURL: url)
+ .open(maximumEncodedBytes: VisionImageLimits().maximumEncodedBytes)
+ return try reader.read(opened: opened)
+ }
+
+ // Intact: accepted.
+ #expect(try read(whole).orientedWidth == 640)
+
+ // Trailing data past EOI, more than the old 4 MiB window: still accepted.
+ let motion = directory.appendingPathComponent("motion.jpg")
+ var withVideo = encoded
+ withVideo.append(Data(repeating: 0x11, count: 8 * 1_024 * 1_024))
+ try withVideo.write(to: motion)
+ #expect(try read(motion).orientedWidth == 640,
+ "a file with data after EOI was rejected")
+
+ // Truncated mid-scan: rejected, where the byte scan let it through
+ // because the thumbnail's own EOI sits near the front.
+ let truncated = directory.appendingPathComponent("truncated.jpg")
+ try encoded.prefix(encoded.count / 2).write(to: truncated)
+ #expect(throws: VisionImageError.self) { _ = try read(truncated) }
+ }
+
+ /// PNG had no completeness check at all, so a file cut short was accepted,
+ /// decoded with the undecoded remainder black, and described as "a solid,
+ /// uniform black square" - an answer about an image that was never
+ /// delivered. The JPEG guard next door had covered this class since it was
+ /// written; PNG simply was not asked.
+ @Test func aTruncatedPNGIsRejectedRatherThanDecodedAsBlack() throws {
+ let manager = FileManager.default
+ let directory = manager.temporaryDirectory
+ .appendingPathComponent("png-\(UUID().uuidString)", isDirectory: true)
+ try manager.createDirectory(at: directory, withIntermediateDirectories: true)
+ defer { try? manager.removeItem(at: directory) }
+
+ let colorSpace = try #require(CGColorSpace(name: CGColorSpace.sRGB))
+ let bitmap = try #require(CGContext(
+ data: nil, width: 320, height: 240, bitsPerComponent: 8,
+ bytesPerRow: 320 * 4, space: colorSpace,
+ bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue))
+ // Noise rather than a flat fill, so the file does not compress to a
+ // size where "half of it" still carries every row.
+ for x in stride(from: 0, to: 320, by: 2) {
+ for y in stride(from: 0, to: 240, by: 2) {
+ bitmap.setFillColor(CGColor(
+ red: Double((x &* 7) % 255) / 255, green: Double((y &* 13) % 255) / 255,
+ blue: Double((x &+ y) % 255) / 255, alpha: 1))
+ bitmap.fill(CGRect(x: x, y: y, width: 2, height: 2))
+ }
+ }
+ let image = try #require(bitmap.makeImage())
+ let whole = directory.appendingPathComponent("whole.png")
+ let destination = try #require(CGImageDestinationCreateWithURL(
+ whole as CFURL, UTType.png.identifier as CFString, 1, nil))
+ CGImageDestinationAddImage(destination, image, nil)
+ #expect(CGImageDestinationFinalize(destination))
+ let encoded = try Data(contentsOf: whole)
+
+ let reader = ImageMetadataReader(limits: VisionImageLimits())
+ func read(_ url: URL) throws -> VisionImageMetadata {
+ let opened = try VisionImageSource(fileURL: url)
+ .open(maximumEncodedBytes: VisionImageLimits().maximumEncodedBytes)
+ return try reader.read(opened: opened)
+ }
+
+ #expect(try read(whole).orientedWidth == 320, "an intact PNG was rejected")
+
+ let truncated = directory.appendingPathComponent("truncated.png")
+ try encoded.prefix(encoded.count / 2).write(to: truncated)
+ #expect(throws: VisionImageError.self) { _ = try read(truncated) }
+
+ // One byte short of IEND is the boundary the check actually draws.
+ let clipped = directory.appendingPathComponent("clipped.png")
+ try encoded.prefix(encoded.count - 1).write(to: clipped)
+ #expect(throws: VisionImageError.self) { _ = try read(clipped) }
+ }
+
+ /// A 0xFF fill byte before a marker is legal (ITU T.81 B.1.1.2) and real
+ /// scanners emit it. Reading it as the marker itself made the next two
+ /// bytes a length, which jumped into the entropy data and reported an
+ /// intact photo as truncated.
+ @Test func fillBytesBeforeMarkersDoNotLookLikeTruncation() throws {
+ let manager = FileManager.default
+ let directory = manager.temporaryDirectory
+ .appendingPathComponent("jpeg-fill-\(UUID().uuidString)", isDirectory: true)
+ try manager.createDirectory(at: directory, withIntermediateDirectories: true)
+ defer { try? manager.removeItem(at: directory) }
+
+ let colorSpace = try #require(CGColorSpace(name: CGColorSpace.sRGB))
+ let bitmap = try #require(CGContext(
+ data: nil, width: 320, height: 240, bitsPerComponent: 8,
+ bytesPerRow: 320 * 4, space: colorSpace,
+ bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue))
+ bitmap.setFillColor(CGColor(red: 0.9, green: 0.4, blue: 0.1, alpha: 1))
+ bitmap.fill(CGRect(x: 0, y: 0, width: 320, height: 240))
+ let image = try #require(bitmap.makeImage())
+ let source = directory.appendingPathComponent("plain.jpg")
+ let destination = try #require(CGImageDestinationCreateWithURL(
+ source as CFURL, UTType.jpeg.identifier as CFString, 1, nil))
+ CGImageDestinationAddImage(destination, image, nil)
+ #expect(CGImageDestinationFinalize(destination))
+ let encoded = [UInt8](try Data(contentsOf: source))
+
+ // Pad every marker in the header with extra 0xFF fill bytes, stopping
+ // at the start of scan so the entropy data is untouched.
+ var padded: [UInt8] = [encoded[0], encoded[1]]
+ var index = 2
+ while index + 3 < encoded.count {
+ guard encoded[index] == 0xFF else { break }
+ let marker = encoded[index + 1]
+ let length = Int(encoded[index + 2]) << 8 | Int(encoded[index + 3])
+ padded.append(contentsOf: [0xFF, 0xFF])
+ if marker == 0xDA {
+ padded.append(contentsOf: encoded[index...])
+ break
+ }
+ padded.append(contentsOf: encoded[index..<(index + 2 + length)])
+ index += 2 + length
+ }
+
+ let url = directory.appendingPathComponent("filled.jpg")
+ try Data(padded).write(to: url)
+ let opened = try VisionImageSource(fileURL: url)
+ .open(maximumEncodedBytes: VisionImageLimits().maximumEncodedBytes)
+ #expect(opened.hasCompleteJPEGStream(),
+ "a legal fill byte was read as truncation")
+ // And the whole path accepts it, since that is where users meet it.
+ let metadata = try ImageMetadataReader(limits: VisionImageLimits())
+ .read(opened: opened)
+ #expect(metadata.orientedWidth == 320)
+ }
+
+ /// The whole reduction belongs to our filter, which is the pinned
+ /// reference's. Decoding at the target handed it to ImageIO instead, and on
+ /// a UI screenshot that changed the model's transcription — measured
+ /// 0.0984 patch NRMSE against 0.0096 for a photo, and whole lines of text
+ /// lost. The cost that once justified the target-size decode was a
+ /// debug-build artifact; on the GPU the reference reduction is a few
+ /// milliseconds.
+ @Test func adownscaleDecodesAtTheSourceSize() throws {
+ let metadata = VisionImageMetadata(
+ encodedBytes: 1, encodedWidth: 4_032, encodedHeight: 3_024,
+ orientedWidth: 4_032, orientedHeight: 3_024, orientation: 1,
+ bitsPerComponent: 8, colorModel: "RGB", typeIdentifier: "public.jpeg")
+ let geometry = try Gemma4ImageGeometry(
+ sourceWidth: 4_032, sourceHeight: 3_024, config: VisionConfig())
+ #expect(geometry.processedWidth < 4_032, "this fixture is not a downscale")
+ #expect(Gemma4ImagePreprocessor.decodeMaxPixelSize(
+ metadata: metadata, geometry: geometry) == 4_032,
+ "the reduction was handed back to ImageIO's scaler")
+
+ // An upscale still decodes at its own size; there is nothing to reduce.
+ let small = VisionImageMetadata(
+ encodedBytes: 1, encodedWidth: 64, encodedHeight: 64,
+ orientedWidth: 64, orientedHeight: 64, orientation: 1,
+ bitsPerComponent: 8, colorModel: "RGB", typeIdentifier: "public.png")
+ let smallGeometry = try Gemma4ImageGeometry(
+ sourceWidth: 64, sourceHeight: 64, config: VisionConfig())
+ #expect(Gemma4ImagePreprocessor.decodeMaxPixelSize(
+ metadata: small, geometry: smallGeometry) == 64)
+ }
+}
+
+/// A directory reader that only worked once. The `fcntl` duplicate shares its
+/// offset with the retained descriptor, and `readdir` consumes it, so a second
+/// enumeration returned nothing and a valid pack read as having no entries.
+/// Only ever called once per instance in production, which is why it survived.
+@Suite struct DirectoryEnumerationTests {
+ @Test func basenamesAreStableAcrossRepeatedCalls() throws {
+ let manager = FileManager.default
+ let root = manager.temporaryDirectory
+ .appendingPathComponent("enumerate-\(UUID().uuidString)", isDirectory: true)
+ try manager.createDirectory(at: root, withIntermediateDirectories: true)
+ defer { try? manager.removeItem(at: root) }
+ for name in ["manifest.json", "weights.bin", "receipt.json"] {
+ try Data("x".utf8).write(to: root.appendingPathComponent(name))
+ }
+
+ let directory = try GTurboModelDirectory(rootURL: root)
+ let first = try directory.basenames()
+ #expect(first == ["manifest.json", "weights.bin", "receipt.json"])
+ let second = try directory.basenames()
+ #expect(second == first,
+ "the second enumeration of the same directory returned \(second)")
+ let third = try directory.basenames()
+ #expect(third == first)
+ }
+}
diff --git a/Tests/TurboFieldfare/Core/Runtime/Vision/MultimodalPromptRendererTests.swift b/Tests/TurboFieldfare/Core/Runtime/Vision/MultimodalPromptRendererTests.swift
new file mode 100644
index 00000000..dca2e85f
--- /dev/null
+++ b/Tests/TurboFieldfare/Core/Runtime/Vision/MultimodalPromptRendererTests.swift
@@ -0,0 +1,73 @@
+import Metal
+import Testing
+@testable import TurboFieldfare
+
+@Suite struct MultimodalPromptRendererTests {
+ @Test func expandsImagesInContentOrderAndZerosEmbeddingRows() async throws {
+ let tokenizer = try await GFTokenizer.load()
+ let context = try MetalContext()
+ let firstID = UUID()
+ let secondID = UUID()
+ let first = try features(rows: 2, context: context)
+ let second = try features(rows: 3, context: context)
+
+ let input = try MultimodalPromptRenderer.render(
+ messages: [MultimodalMessage(
+ role: .user,
+ content: [
+ .text("before"), .image(id: firstID),
+ .text("between"), .image(id: secondID), .text("after"),
+ ])],
+ featuresByID: [secondID: second, firstID: first],
+ tokenizer: tokenizer)
+
+ #expect(input.imageSpans.map(\.features.tokenCount) == [2, 3])
+ for span in input.imageSpans {
+ #expect(input.embeddingTokenIDs[span.tokenRange].allSatisfy { $0 == 0 })
+ #expect(input.effectiveTokenIDs[span.tokenRange].allSatisfy {
+ $0 == MultimodalPromptRenderer.imageTokenID
+ })
+ #expect(input.effectiveTokenIDs[span.tokenRange.lowerBound - 1]
+ == MultimodalPromptRenderer.beginImageTokenID)
+ #expect(input.effectiveTokenIDs[span.tokenRange.upperBound]
+ == MultimodalPromptRenderer.endImageTokenID)
+ }
+ }
+
+ @Test func rejectsReservedMarkersAndMissingFeatures() async throws {
+ let tokenizer = try await GFTokenizer.load()
+ #expect(throws: MultimodalPromptRendererError.reservedImageMarker) {
+ try MultimodalPromptRenderer.render(
+ messages: [MultimodalMessage(
+ role: .user,
+ content: [.text("typed <|image|> marker")])],
+ featuresByID: [:],
+ tokenizer: tokenizer)
+ }
+ let missing = UUID()
+ #expect(throws: MultimodalPromptRendererError.missingImage(missing)) {
+ try MultimodalPromptRenderer.render(
+ messages: [MultimodalMessage(
+ role: .user,
+ content: [.image(id: missing)])],
+ featuresByID: [:],
+ tokenizer: tokenizer)
+ }
+ }
+
+ private func features(rows: Int, context: MetalContext) throws -> VisionFeatures {
+ let bytes = rows * VisionConfig().textHiddenSize * MemoryLayout<Float16>.stride
+ let buffer = try #require(context.device.makeBuffer(
+ length: bytes, options: .storageModePrivate))
+ return VisionFeatures(
+ buffer: buffer,
+ tokenCount: rows,
+ hiddenSize: VisionConfig().textHiddenSize,
+ gpuNanoseconds: 0,
+ scratchBytes: bytes,
+ attentionVariant: .native72Q16,
+ projectorPath: .affineThreadgroupF16,
+ expertResidencyTransition: nil,
+ preprocessing: nil)
+ }
+}
diff --git a/Tests/TurboFieldfare/Core/Runtime/Vision/MultimodalSuffixPrefillTests.swift b/Tests/TurboFieldfare/Core/Runtime/Vision/MultimodalSuffixPrefillTests.swift
new file mode 100644
index 00000000..34633c73
--- /dev/null
+++ b/Tests/TurboFieldfare/Core/Runtime/Vision/MultimodalSuffixPrefillTests.swift
@@ -0,0 +1,203 @@
+import Metal
+import Testing
+@testable import TurboFieldfare
+
+/// Resuming a multimodal prompt on a cached KV prefix is only safe if the tail
+/// handed to the runner reconstructs the rendered prompt exactly. These pin that
+/// contract; a rebasing mistake would silently shift image injection and corrupt
+/// generation without failing anything else.
+@Suite struct MultimodalSuffixPrefillTests {
+ private func features(context: MetalContext, tokens: Int) throws -> VisionFeatures {
+ let hidden = VisionConfig().textHiddenSize
+ let buffer = try #require(context.device.makeBuffer(
+ length: tokens * hidden * MemoryLayout<Float16>.stride,
+ options: .storageModeShared))
+ return VisionFeatures(
+ buffer: buffer,
+ tokenCount: tokens,
+ hiddenSize: hidden,
+ gpuNanoseconds: 0,
+ scratchBytes: 0,
+ attentionVariant: .mppTensorOps72,
+ projectorPath: .affineThreadgroupBF16Apple10,
+ expertResidencyTransition: nil,
+ preprocessing: nil)
+ }
+
+ private func input(context: MetalContext,
+ total: Int,
+ spans: [(Range<Int>, Int)]) throws -> MultimodalPrefillInput {
+ var effective = (0..<total).map { Int32(1_000 + $0) }
+ var embedding = effective
+ var built: [MultimodalImageSpan] = []
+ for (range, tokens) in spans {
+ for index in range {
+ effective[index] = 258_880
+ embedding[index] = 0
+ }
+ built.append(MultimodalImageSpan(
+ tokenRange: range,
+ features: try features(context: context, tokens: tokens)))
+ }
+ return try MultimodalPrefillInput(
+ effectiveTokenIDs: effective,
+ embeddingTokenIDs: embedding,
+ imageSpans: built)
+ }
+
+ @Test func suffixReconstructsTheRenderedPromptExactly() throws {
+ let context = try MetalContext()
+ let full = try input(context: context, total: 120,
+ spans: [(40..<50, 10), (80..<95, 15)])
+ for cached in [1, 20, 39, 40] {
+ let suffix = try full.suffix(dropping: cached)
+ #expect(Array(full.effectiveTokenIDs.dropFirst(cached))
+ == suffix.effectiveTokenIDs)
+ #expect(Array(full.embeddingTokenIDs.dropFirst(cached))
+ == suffix.embeddingTokenIDs)
+ // Every span must land on the same absolute tokens once the start
+ // position is added back.
+ #expect(suffix.imageSpans.count == full.imageSpans.count)
+ for (original, rebased) in zip(full.imageSpans, suffix.imageSpans) {
+ #expect(rebased.tokenRange.lowerBound + cached
+ == original.tokenRange.lowerBound)
+ #expect(rebased.tokenRange.upperBound + cached
+ == original.tokenRange.upperBound)
+ #expect(rebased.features.tokenCount == original.features.tokenCount)
+ }
+ }
+ }
+
+ @Test func spansAlreadyInsideTheCachedPrefixAreDropped() throws {
+ let context = try MetalContext()
+ let full = try input(context: context, total: 120,
+ spans: [(10..<20, 10), (80..<95, 15)])
+ let suffix = try full.suffix(dropping: 60)
+ #expect(suffix.imageSpans.count == 1)
+ #expect(suffix.imageSpans[0].tokenRange == 20..<35)
+ #expect(Array(full.effectiveTokenIDs.dropFirst(60))
+ == suffix.effectiveTokenIDs)
+ }
+
+ /// A span crossing the boundary cannot be split: half its features are
+ /// already in the KV. It must be refused, not silently truncated.
+ @Test func spanStraddlingTheCachedBoundaryIsRefused() throws {
+ let context = try MetalContext()
+ let full = try input(context: context, total: 120,
+ spans: [(40..<50, 10)])
+ #expect(throws: MultimodalPrefillInputError.self) {
+ _ = try full.suffix(dropping: 45)
+ }
+ }
+
+ @Test func outOfRangeCachedCountsAreRefused() throws {
+ let context = try MetalContext()
+ let full = try input(context: context, total: 60, spans: [(10..<20, 10)])
+ #expect(throws: MultimodalPrefillInputError.self) {
+ _ = try full.suffix(dropping: 60)
+ }
+ #expect(throws: MultimodalPrefillInputError.self) {
+ _ = try full.suffix(dropping: -1)
+ }
+ }
+}
+
+/// The continuation bridge must produce the same tokens a full render produces
+/// for the same turn, or the KV lineage silently diverges from the prompt.
+@Suite struct MultimodalContinuationBridgeTests {
+ @Test(arguments: [[280], [17], [280, 17]])
+ func bridgeMatchesAFullRenderOfTheSameTurn(counts: [Int]) async throws {
+ let tokenizer = try await GFTokenizer.load()
+ var parts: [MultimodalContinuationPart] = [.text("look at ")]
+ for _ in counts { parts.append(.image) }
+ parts.append(.text(" and describe"))
+
+ let bridge = try tokenizer.encodeMultimodalUserContinuation(
+ textAndImages: parts, imageTokenCounts: counts)
+
+ // What a full render of the same user turn expands to, built from the
+ // renderer's own marker expansion rules.
+ let markers = counts.map { _ in MultimodalPromptRenderer.placeholder }
+ .joined(separator: "")
+ let text = ("look at " + markers + " and describe")
+ .trimmingCharacters(in: .whitespacesAndNewlines)
+ let template = [tokenizer.endOfTurnID] + tokenizer.encode(
+ "\n<|turn>user\n\(text)<turn|>\n<|turn>model\n<|channel>thought\n<channel|>",
+ addBOS: false)
+ var expected: [Int32] = []
+ var expectedEmbedding: [Int32] = []
+ var index = 0
+ for token in template {
+ guard token == MultimodalPromptRenderer.imageTokenID else {
+ expected.append(token); expectedEmbedding.append(token); continue
+ }
+ expected.append(MultimodalPromptRenderer.beginImageTokenID)
+ expectedEmbedding.append(MultimodalPromptRenderer.beginImageTokenID)
+ expected.append(contentsOf: repeatElement(
+ MultimodalPromptRenderer.imageTokenID, count: counts[index]))
+ expectedEmbedding.append(contentsOf: repeatElement(
+ Int32(0), count: counts[index]))
+ expected.append(MultimodalPromptRenderer.endImageTokenID)
+ expectedEmbedding.append(MultimodalPromptRenderer.endImageTokenID)
+ index += 1
+ }
+ #expect(bridge.effectiveTokenIDs == expected)
+ #expect(bridge.embeddingTokenIDs == expectedEmbedding)
+ #expect(bridge.imageTokenRanges.count == counts.count)
+ for (range, count) in zip(bridge.imageTokenRanges, counts) {
+ #expect(range.count == count)
+ #expect(bridge.effectiveTokenIDs[range]
+ .allSatisfy { $0 == MultimodalPromptRenderer.imageTokenID })
+ #expect(bridge.effectiveTokenIDs[range.lowerBound - 1]
+ == MultimodalPromptRenderer.beginImageTokenID)
+ #expect(bridge.effectiveTokenIDs[range.upperBound]
+ == MultimodalPromptRenderer.endImageTokenID)
+ }
+ }
+
+ @Test func bridgeStartsWithTheTurnBoundaryTheCacheExpects() async throws {
+ let tokenizer = try await GFTokenizer.load()
+ let bridge = try tokenizer.encodeMultimodalUserContinuation(
+ textAndImages: [.image, .text("what is it")], imageTokenCounts: [42])
+ #expect(bridge.effectiveTokenIDs.first == tokenizer.endOfTurnID)
+ #expect(bridge.effectiveTokenIDs.count == bridge.embeddingTokenIDs.count)
+ }
+
+ @Test func mismatchedImageCountsAreRefused() async throws {
+ let tokenizer = try await GFTokenizer.load()
+ #expect(throws: MultimodalPromptRendererError.self) {
+ _ = try tokenizer.encodeMultimodalUserContinuation(
+ textAndImages: [.image, .image], imageTokenCounts: [10])
+ }
+ #expect(throws: MultimodalPromptRendererError.self) {
+ _ = try tokenizer.encodeMultimodalUserContinuation(
+ textAndImages: [.text("no images")], imageTokenCounts: [])
+ }
+ }
+
+ @Test func aReservedMarkerInUserTextIsRefused() async throws {
+ let tokenizer = try await GFTokenizer.load()
+ #expect(throws: MultimodalPromptRendererError.self) {
+ _ = try tokenizer.encodeMultimodalUserContinuation(
+ textAndImages: [.text(MultimodalPromptRenderer.placeholder), .image],
+ imageTokenCounts: [10])
+ }
+ }
+
+ /// A reserved marker split across two text parts survives a per-part check
+ /// but reassembles on concatenation into a real image token. Left unguarded
+ /// it produced more placeholders than counts and trapped while indexing —
+ /// reachable from a request body, so a remote crash.
+ @Test func aMarkerSplitAcrossTextPartsIsRefusedRatherThanTrapping() async throws {
+ let tokenizer = try await GFTokenizer.load()
+ let marker = MultimodalPromptRenderer.placeholder
+ let cut = marker.index(marker.startIndex, offsetBy: 4)
+ #expect(throws: MultimodalPromptRendererError.self) {
+ _ = try tokenizer.encodeMultimodalUserContinuation(
+ textAndImages: [.text(String(marker[..<cut])),
+ .text(String(marker[cut...])),
+ .image],
+ imageTokenCounts: [10])
+ }
+ }
+}
diff --git a/Tests/TurboFieldfare/Core/Runtime/Vision/VisionImageContentTypesTests.swift b/Tests/TurboFieldfare/Core/Runtime/Vision/VisionImageContentTypesTests.swift
new file mode 100644
index 00000000..97e56731
--- /dev/null
+++ b/Tests/TurboFieldfare/Core/Runtime/Vision/VisionImageContentTypesTests.swift
@@ -0,0 +1,61 @@
+import Foundation
+import Testing
+import UniformTypeIdentifiers
+@testable import TurboFieldfare
+
+/// The formats a caller may attach and the formats the pack can decode have to
+/// be one list.
+///
+/// The picker and the pasteboard admitted anything conforming to `public.image`
+/// — which includes camera RAW, EXR and WebP — while `ImageMetadataReader`
+/// accepts seven identifiers. Everything in between was copied at up to 64 MB,
+/// decoded in-process for a thumbnail beside a loaded model, and only then
+/// refused by the run.
+@Suite struct VisionImageContentTypesTests {
+ @Test func thecontentTypeListMatchesTheIdentifierAllowlist() {
+ let limits = VisionImageLimits()
+ #expect(Set(limits.allowedContentTypes.map(\.identifier))
+ == limits.allowedTypeIdentifiers,
+ "the UTType list and the identifier allowlist disagree")
+ }
+
+ /// The gate has to be narrower than `public.image`, which is the whole
+ /// reason it exists.
+ @Test func formatsThePackCannotDecodeAreOutsideTheList() {
+ let limits = VisionImageLimits()
+ for excluded in [UTType("com.adobe.raw-image"),
+ UTType("public.camera-raw-image"),
+ UTType("com.ilm.openexr-image"),
+ UTType.webP,
+ UTType.bmp,
+ UTType.pdf] {
+ guard let excluded else { continue }
+ #expect(!limits.allowedTypeIdentifiers.contains(excluded.identifier),
+ "\(excluded.identifier) is admitted but cannot be decoded")
+ // Everything excluded here still conforms to public.image, which is
+ // why the old gate let it through.
+ #expect(!limits.allowedContentTypes.contains(excluded))
+ }
+ }
+
+ /// The formats the pack does decode have to survive the round trip to
+ /// `UTType`, or the picker would silently offer fewer than it supports.
+ @Test func everySupportedIdentifierResolvesToAContentType() {
+ let limits = VisionImageLimits()
+ #expect(limits.allowedContentTypes.count == limits.allowedTypeIdentifiers.count,
+ "an identifier did not resolve to a UTType and was dropped from the picker")
+ for expected in [UTType.jpeg, .png, .heic, .tiff, .gif] {
+ #expect(limits.allowedContentTypes.contains(expected),
+ "\(expected.identifier) is decodable but the picker would not offer it")
+ }
+ }
+
+ /// Stable ordering, so the picker's type list does not shuffle between
+ /// launches from `Set` iteration order.
+ @Test func thecontentTypeListIsStablyOrdered() {
+ let limits = VisionImageLimits()
+ #expect(limits.allowedContentTypes == limits.allowedContentTypes)
+ #expect(limits.allowedContentTypes.map(\.identifier)
+ == limits.allowedContentTypes.map(\.identifier).sorted())
+ }
+}
diff --git a/Tests/TurboFieldfare/Core/Runtime/Vision/VisionImagePreprocessorTests.swift b/Tests/TurboFieldfare/Core/Runtime/Vision/VisionImagePreprocessorTests.swift
new file mode 100644
index 00000000..7e04d45c
--- /dev/null
+++ b/Tests/TurboFieldfare/Core/Runtime/Vision/VisionImagePreprocessorTests.swift
@@ -0,0 +1,294 @@
+import Foundation
+import ImageIO
+import Metal
+import Testing
+import UniformTypeIdentifiers
+@testable import TurboFieldfare
+
+@Suite struct VisionImagePreprocessorTests {
+ private struct Corpus: Decodable {
+ struct Case: Decodable {
+ let file: String
+ let orientation: Int
+ let processedWidth: Int
+ let processedHeight: Int
+ let gridWidth: Int
+ let gridHeight: Int
+
+ enum CodingKeys: String, CodingKey {
+ case file, orientation
+ case processedWidth = "processed_width"
+ case processedHeight = "processed_height"
+ case gridWidth = "grid_width"
+ case gridHeight = "grid_height"
+ }
+ }
+
+ let cases: [Case]
+ }
+
+ @Test func geometryMatchesReferenceProcessor() throws {
+ let square = try Gemma4ImageGeometry(sourceWidth: 641, sourceHeight: 641)
+ #expect(square.processedWidth == 768)
+ #expect(square.processedHeight == 768)
+ #expect(square.patchGridWidth == 48)
+ #expect(square.patchGridHeight == 48)
+ #expect(square.softTokenCount == 256)
+
+ let panorama = try Gemma4ImageGeometry(sourceWidth: 1_537, sourceHeight: 257)
+ #expect(panorama.processedWidth == 1_920)
+ #expect(panorama.processedHeight == 288)
+ #expect(panorama.patchCount == 2_160)
+ #expect(panorama.softTokenCount == 240)
+
+ let fortyEightMegapixels = try Gemma4ImageGeometry(
+ sourceWidth: 8_000, sourceHeight: 6_000)
+ #expect(fortyEightMegapixels.processedWidth == 912)
+ #expect(fortyEightMegapixels.processedHeight == 672)
+ #expect(fortyEightMegapixels.patchGridWidth == 57)
+ #expect(fortyEightMegapixels.patchGridHeight == 42)
+ #expect(fortyEightMegapixels.patchCount == 2_394)
+ #expect(fortyEightMegapixels.softTokenCount == 266)
+
+ let veryWide = try Gemma4ImageGeometry(sourceWidth: 32_768, sourceHeight: 1)
+ #expect(veryWide.processedWidth == 13_440)
+ #expect(veryWide.processedHeight == 48)
+ #expect(veryWide.patchCount == 2_520)
+
+ let veryTall = try Gemma4ImageGeometry(sourceWidth: 1, sourceHeight: 32_768)
+ #expect(veryTall.processedWidth == 48)
+ #expect(veryTall.processedHeight == 13_440)
+ #expect(veryTall.patchCount == 2_520)
+ }
+
+ @Test func frozenCorpusProducesExactGeometryAndPositions() throws {
+ let device = try #require(MTLCreateSystemDefaultDevice())
+ let root = try #require(Self.corpusRoot)
+ let corpus = try JSONDecoder().decode(
+ Corpus.self,
+ from: Data(contentsOf: root.appendingPathComponent("corpus.json")))
+ let preprocessor = Gemma4ImagePreprocessor(device: device)
+
+ for fixture in corpus.cases {
+ let result = try preprocessor.preprocess(
+ fileURL: root.appendingPathComponent(fixture.file))
+ #expect(result.metadata.orientation == fixture.orientation)
+ #expect(result.geometry.processedWidth == fixture.processedWidth)
+ #expect(result.geometry.processedHeight == fixture.processedHeight)
+ #expect(result.geometry.patchGridWidth == fixture.gridWidth)
+ #expect(result.geometry.patchGridHeight == fixture.gridHeight)
+ #expect(result.patchesBF16.length
+ == result.geometry.patchCount * VisionConfig().patchDimension * 2)
+ #expect(result.positionsInt32x2.length
+ == result.geometry.patchCount * 2 * MemoryLayout<Int32>.stride)
+ #expect(result.allocatedBytes < 12 * 1_024 * 1_024)
+
+ let positions = result.positionsInt32x2.contents().bindMemory(
+ to: Int32.self, capacity: result.geometry.patchCount * 2)
+ for row in 0..<result.geometry.patchCount {
+ #expect(positions[row * 2] == Int32(row % fixture.gridWidth))
+ #expect(positions[row * 2 + 1] == Int32(row / fixture.gridWidth))
+ }
+ let patches = result.patchesBF16.contents().bindMemory(
+ to: UInt16.self,
+ capacity: result.geometry.patchCount * VisionConfig().patchDimension)
+ let count = result.geometry.patchCount * VisionConfig().patchDimension
+ for index in stride(from: 0, to: count, by: 251) {
+ let value = Quantization.bf16ToFloat(patches[index])
+ #expect(value.isFinite && value >= 0 && value <= 1)
+ }
+ }
+ }
+
+ @Test func rejectsMalformedEncodedInput() throws {
+ let url = FileManager.default.temporaryDirectory
+ .appendingPathComponent("vision-malformed-\(UUID().uuidString).jpg")
+ try Data([0xFF, 0xD8, 0xFF]).write(to: url)
+ defer { try? FileManager.default.removeItem(at: url) }
+ let preprocessor = Gemma4ImagePreprocessor(
+ device: try #require(MTLCreateSystemDefaultDevice()))
+ #expect(throws: VisionImageError.self) {
+ try preprocessor.preprocess(fileURL: url)
+ }
+ }
+
+ @Test func rejectsOversizedSourceBeforeDecode() throws {
+ let image = try #require(Self.corpusRoot).appendingPathComponent("natural-square.png")
+ let preprocessor = Gemma4ImagePreprocessor(
+ device: try #require(MTLCreateSystemDefaultDevice()),
+ limits: VisionImageLimits(maximumEncodedBytes: 1))
+ #expect(throws: VisionImageError.self) {
+ try preprocessor.preprocess(fileURL: image)
+ }
+ }
+
+ @Test func rejectsSourceDimensionLimitBeforeDecode() throws {
+ let image = try #require(Self.corpusRoot).appendingPathComponent("natural-square.png")
+ let preprocessor = Gemma4ImagePreprocessor(
+ device: try #require(MTLCreateSystemDefaultDevice()),
+ limits: VisionImageLimits(
+ maximumSourcePixels: 100,
+ maximumSourceDimension: 10))
+ #expect(throws: VisionImageError.self) {
+ try preprocessor.preprocess(fileURL: image)
+ }
+ }
+
+ @Test func rejectsSymlinkSource() throws {
+ let target = try #require(Self.corpusRoot).appendingPathComponent("natural-square.png")
+ let link = FileManager.default.temporaryDirectory
+ .appendingPathComponent("vision-link-\(UUID().uuidString).png")
+ try FileManager.default.createSymbolicLink(at: link, withDestinationURL: target)
+ defer { try? FileManager.default.removeItem(at: link) }
+ let preprocessor = Gemma4ImagePreprocessor(
+ device: try #require(MTLCreateSystemDefaultDevice()))
+ #expect(throws: VisionImageError.self) {
+ try preprocessor.preprocess(fileURL: link)
+ }
+ }
+
+ @Test func rejectsTruncatedPayload() throws {
+ let source = try #require(Self.corpusRoot).appendingPathComponent("natural-odd-4x3.jpg")
+ let truncated = FileManager.default.temporaryDirectory
+ .appendingPathComponent("vision-truncated-\(UUID().uuidString).jpg")
+ let prefix = try Data(contentsOf: source).prefix(1_024)
+ try Data(prefix).write(to: truncated)
+ defer { try? FileManager.default.removeItem(at: truncated) }
+ let preprocessor = Gemma4ImagePreprocessor(
+ device: try #require(MTLCreateSystemDefaultDevice()))
+ #expect(throws: VisionImageError.self) {
+ try preprocessor.preprocess(fileURL: truncated)
+ }
+ }
+
+ @Test func rejectsMultiframeMedia() throws {
+ let url = FileManager.default.temporaryDirectory
+ .appendingPathComponent("vision-multiframe-\(UUID().uuidString).gif")
+ guard let colorSpace = CGColorSpace(name: CGColorSpace.sRGB),
+ let context = CGContext(
+ data: nil, width: 1, height: 1, bitsPerComponent: 8,
+ bytesPerRow: 4, space: colorSpace,
+ bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue),
+ let image = context.makeImage(),
+ let destination = CGImageDestinationCreateWithURL(
+ url as CFURL, UTType.gif.identifier as CFString, 2, nil) else {
+ Issue.record("could not create multiframe fixture")
+ return
+ }
+ CGImageDestinationAddImage(destination, image, nil)
+ CGImageDestinationAddImage(destination, image, nil)
+ #expect(CGImageDestinationFinalize(destination))
+ defer { try? FileManager.default.removeItem(at: url) }
+
+ let preprocessor = Gemma4ImagePreprocessor(
+ device: try #require(MTLCreateSystemDefaultDevice()))
+ #expect(throws: VisionImageError.self) {
+ try preprocessor.preprocess(fileURL: url)
+ }
+ }
+
+ @Test func convertsCMYKToSRGB() throws {
+ let url = FileManager.default.temporaryDirectory
+ .appendingPathComponent("vision-cmyk-\(UUID().uuidString).jpg")
+ try writeImage(
+ url: url,
+ type: .jpeg,
+ colorSpace: CGColorSpaceCreateDeviceCMYK(),
+ bitsPerComponent: 8,
+ bitsPerPixel: 32,
+ bitmapInfo: CGBitmapInfo(rawValue: 0),
+ bytes: [0, 255, 255, 0])
+ defer { try? FileManager.default.removeItem(at: url) }
+ let preprocessor = Gemma4ImagePreprocessor(
+ device: try #require(MTLCreateSystemDefaultDevice()))
+ let result = try preprocessor.preprocess(fileURL: url)
+ #expect(result.metadata.colorModel == kCGImagePropertyColorModelCMYK as String)
+ assertFiniteUnitPatches(result)
+ }
+
+ @Test func convertsSixteenBitToEightBit() throws {
+ let url = FileManager.default.temporaryDirectory
+ .appendingPathComponent("vision-16bit-\(UUID().uuidString).png")
+ try writeImage(
+ url: url,
+ type: .png,
+ colorSpace: CGColorSpaceCreateDeviceGray(),
+ bitsPerComponent: 16,
+ bitsPerPixel: 16,
+ bitmapInfo: .byteOrder16Big,
+ bytes: [0x80, 0x00])
+ defer { try? FileManager.default.removeItem(at: url) }
+ let preprocessor = Gemma4ImagePreprocessor(
+ device: try #require(MTLCreateSystemDefaultDevice()))
+ let result = try preprocessor.preprocess(fileURL: url)
+ #expect(result.metadata.bitsPerComponent == 16)
+ assertFiniteUnitPatches(result)
+ }
+
+ @Test func acceptsSingleFrameTIFF() throws {
+ let url = FileManager.default.temporaryDirectory
+ .appendingPathComponent("vision-tiff-\(UUID().uuidString).tiff")
+ try writeImage(
+ url: url,
+ type: .tiff,
+ colorSpace: CGColorSpaceCreateDeviceRGB(),
+ bitsPerComponent: 8,
+ bitsPerPixel: 32,
+ bitmapInfo: CGBitmapInfo(rawValue:
+ CGImageAlphaInfo.premultipliedLast.rawValue),
+ bytes: [0x33, 0x66, 0x99, 0xff])
+ defer { try? FileManager.default.removeItem(at: url) }
+ let preprocessor = Gemma4ImagePreprocessor(
+ device: try #require(MTLCreateSystemDefaultDevice()))
+
+ let result = try preprocessor.preprocess(fileURL: url)
+
+ #expect(result.metadata.typeIdentifier == UTType.tiff.identifier)
+ assertFiniteUnitPatches(result)
+ }
+
+ private func assertFiniteUnitPatches(_ result: VisionPixelBuffer) {
+ let count = result.geometry.patchCount * VisionConfig().patchDimension
+ let patches = result.patchesBF16.contents().bindMemory(
+ to: UInt16.self, capacity: count)
+ for index in stride(from: 0, to: count, by: 251) {
+ let value = Quantization.bf16ToFloat(patches[index])
+ #expect(value.isFinite && value >= 0 && value <= 1)
+ }
+ }
+
+ private func writeImage(
+ url: URL,
+ type: UTType,
+ colorSpace: CGColorSpace,
+ bitsPerComponent: Int,
+ bitsPerPixel: Int,
+ bitmapInfo: CGBitmapInfo,
+ bytes: [UInt8]
+ ) throws {
+ let data = Data(bytes)
+ let provider = try #require(CGDataProvider(data: data as CFData))
+ let image = try #require(CGImage(
+ width: 1,
+ height: 1,
+ bitsPerComponent: bitsPerComponent,
+ bitsPerPixel: bitsPerPixel,
+ bytesPerRow: bytes.count,
+ space: colorSpace,
+ bitmapInfo: bitmapInfo,
+ provider: provider,
+ decode: nil,
+ shouldInterpolate: false,
+ intent: .defaultIntent))
+ let destination = try #require(CGImageDestinationCreateWithURL(
+ url as CFURL, type.identifier as CFString, 1, nil))
+ CGImageDestinationAddImage(destination, image, nil)
+ #expect(CGImageDestinationFinalize(destination))
+ }
+
+ /// The frozen corpus, shipped as a test resource.
+ private static var corpusRoot: URL? {
+ Bundle.module.url(forResource: "images", withExtension: nil)
+ }
+
+}
diff --git a/Tests/TurboFieldfare/Core/Runtime/Vision/VisionPackUseLeaseTests.swift b/Tests/TurboFieldfare/Core/Runtime/Vision/VisionPackUseLeaseTests.swift
new file mode 100644
index 00000000..5647f02d
--- /dev/null
+++ b/Tests/TurboFieldfare/Core/Runtime/Vision/VisionPackUseLeaseTests.swift
@@ -0,0 +1,80 @@
+import Darwin
+import Foundation
+import Testing
+@testable import TurboFieldfare
+
+/// The shared use lease against real filesystem permissions: the writable
+/// happy path, the read-only fallbacks, and the fail-closed cases. The
+/// EROFS lock-free path needs an actual read-only mount and stays covered by
+/// code review only.
+@Suite struct VisionPackUseLeaseTests {
+
+ private func makePack() throws -> URL {
+ let root = FileManager.default.temporaryDirectory
+ .appendingPathComponent("use-lease-\(UUID().uuidString)", isDirectory: true)
+ let pack = root.appendingPathComponent("model.vision.gturbo", isDirectory: true)
+ try FileManager.default.createDirectory(at: pack, withIntermediateDirectories: true)
+ return pack
+ }
+
+ @Test func sharedLeaseCreatesAndNamesTheDottedLockFile() throws {
+ let pack = try makePack()
+ defer { try? FileManager.default.removeItem(at: pack.deletingLastPathComponent()) }
+ let lease = try VisionPackUseLease.acquireShared(companionURL: pack)
+ #expect(lease.lockFileURL.lastPathComponent == ".model.vision.gturbo.use.lock")
+ #expect(FileManager.default.fileExists(atPath: lease.lockFileURL.path))
+ }
+
+ @Test func readOnlyLockFileStillGrantsASharedLease() throws {
+ let pack = try makePack()
+ defer { try? FileManager.default.removeItem(at: pack.deletingLastPathComponent()) }
+ let lockURL = VisionPackUseLease.lockURL(for: pack)
+ #expect(FileManager.default.createFile(atPath: lockURL.path, contents: nil))
+ #expect(chmod(lockURL.path, 0o444) == 0)
+ // The O_RDWR create-open gets EACCES; the O_RDONLY retry must lock.
+ let lease = try VisionPackUseLease.acquireShared(companionURL: pack)
+ #expect(lease.lockFileURL.path == lockURL.path)
+ }
+
+ @Test func unwritableParentWithoutALockFileFailsClosed() throws {
+ let pack = try makePack()
+ let parent = pack.deletingLastPathComponent()
+ defer {
+ _ = chmod(parent.path, 0o755)
+ try? FileManager.default.removeItem(at: parent)
+ }
+ #expect(chmod(parent.path, 0o555) == 0)
+ // A writable volume whose directory merely denies us could still host
+ // a privileged writer, so no lock file means no lease.
+ #expect(throws: VisionPackError.self) {
+ _ = try VisionPackUseLease.acquireShared(companionURL: pack)
+ }
+ }
+
+ @Test func fifoAtTheLockPathIsRejectedNotHung() throws {
+ let pack = try makePack()
+ defer { try? FileManager.default.removeItem(at: pack.deletingLastPathComponent()) }
+ let lockURL = VisionPackUseLease.lockURL(for: pack)
+ // Read-only FIFO: the create-open gets EACCES, and the O_RDONLY retry
+ // would block forever on a FIFO without O_NONBLOCK; the S_IFREG check
+ // must reject it instead.
+ #expect(mkfifo(lockURL.path, 0o444) == 0)
+ #expect(throws: VisionPackError.self) {
+ _ = try VisionPackUseLease.acquireShared(companionURL: pack)
+ }
+ }
+
+ @Test func anExclusiveWriterBlocksTheSharedLeaseUntilTimeout() throws {
+ let pack = try makePack()
+ defer { try? FileManager.default.removeItem(at: pack.deletingLastPathComponent()) }
+ let lockURL = VisionPackUseLease.lockURL(for: pack)
+ let writer = open(lockURL.path, O_RDWR | O_CREAT | O_CLOEXEC, 0o600)
+ #expect(writer >= 0)
+ defer { close(writer) }
+ #expect(flock(writer, LOCK_EX) == 0)
+ #expect(throws: VisionPackError.self) {
+ _ = try VisionPackUseLease.acquireShared(
+ companionURL: pack, timeout: .milliseconds(120))
+ }
+ }
+}
diff --git a/Tests/TurboFieldfare/Core/Runtime/Vision/VisionResizeParityTests.swift b/Tests/TurboFieldfare/Core/Runtime/Vision/VisionResizeParityTests.swift
new file mode 100644
index 00000000..26f73f41
--- /dev/null
+++ b/Tests/TurboFieldfare/Core/Runtime/Vision/VisionResizeParityTests.swift
@@ -0,0 +1,97 @@
+import Foundation
+import Testing
+@testable import TurboFieldfare
+
+/// The GPU resize exists to make the reference filter affordable, so it has to
+/// be the same filter — not a close one. Every case here asserts byte equality
+/// with `TorchBicubicResize`, which is the path validated against the pinned
+/// image processor.
+@Suite struct VisionResizeParityTests {
+ private func pattern(width: Int, height: Int, seed: UInt64) -> [UInt8] {
+ var pixels = [UInt8](repeating: 0, count: width * height * 4)
+ var state = seed &* 6_364_136_223_846_793_005 &+ 1
+ for index in pixels.indices {
+ state = state &* 6_364_136_223_846_793_005 &+ 1_442_695_040_888_963_407
+ // High-frequency content: a smooth ramp hides exactly the
+ // differences this test is looking for.
+ pixels[index] = UInt8(truncatingIfNeeded: state >> 33)
+ }
+ return pixels
+ }
+
+ private func cpuResize(_ source: [UInt8], _ sw: Int, _ sh: Int,
+ _ dw: Int, _ dh: Int) -> [UInt8] {
+ var destination = [UInt8](repeating: 0, count: dw * dh * 4)
+ source.withUnsafeBufferPointer { input in
+ destination.withUnsafeMutableBufferPointer { output in
+ _ = TorchBicubicResize.resize(
+ source: input.baseAddress!, sourceWidth: sw, sourceHeight: sh,
+ sourceRowBytes: sw * 4,
+ destination: output.baseAddress!,
+ destinationWidth: dw, destinationHeight: dh,
+ destinationRowBytes: dw * 4)
+ }
+ }
+ return destination
+ }
+
+ private func gpuResize(_ resizer: VisionResize, _ source: [UInt8],
+ _ sw: Int, _ sh: Int, _ dw: Int, _ dh: Int) throws -> [UInt8] {
+ var destination = [UInt8](repeating: 0, count: dw * dh * 4)
+ try source.withUnsafeBufferPointer { input in
+ try destination.withUnsafeMutableBufferPointer { output in
+ try resizer.resize(
+ source: input.baseAddress!, sourceWidth: sw, sourceHeight: sh,
+ sourceRowBytes: sw * 4,
+ destination: output.baseAddress!,
+ destinationWidth: dw, destinationHeight: dh,
+ destinationRowBytes: dw * 4)
+ }
+ }
+ return destination
+ }
+
+ @Test func theGPUFilterIsByteIdenticalToTheCPUOracle() throws {
+ let context = try MetalContext()
+ let resizer = try VisionResize(context: context)
+
+ // Downscales of several ratios, an upscale, a one-axis change, and the
+ // identity — the shapes a real corpus produces.
+ let cases: [(Int, Int, Int, Int)] = [
+ (640, 480, 320, 240),
+ (1_920, 1_080, 720, 405),
+ (2_484, 3_000, 720, 864),
+ (333, 217, 111, 73),
+ (64, 64, 192, 192),
+ (500, 300, 500, 120),
+ (256, 256, 256, 256),
+ ]
+ for (sw, sh, dw, dh) in cases {
+ let source = pattern(width: sw, height: sh, seed: UInt64(sw &* 31 &+ sh))
+ let expected = cpuResize(source, sw, sh, dw, dh)
+ let actual = try gpuResize(resizer, source, sw, sh, dw, dh)
+ #expect(actual == expected,
+ "\(sw)x\(sh) -> \(dw)x\(dh) differs from the CPU filter")
+ if actual != expected {
+ let differing = zip(actual, expected).filter { $0 != $1 }.count
+ let worst = zip(actual, expected)
+ .map { abs(Int($0) - Int($1)) }.max() ?? 0
+ Issue.record("\(differing) bytes differ, worst by \(worst)")
+ }
+ }
+ }
+
+ /// A tall, thin reduction exercises the vertical pass alone, where the CPU
+ /// walks bytes rather than pixels; an off-by-one in that indexing would
+ /// otherwise show up only as a colour shift on real images.
+ @Test func singleAxisReductionsMatch() throws {
+ let context = try MetalContext()
+ let resizer = try VisionResize(context: context)
+ for (sw, sh, dw, dh) in [(97, 1_000, 97, 137), (1_000, 97, 137, 97)] {
+ let source = pattern(width: sw, height: sh, seed: 7)
+ #expect(try gpuResize(resizer, source, sw, sh, dw, dh)
+ == cpuResize(source, sw, sh, dw, dh),
+ "\(sw)x\(sh) -> \(dw)x\(dh) differs")
+ }
+ }
+}
diff --git a/Tests/TurboFieldfare/Core/Runtime/Vision/VisionResourceLimitTests.swift b/Tests/TurboFieldfare/Core/Runtime/Vision/VisionResourceLimitTests.swift
new file mode 100644
index 00000000..707f8c6d
--- /dev/null
+++ b/Tests/TurboFieldfare/Core/Runtime/Vision/VisionResourceLimitTests.swift
@@ -0,0 +1,373 @@
+import CoreGraphics
+import UniformTypeIdentifiers
+import TurboFieldfareFormat
+import Foundation
+import ImageIO
+import Metal
+import Testing
+@testable import TurboFieldfare
+
+/// Resource-limit and buffer-validity guards. Each test fails against the
+/// behaviour each comment describes.
+@Suite struct VisionResourceLimitTests {
+ /// The per-side, pixel and decoded-bytes guards all threw the pixel-limit
+ /// error, so two of the three sent the user to resize against a constraint
+ /// their image already met.
+ @Test func eachRejectionGuardNamesItsOwnLimit() throws {
+ let manager = FileManager.default
+ let directory = manager.temporaryDirectory
+ .appendingPathComponent("limit-errors-\(UUID().uuidString)", isDirectory: true)
+ try manager.createDirectory(at: directory, withIntermediateDirectories: true)
+ defer { try? manager.removeItem(at: directory) }
+ func read(width: Int, height: Int, limits: VisionImageLimits) throws {
+ let url = directory.appendingPathComponent(
+ "img-\(width)x\(height)-\(UUID().uuidString).png")
+ try Self.writeSolidPNG(width: width, height: height, to: url)
+ let opened = try VisionImageSource(fileURL: url)
+ .open(maximumEncodedBytes: limits.maximumEncodedBytes)
+ _ = try ImageMetadataReader(limits: limits).read(opened: opened)
+ }
+
+ // 300x50 is far under the default pixel cap; only a side exceeds.
+ #expect {
+ try read(width: 300, height: 50,
+ limits: VisionImageLimits(maximumSourceDimension: 100))
+ } throws: { error in
+ guard case VisionImageError.sideTooLarge(
+ let width, let height, let limit) = error else { return false }
+ return width == 300 && height == 50 && limit == 100
+ }
+
+ // Both sides fit; only the pixel product exceeds.
+ #expect {
+ try read(width: 300, height: 50,
+ limits: VisionImageLimits(maximumSourcePixels: 10_000))
+ } throws: { error in
+ guard case VisionImageError.dimensionsTooLarge(
+ let width, let height, let limit) = error else { return false }
+ return width == 300 && height == 50 && limit == 10_000
+ }
+
+ // Sides and pixels fit; only the decoded-surface ceiling exceeds.
+ let decodedBytes = 320 * 320 * 4
+ #expect {
+ try read(width: 320, height: 320,
+ limits: VisionImageLimits(maximumDecodedBytes: decodedBytes / 2))
+ } throws: { error in
+ guard case VisionImageError.decodedBytesTooLarge(
+ let width, let height, let limit) = error else { return false }
+ return width == 320 && height == 320 && limit == decodedBytes / 2
+ }
+ }
+
+ /// The coordinate validator dereferences `contents()`, which is invalid for
+ /// private storage — the natural choice for a caller building buffers only
+ /// GPU kernels consume. The validation added to prevent GPU faults must
+ /// throw, not fault first.
+ @Test(.enabled(if: Self.visionModelURL != nil && Self.supportsVisionRuntime,
+ "requires an installed vision model on M2 or newer"))
+ func privateStoragePositionsAreRefusedRatherThanDereferenced() throws {
+ let modelURL = try #require(Self.visionModelURL)
+ let context = try MetalContext()
+ let config = VisionConfig()
+ let runtime = try VisionRuntime.open(
+ textModelURL: modelURL, context: context, environment: [:])
+
+ let rows = config.poolingKernel * config.poolingKernel
+ let patches = try #require(context.device.makeBuffer(
+ length: rows * config.patchDimension * 2, options: .storageModeShared))
+ let positions = try #require(context.device.makeBuffer(
+ length: rows * 2 * MemoryLayout<Int32>.stride,
+ options: .storageModePrivate))
+ #expect {
+ _ = try runtime.encodePatches(
+ patchesBF16: patches,
+ positionsInt32x2: positions,
+ patchGridWidth: config.poolingKernel,
+ patchGridHeight: config.poolingKernel)
+ } throws: { error in
+ guard case VisionRuntimeError.invalidInput(let detail) = error else {
+ return false
+ }
+ return detail.contains("CPU-visible")
+ }
+ }
+
+ /// The use lease opens its lock with `O_CREAT`, so pointing the runtime at
+ /// a directory that merely exists — a `.partial` download, a mistyped path —
+ /// left a zero-byte `.<name>.use.lock` there that nothing ever removes. The
+ /// existence check in front of it had already been added for exactly this
+ /// reason; the validity check still ran after the lease.
+ @Test(.enabled(if: Self.visionModelURL != nil && Self.supportsVisionRuntime,
+ "requires an installed vision model on M2 or newer"))
+ func aDirectoryThatIsNotAPackLeavesNoLockFileBehind() throws {
+ let modelURL = try #require(Self.visionModelURL)
+ let manager = FileManager.default
+ let parent = manager.temporaryDirectory
+ .appendingPathComponent("not-a-pack-\(UUID().uuidString)", isDirectory: true)
+ let candidate = parent.appendingPathComponent(
+ "model.vision.gturbo", isDirectory: true)
+ try manager.createDirectory(at: candidate, withIntermediateDirectories: true)
+ defer { try? manager.removeItem(at: parent) }
+ // Pack-shaped enough to reach the open, empty enough to be refused.
+ try Data("not a manifest".utf8).write(
+ to: candidate.appendingPathComponent("vision_weights.bin"))
+
+ let context = try MetalContext()
+ #expect(throws: (any Error).self) {
+ _ = try VisionRuntime.open(
+ textModelURL: modelURL, context: context,
+ visionPackURL: candidate, environment: [:])
+ }
+
+ let lock = parent.appendingPathComponent(".model.vision.gturbo.use.lock")
+ #expect(!manager.fileExists(atPath: lock.path),
+ "a refused open left a lock file with no owner at \(lock.path)")
+ #expect(try manager.contentsOfDirectory(atPath: parent.path).sorted()
+ == ["model.vision.gturbo"])
+ }
+
+ /// One `VisionRuntime` init used to compile the identical tensorops source
+ /// three times. Libraries are immutable, so the same module for the same
+ /// device must come back as the same object.
+ @Test func privateLibraryIsCompiledOncePerDeviceAndModule() throws {
+ let context = try MetalContext()
+ let first = try MetalContext.privateLibrary(
+ device: context.device, module: "tensorops")
+ let second = try MetalContext.privateLibrary(
+ device: context.device, module: "tensorops")
+ #expect(first === second, "the same module was compiled twice for one device")
+ }
+
+ @Test func imageTowerFailsClosedBeforeApple8() throws {
+ #expect {
+ try VisionRuntime.requireSupportedDevice(supportsApple8: false)
+ } throws: { error in
+ guard case VisionRuntimeError.unsupportedKernel(let detail) = error else {
+ return false
+ }
+ return detail.contains("M2 or newer")
+ }
+ try VisionRuntime.requireSupportedDevice(supportsApple8: true)
+ }
+
+ @Test(.enabled(if: !Self.supportsVisionRuntime,
+ "requires an Apple7 or older Metal device"))
+ func unsupportedDeviceIsRejectedBeforeModelIO() throws {
+ let context = try MetalContext()
+ let missing = FileManager.default.temporaryDirectory
+ .appendingPathComponent("missing-model-\(UUID().uuidString)")
+ #expect {
+ _ = try VisionRuntime.open(textModelURL: missing, context: context)
+ } throws: { error in
+ guard case VisionRuntimeError.unsupportedKernel(let detail) = error else {
+ return false
+ }
+ return detail.contains("M2 or newer")
+ }
+ }
+
+ @Test func defaultKernelSelectionKeepsPromotedAndBaselinePathsDistinct() {
+ let promoted = VisionRuntime.resolvedKernelEnvironment([:])
+ #expect(promoted["TURBO_FIELDFARE_VISION_ATTENTION_MPP"] == "1")
+ #expect(promoted["TURBO_FIELDFARE_VISION_REGISTER_GEMM"] == "1")
+
+ let baseline = VisionRuntime.resolvedKernelEnvironment(
+ ["TURBO_FIELDFARE_VISION_BASELINE_KERNELS": "1"])
+ #expect(baseline["TURBO_FIELDFARE_VISION_ATTENTION_MPP"] == nil)
+ #expect(baseline["TURBO_FIELDFARE_VISION_REGISTER_GEMM"] == nil)
+
+ let explicit = VisionRuntime.resolvedKernelEnvironment([
+ "TURBO_FIELDFARE_VISION_ATTENTION_Q8": "1",
+ "TURBO_FIELDFARE_VISION_REGISTER_ATTENTION": "1",
+ ])
+ #expect(explicit["TURBO_FIELDFARE_VISION_ATTENTION_MPP"] == nil)
+ #expect(explicit["TURBO_FIELDFARE_VISION_REGISTER_GEMM"] == nil)
+ }
+
+ private static func writeSolidPNG(width: Int, height: Int, to url: URL) throws {
+ let colorSpace = try #require(CGColorSpace(name: CGColorSpace.sRGB))
+ let bitmap = try #require(CGContext(
+ data: nil, width: width, height: height, bitsPerComponent: 8,
+ bytesPerRow: width * 4, space: colorSpace,
+ bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue))
+ bitmap.setFillColor(CGColor(gray: 0.5, alpha: 1))
+ bitmap.fill(CGRect(x: 0, y: 0, width: width, height: height))
+ let image = try #require(bitmap.makeImage())
+ let destination = try #require(CGImageDestinationCreateWithURL(
+ url as CFURL, "public.png" as CFString, 1, nil))
+ CGImageDestinationAddImage(destination, image, nil)
+ #expect(CGImageDestinationFinalize(destination))
+ }
+
+ /// An installed text model with its companion pack beside it, or nil when
+ /// this checkout has none — the model-dependent cases then skip.
+ ///
+ /// Searched by walking up from this source file rather than from the
+ /// working directory. The working directory is wherever the suite happens
+ /// to be run from, so a checkout nested inside another one silently skipped
+ /// every case here while a model sat one level up.
+ static func visionModelURL(from file: StaticString = #filePath) -> URL? {
+ let manager = FileManager.default
+ var directory = URL(fileURLWithPath: "\(file)").deletingLastPathComponent()
+ while directory.path != "/" {
+ let candidate = directory
+ .appendingPathComponent("scratch")
+ .appendingPathComponent("gemma4.gturbo")
+ if let companion = try? VisionPackLocation.companionURL(
+ forTextModel: candidate),
+ manager.fileExists(atPath: candidate.path),
+ manager.fileExists(atPath: companion.path) {
+ return candidate
+ }
+ directory = directory.deletingLastPathComponent()
+ }
+ return nil
+ }
+
+ static var visionModelURL: URL? { visionModelURL() }
+
+ static var supportsVisionRuntime: Bool {
+ MTLCreateSystemDefaultDevice()?.supportsFamily(.apple8) == true
+ }
+
+ @Test func osSidecarsDoNotInvalidateAPack() {
+ for name in [".DS_Store", "._manifest.json", "._vision_weights.bin",
+ ".Spotlight-V100", ".fseventsd", "manifest.json.icloud"] {
+ #expect(GTurboVisionFormatV1.isSidecarEntry(name),
+ "\(name) would still be treated as part of the pack")
+ }
+ // The other direction is the one that matters more: `VisionWeightStore`
+ // and the pack verifier both drop every entry this matches before
+ // comparing the directory against the pack, so a rule broad enough to
+ // swallow a required file reports the same "image support is
+ // unavailable" as the sidecar it was widened for — for a pack that is
+ // complete on disk. The names are spelled out as well as read off the
+ // constants, so renaming a constant cannot quietly empty this check.
+ let packEntries = ["manifest.json", "vision_weights.bin",
+ "processor_config.json", "verified-install.json"]
+ #expect(packEntries == [GTurboVisionFormatV1.manifestFile,
+ GTurboVisionFormatV1.weightsFile,
+ GTurboVisionFormatV1.processorFile,
+ GTurboVisionFormatV1.receiptFile],
+ "the pack's entry names changed; this list has to change with them")
+ // `_manifest.json` is the near miss for the AppleDouble prefix: a real
+ // file, one character from the rule that ignores one.
+ for name in packEntries + ["vision_weights.bin.tmp", "_manifest.json"] {
+ #expect(!GTurboVisionFormatV1.isSidecarEntry(name),
+ "\(name) would be ignored, which is how a real file goes missing")
+ }
+ }
+
+ /// A deleted pack file used to be reported as the surviving files being
+ /// "unexpected", so the message pointed at three files that belong there
+ /// and never named the one that had gone. Both the runtime store and the
+ /// installer's verifier phrase it through this helper, so both are covered.
+ @Test func aMissingPackFileIsReportedAsMissingRatherThanAsSurplus() {
+ let expected: Set<String> = [
+ GTurboVisionFormatV1.manifestFile,
+ GTurboVisionFormatV1.weightsFile,
+ GTurboVisionFormatV1.processorFile,
+ GTurboVisionFormatV1.receiptFile,
+ ]
+
+ let withoutProcessor = expected.subtracting([GTurboVisionFormatV1.processorFile])
+ let missing = GTurboVisionFormatV1.entryDifference(
+ expected: expected, actual: withoutProcessor)
+ #expect(missing == "missing [\"processor_config.json\"]")
+ #expect(!missing.contains("unexpected"),
+ "a deleted file must not be described as surplus entries")
+
+ let withStray = expected.union(["stray.bin"])
+ #expect(GTurboVisionFormatV1.entryDifference(
+ expected: expected, actual: withStray) == "unexpected [\"stray.bin\"]")
+
+ // Both at once, which is what a half-written pack looks like.
+ let both = withoutProcessor.union(["stray.bin"])
+ #expect(GTurboVisionFormatV1.entryDifference(expected: expected, actual: both)
+ == "missing [\"processor_config.json\"], unexpected [\"stray.bin\"]")
+ }
+
+ /// The decoded-byte ceiling is inclusive. This catches a `<=` quietly
+ /// changing to `<`, which would reject an image exactly at the contract.
+ @Test func theDecodedCeilingAdmitsExactlyItselfAndRefusesOneByteMore() throws {
+ let side = 320
+ let decodedBytes = side * side * 4
+ let manager = FileManager.default
+ let directory = manager.temporaryDirectory
+ .appendingPathComponent("decode-boundary-\(UUID().uuidString)", isDirectory: true)
+ try manager.createDirectory(at: directory, withIntermediateDirectories: true)
+ defer { try? manager.removeItem(at: directory) }
+ let url = directory.appendingPathComponent("square.png")
+ try Self.writeSolidPNG(width: side, height: side, to: url)
+
+ func read(ceiling: Int) throws {
+ let limits = VisionImageLimits(maximumDecodedBytes: ceiling)
+ let opened = try VisionImageSource(fileURL: url)
+ .open(maximumEncodedBytes: limits.maximumEncodedBytes)
+ _ = try ImageMetadataReader(limits: limits).read(opened: opened)
+ }
+
+ // Exactly at the ceiling: admitted.
+ try read(ceiling: decodedBytes)
+ // One byte under it: refused, and by the decoded-bytes guard rather
+ // than a dimension guard, which is what the user is told to act on.
+ #expect {
+ try read(ceiling: decodedBytes - 1)
+ } throws: { error in
+ guard case VisionImageError.decodedBytesTooLarge(_, _, let limit) = error else {
+ return false
+ }
+ return limit == decodedBytes - 1
+ }
+ }
+
+ @Test func oversizedSourcesAreRefusedWhateverTheFormat() throws {
+ let side = 320
+ let decodedBytes = side * side * 4
+ // Injected rather than shipped so the light suite does not allocate a
+ // production-size surface merely to prove the format-independent gate.
+ let limits = VisionImageLimits(maximumDecodedBytes: decodedBytes / 2)
+
+ let manager = FileManager.default
+ let directory = manager.temporaryDirectory
+ .appendingPathComponent("decode-cap-\(UUID().uuidString)", isDirectory: true)
+ try manager.createDirectory(at: directory, withIntermediateDirectories: true)
+ defer { try? manager.removeItem(at: directory) }
+
+ let reader = ImageMetadataReader(limits: limits)
+ for (type, ext) in [(UTType.png, "png"), (UTType.jpeg, "jpg")] {
+ let url = directory.appendingPathComponent("big.\(ext)")
+ try Self.writeSolidImage(width: side, height: side, type: type, to: url)
+ let opened = try VisionImageSource(fileURL: url)
+ .open(maximumEncodedBytes: limits.maximumEncodedBytes)
+ #expect(throws: VisionImageError.self) { _ = try reader.read(opened: opened) }
+ }
+
+ // The shipped ceiling must admit the largest supported 8-bit camera
+ // input. This fails if the earlier 96 MiB low-end policy returns.
+ let shipped = VisionImageLimits()
+ let pixels = 8_000 * 6_000
+ #expect(pixels <= shipped.maximumSourcePixels)
+ #expect(8_000 <= shipped.maximumSourceDimension)
+ #expect(pixels * 4 <= shipped.maximumDecodedBytes)
+ }
+
+ private static func writeSolidImage(
+ width: Int, height: Int, type: UTType, to url: URL
+ ) throws {
+ let colorSpace = try #require(CGColorSpace(name: CGColorSpace.sRGB))
+ let bitmap = try #require(CGContext(
+ data: nil, width: width, height: height, bitsPerComponent: 8,
+ bytesPerRow: width * 4, space: colorSpace,
+ bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue))
+ bitmap.setFillColor(CGColor(gray: 0.5, alpha: 1))
+ bitmap.fill(CGRect(x: 0, y: 0, width: width, height: height))
+ let image = try #require(bitmap.makeImage())
+ let destination = try #require(CGImageDestinationCreateWithURL(
+ url as CFURL, type.identifier as CFString, 1, nil))
+ CGImageDestinationAddImage(destination, image, nil)
+ #expect(CGImageDestinationFinalize(destination))
+ }
+
+}
diff --git a/Tests/TurboFieldfare/Core/Runtime/Vision/VisionWeightStoreTests.swift b/Tests/TurboFieldfare/Core/Runtime/Vision/VisionWeightStoreTests.swift
new file mode 100644
index 00000000..98ec6f1f
--- /dev/null
+++ b/Tests/TurboFieldfare/Core/Runtime/Vision/VisionWeightStoreTests.swift
@@ -0,0 +1,118 @@
+import Foundation
+import Metal
+import Testing
+@testable import TurboFieldfare
+@testable import TurboFieldfareFormat
+
+@Suite struct VisionWeightStoreTests {
+ private let zeroSHA = String(repeating: "0", count: 64)
+
+ @Test func companionLocationPreservesTextModelStem() throws {
+ let text = URL(fileURLWithPath: "/models/custom-name.gturbo")
+ #expect(try VisionPackLocation.companionURL(forTextModel: text).path
+ == "/models/custom-name.vision.gturbo")
+ #expect(throws: VisionPackError.self) {
+ try VisionPackLocation.companionURL(
+ forTextModel: URL(fileURLWithPath: "/models/custom-name"))
+ }
+ }
+
+ @Test func opensTrustedBoundedCompanionWithoutHashingWeights() throws {
+ let fixture = try makeFixture()
+ defer { try? FileManager.default.removeItem(at: fixture.root) }
+
+ let store = try VisionWeightStore.open(
+ directoryURL: fixture.root,
+ compatibleTextSourceSnapshotHash: "text-snapshot",
+ compatibleTextManifestSha256: zeroSHA)
+ #expect(store.manifest.modelID == "fixture/model")
+ #expect(store.manifest.tensors.map(\.name) == ["vision.weight"])
+ let mapped = try store.mapRegion(
+ executionPosition: 0,
+ device: try #require(MTLCreateSystemDefaultDevice()))
+ #expect(mapped.residentSize == 2)
+ #expect(mapped.mappedLength == 2)
+ }
+
+ @Test func rejectsWrongTextBindingReceiptPathAndUnexpectedEntry() throws {
+ let incompatible = try makeFixture()
+ defer { try? FileManager.default.removeItem(at: incompatible.root) }
+ #expect(throws: VisionPackError.self) {
+ try VisionWeightStore.open(
+ directoryURL: incompatible.root,
+ compatibleTextSourceSnapshotHash: "other",
+ compatibleTextManifestSha256: zeroSHA)
+ }
+
+ let wrongPath = try makeFixture(receiptDirectoryPath: "/tmp/partial")
+ defer { try? FileManager.default.removeItem(at: wrongPath.root) }
+ #expect(throws: VisionPackError.self) {
+ try VisionWeightStore.open(
+ directoryURL: wrongPath.root,
+ compatibleTextSourceSnapshotHash: "text-snapshot",
+ compatibleTextManifestSha256: zeroSHA)
+ }
+
+ let extra = try makeFixture()
+ defer { try? FileManager.default.removeItem(at: extra.root) }
+ try Data().write(to: extra.root.appendingPathComponent("extra"))
+ #expect(throws: VisionPackError.self) {
+ try VisionWeightStore.open(
+ directoryURL: extra.root,
+ compatibleTextSourceSnapshotHash: "text-snapshot",
+ compatibleTextManifestSha256: zeroSHA)
+ }
+ }
+
+ private func makeFixture(receiptDirectoryPath: String? = nil)
+ throws -> (root: URL, manifest: GTurboVisionManifestV1) {
+ let root = FileManager.default.temporaryDirectory
+ .appendingPathComponent("vision-weight-store-\(UUID().uuidString).vision.gturbo")
+ try FileManager.default.createDirectory(at: root,
+ withIntermediateDirectories: false)
+
+ let weights = Data(repeating: 0, count: Int(GTurboVisionFormatV1.alignmentBytes))
+ let processor = Data("{}".utf8)
+ let weightSHA = Sha256Verifier.hashData(weights)
+ let processorSHA = Sha256Verifier.hashData(processor)
+ let manifest = GTurboVisionManifestV1(
+ modelID: "fixture/model", sourceRevision: "fixture-revision",
+ sourceIndexSha256: zeroSHA,
+ processorConfigSha256: processorSHA,
+ compatibleTextSourceSnapshotHash: "text-snapshot",
+ compatibleTextManifestSha256: zeroSHA,
+ files: [
+ GTurboVisionFormatV1.weightsFile: .init(
+ size: UInt64(weights.count), sha256: weightSHA),
+ GTurboVisionFormatV1.processorFile: .init(
+ size: UInt64(processor.count), sha256: processorSHA),
+ ],
+ tensors: [.init(
+ name: "vision.weight", executionPosition: 0,
+ offset: 0, size: 2, shape: [1], dtype: .bf16)])
+ let manifestData = try GTurboVisionManifestCodec.encode(manifest)
+ let manifestSHA = Sha256Verifier.hashData(manifestData)
+ let receipt = GTurboVisionReceiptV1(
+ manifestSha256: manifestSHA,
+ companionDirectoryPath: receiptDirectoryPath ?? root.standardizedFileURL.path,
+ compatibleTextManifestSha256: zeroSHA,
+ sourceRepoID: "fixture/model", sourceRevision: "fixture-revision",
+ verificationTimestamp: "2026-08-05T00:00:00Z",
+ toolVersion: "fixture",
+ files: [
+ GTurboVisionFormatV1.manifestFile: .init(
+ size: UInt64(manifestData.count), sha256: manifestSHA),
+ GTurboVisionFormatV1.weightsFile: manifest.files[
+ GTurboVisionFormatV1.weightsFile]!,
+ GTurboVisionFormatV1.processorFile: manifest.files[
+ GTurboVisionFormatV1.processorFile]!,
+ ])
+
+ try weights.write(to: root.appendingPathComponent(GTurboVisionFormatV1.weightsFile))
+ try processor.write(to: root.appendingPathComponent(GTurboVisionFormatV1.processorFile))
+ try manifestData.write(to: root.appendingPathComponent(GTurboVisionFormatV1.manifestFile))
+ try GTurboVisionReceiptCodec.encode(receipt).write(
+ to: root.appendingPathComponent(GTurboVisionFormatV1.receiptFile))
+ return (root, manifest)
+ }
+}
diff --git a/Tests/TurboFieldfareApp/Core/Configuration/AppContextLengthOptionTests.swift b/Tests/TurboFieldfareApp/Core/Configuration/AppContextLengthOptionTests.swift
index ae6dc41b..37dc3fe2 100644
--- a/Tests/TurboFieldfareApp/Core/Configuration/AppContextLengthOptionTests.swift
+++ b/Tests/TurboFieldfareApp/Core/Configuration/AppContextLengthOptionTests.swift
@@ -11,13 +11,20 @@ import Testing
let mebibytes = AppContextLengthOption.allCases.map {
$0.fp16KVBytes / 1_048_576
}
- #expect(mebibytes == [305, 385, 545, 865, 1_505])
+ // 29 MiB above the older figures at every size, because the sliding
+ // ring is sized for the widest prefill chunk the runtime may see - the
+ // pooled image-token count - and the estimate had used the smaller text
+ // chunk. The menu deltas are unchanged: every option grew equally.
+ #expect(mebibytes == [334, 414, 574, 894, 1_534])
+ // Deltas are relative to the default, which is 8K as of 2026-08-17 so
+ // that an image and its prompt fit without the user changing anything.
+ // 334 - 414 = -80 MiB, 574 - 414 = +160 MiB, and so on.
#expect(AppContextLengthOption.allCases.map(\.menuLabel) == [
- "4K, Default",
- "8K, +85 MB",
- "16K, +250 MB",
- "32K, +590 MB",
- "64K, +1.26 GB",
+ "4K, -85 MB",
+ "8K, Default",
+ "16K, +170 MB",
+ "32K, +500 MB",
+ "64K, +1.17 GB",
])
}
}
diff --git a/Tests/TurboFieldfareApp/Core/Configuration/AppRuntimeOptionsTests.swift b/Tests/TurboFieldfareApp/Core/Configuration/AppRuntimeOptionsTests.swift
index 691fb4b1..2775e39d 100644
--- a/Tests/TurboFieldfareApp/Core/Configuration/AppRuntimeOptionsTests.swift
+++ b/Tests/TurboFieldfareApp/Core/Configuration/AppRuntimeOptionsTests.swift
@@ -21,7 +21,10 @@ import TurboFieldfare
@Test func everyPublicChoiceMapsToRuntime() throws {
for slots in AppRuntimeOptions.allowedSlotCounts {
- let runtime = try AppRuntimeOptions(expertCacheSlots: slots)
+ let prefillEnabled =
+ slots >= RuntimeConfiguration.minimumExpertCacheSlotsForChunkedPrefill
+ let runtime = try AppRuntimeOptions(expertCacheSlots: slots,
+ prefillEnabled: prefillEnabled)
.resolvedRuntimeConfiguration(forceLogitsHead: false)
#expect(runtime.expertCacheSlots == slots)
}
@@ -98,4 +101,19 @@ import TurboFieldfare
maxContextTokens: 4096,
options: value) == baseline)
}
+ /// Refused at selection, not inside the first prefill chunk - which is
+ /// after the model load and, on an image turn, after every attachment has
+ /// already been encoded on the GPU.
+ @Test func slotsBelowTheChunkedPrefillMinimumRequirePrefillOff() {
+ let minimum = RuntimeConfiguration.minimumExpertCacheSlotsForChunkedPrefill
+ for slots in AppRuntimeOptions.allowedSlotCounts where slots < minimum {
+ #expect(throws: AppInferenceError.self) {
+ try AppRuntimeOptions(expertCacheSlots: slots, prefillEnabled: true).validate()
+ }
+ #expect(throws: Never.self) {
+ try AppRuntimeOptions(expertCacheSlots: slots, prefillEnabled: false).validate()
+ }
+ }
+ }
+
}
diff --git a/Tests/TurboFieldfareApp/Core/Configuration/MacAppSettingsTests.swift b/Tests/TurboFieldfareApp/Core/Configuration/MacAppSettingsTests.swift
index 6615758b..7be69456 100644
--- a/Tests/TurboFieldfareApp/Core/Configuration/MacAppSettingsTests.swift
+++ b/Tests/TurboFieldfareApp/Core/Configuration/MacAppSettingsTests.swift
@@ -275,6 +275,62 @@ import Testing
#expect(!model.showPromptExamples)
}
+ /// Phase D item 15. The newer-version branch says "Every key decodes with
+ /// `decodeIfPresent`, so it reads cleanly", and that is false: nine keys use
+ /// a hard `decode`. So a version-3 file whose schema moved any of those nine
+ /// throws inside `JSONDecoder().decode` *before* the version guard is
+ /// reached, and lands in the `catch` that deletes the file - destroying a
+ /// newer build's settings, which is the exact outcome that branch exists to
+ /// prevent. A version bump that cannot change the schema protects nothing.
+ @Test func aNewerSettingsFileSurvivesAKeyThisBuildDoesNotKnow() throws {
+ let root = try makeTemporaryRoot()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let modelDirectory = root.appendingPathComponent("gemma4.gturbo", isDirectory: true)
+ let fileURL = MacAppSettingsFileStore.fileURL(forModelDirectory: modelDirectory)
+
+ // A plausible version 3: `topP` became `topProbability`. Everything else
+ // this build knows is still present and still valid.
+ let newer = """
+ {
+ "version": 3,
+ "contextTokens": 8192,
+ "expertCacheSlots": 16,
+ "temperature": 0.2,
+ "topKEnabled": true,
+ "topK": 64,
+ "topPEnabled": true,
+ "topProbability": 0.95,
+ "prefillEnabled": true
+ }
+ """
+ try Data(newer.utf8).write(to: fileURL)
+
+ let settings = MacAppSettingsFileStore.loadOrCreate(forModelDirectory: modelDirectory)
+
+ #expect(settings == MacAppSettings(), "this build must run on defaults")
+ #expect(FileManager.default.fileExists(atPath: fileURL.path),
+ "a newer build's settings file was deleted by an older build")
+ #expect(try String(contentsOf: fileURL, encoding: .utf8) == newer,
+ "a newer build's settings file was rewritten by an older build")
+ }
+
+ /// Phase D item 16. RDADVISE is a Picker in `InspectorView` bound to
+ /// `runtimeOptions.rdadvisePolicy`, and `RUNTIME_CONTROLS.md` lists it as an
+ /// app control - but it had no `CodingKey`, so every relaunch silently
+ /// reverted it while the UI kept offering it as a persistent setting.
+ @Test func rdadviseSurvivesARelaunch() throws {
+ let root = try makeTemporaryRoot()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let modelDirectory = root.appendingPathComponent("gemma4.gturbo", isDirectory: true)
+
+ try MacAppSettingsFileStore.save(
+ MacAppSettings(rdadvisePolicy: .bounded),
+ forModelDirectory: modelDirectory)
+ let reloaded = MacAppSettingsFileStore.loadOrCreate(forModelDirectory: modelDirectory)
+
+ #expect(reloaded.rdadvisePolicy == .bounded)
+ }
+
private func makeTemporaryRoot() throws -> URL {
let root = FileManager.default.temporaryDirectory
.appendingPathComponent("MacAppSettingsTests-\(UUID().uuidString)",
@@ -284,4 +340,34 @@ import Testing
withIntermediateDirectories: true)
return root
}
+ @Test func visionResidencyRoundTrips() throws {
+ let initial = MacAppSettings(visionResidencyPolicy: .keepReady)
+ let decoded = try JSONDecoder().decode(
+ MacAppSettings.self,
+ from: JSONEncoder().encode(initial))
+
+ #expect(decoded == initial)
+ }
+
+ @MainActor
+ @Test func changingModelDirectoryStillReleasesTheImageTower() throws {
+ let root = try makeTemporaryRoot()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let first = root.appendingPathComponent("first/model.gturbo", isDirectory: true)
+ let second = root.appendingPathComponent("second/model.gturbo", isDirectory: true)
+ try MacAppSettingsFileStore.save(
+ MacAppSettings(visionResidencyPolicy: .onDemand),
+ forModelDirectory: first)
+ try MacAppSettingsFileStore.save(
+ MacAppSettings(visionResidencyPolicy: .keepReady),
+ forModelDirectory: second)
+ let model = AppModel(modelDirectory: first, settingsPersistenceEnabled: true)
+ #expect(model.runtimeOptions.visionResidencyPolicy == .onDemand)
+
+ model.setModelURL(second)
+
+ #expect(model.runtimeOptions.visionResidencyPolicy == .onDemand,
+ "a persisted keep-ready came back through the model path change")
+ }
+
}
diff --git a/Tests/TurboFieldfareApp/Core/Configuration/VisionSectionVisibilityTests.swift b/Tests/TurboFieldfareApp/Core/Configuration/VisionSectionVisibilityTests.swift
new file mode 100644
index 00000000..228d2aa0
--- /dev/null
+++ b/Tests/TurboFieldfareApp/Core/Configuration/VisionSectionVisibilityTests.swift
@@ -0,0 +1,67 @@
+import Testing
+@testable import TurboFieldfareAppCore
+
+/// Phase D item 1. The section was last in the inspector and shown
+/// unconditionally in `public/`, while root put it second and hid it until a
+/// text model existed. Neither did what the empty state needs, so the rule now
+/// lives somewhere it can be checked without launching the app.
+@Suite struct VisionSectionVisibilityTests {
+ private func shows(modelInstalled: Bool,
+ packInstalled: Bool,
+ operating: Bool = false,
+ state: AppModelInstallState = .idle,
+ runtimeEnabled: Bool = true,
+ runtimeSupported: Bool = true) -> Bool {
+ VisionSectionVisibility.shows(
+ visionRuntimeEnabled: runtimeEnabled,
+ visionRuntimeSupported: runtimeSupported,
+ isModelInstalled: modelInstalled,
+ isVisionPackInstalled: packInstalled,
+ isCompanionOperationInProgress: operating,
+ installState: state)
+ }
+
+ /// The screen where someone decides whether this app suits them. Hiding the
+ /// section here meant image support was undiscoverable until after a
+ /// 14.62 GB download.
+ @Test func theEmptyStateAdvertisesImageSupport() {
+ #expect(shows(modelInstalled: false, packInstalled: false))
+ }
+
+ @Test func aModelWithoutThePackOffersToInstallIt() {
+ #expect(shows(modelInstalled: true, packInstalled: false))
+ }
+
+ /// Installed and healthy is the one case with nothing to say, so the section
+ /// collapses rather than occupying the inspector permanently.
+ @Test func anInstalledHealthyPackCollapsesTheSection() {
+ #expect(!shows(modelInstalled: true, packInstalled: true))
+ }
+
+ @Test func workInProgressKeepsTheSectionOpen() {
+ #expect(shows(modelInstalled: true, packInstalled: true, operating: true))
+ }
+
+ @Test func aFailureKeepsTheSectionOpenSoItCanBeRead() {
+ #expect(shows(modelInstalled: true, packInstalled: true,
+ state: .failed("pack verification failed")))
+ #expect(shows(modelInstalled: true, packInstalled: true,
+ state: .recoverable("download interrupted")))
+ }
+
+ /// The one hard off switch: nothing about the pack is shown when the runtime
+ /// cannot use it at all.
+ @Test func aDisabledVisionRuntimeHidesEveryCase() {
+ #expect(!shows(modelInstalled: false, packInstalled: false, runtimeEnabled: false))
+ #expect(!shows(modelInstalled: true, packInstalled: false, runtimeEnabled: false))
+ #expect(!shows(modelInstalled: true, packInstalled: true,
+ operating: true, runtimeEnabled: false))
+ }
+
+ @Test func unsupportedHardwareKeepsTheExplanationVisible() {
+ #expect(shows(modelInstalled: false, packInstalled: false,
+ runtimeSupported: false))
+ #expect(shows(modelInstalled: true, packInstalled: true,
+ runtimeSupported: false))
+ }
+}
diff --git a/Tests/TurboFieldfareApp/Core/Inference/AppGenerationRequestTests.swift b/Tests/TurboFieldfareApp/Core/Inference/AppGenerationRequestTests.swift
index 643574d2..7d8d8d12 100644
--- a/Tests/TurboFieldfareApp/Core/Inference/AppGenerationRequestTests.swift
+++ b/Tests/TurboFieldfareApp/Core/Inference/AppGenerationRequestTests.swift
@@ -91,4 +91,44 @@ import Testing
try request.validate()
}
}
+ @Test func duplicateAndMalformedImageDescriptorsAreRejected() {
+ let id = UUID()
+ let attachment = AppImageAttachment(
+ id: id,
+ fileURL: URL(fileURLWithPath: "/tmp/image.png"),
+ displayName: "image.png",
+ encodedBytes: 4,
+ sha256: String(repeating: "a", count: 64))
+ #expect(throws: AppInferenceError.self) {
+ try AppGenerationRequest(
+ modelDirectory: existingDirectory,
+ prompt: "",
+ imageAttachments: [attachment, attachment]).validate()
+ }
+ let malformed = AppImageAttachment(
+ fileURL: URL(fileURLWithPath: "/tmp/image.png"),
+ displayName: "image.png",
+ encodedBytes: 4,
+ sha256: "not-a-digest")
+ #expect(throws: AppInferenceError.self) {
+ try AppGenerationRequest(
+ modelDirectory: existingDirectory,
+ prompt: "",
+ imageAttachments: [malformed]).validate()
+ }
+ }
+
+ @Test func imageOnlyRequestIsValid() throws {
+ let attachment = AppImageAttachment(
+ fileURL: URL(fileURLWithPath: "/tmp/image.png"),
+ displayName: "image.png",
+ encodedBytes: 4,
+ sha256: String(repeating: "a", count: 64))
+ let request = AppGenerationRequest(
+ modelDirectory: existingDirectory,
+ prompt: "",
+ imageAttachments: [attachment])
+ try request.validate()
+ }
+
}
diff --git a/Tests/TurboFieldfareApp/Core/Inference/AppImageAttachmentStoreTests.swift b/Tests/TurboFieldfareApp/Core/Inference/AppImageAttachmentStoreTests.swift
new file mode 100644
index 00000000..9960d0d9
--- /dev/null
+++ b/Tests/TurboFieldfareApp/Core/Inference/AppImageAttachmentStoreTests.swift
@@ -0,0 +1,72 @@
+import Darwin
+import Foundation
+import Testing
+@testable import TurboFieldfareAppCore
+
+/// The store is a trust boundary before it is anything else: whatever it
+/// vouches for gets opened and hashed by another process, so a path it accepts
+/// from outside its own root would make that process an oracle for any file the
+/// user can read.
+@Suite struct AppImageAttachmentStoreTests {
+ @Test func onlyStagedPathsAreAccepted() throws {
+ let root = AppImageAttachmentStore.root
+ let staged = root
+ .appendingPathComponent("pid-\(getpid())", isDirectory: true)
+ .appendingPathComponent(UUID().uuidString, isDirectory: true)
+ .appendingPathComponent("image.png")
+ #expect(AppImageAttachmentStore.contains(staged))
+
+ #expect(!AppImageAttachmentStore.contains(URL(fileURLWithPath: "/etc/passwd")))
+ #expect(!AppImageAttachmentStore.contains(
+ URL(fileURLWithPath: FileManager.default.temporaryDirectory.path)
+ .appendingPathComponent("elsewhere.png")))
+ #expect(!AppImageAttachmentStore.contains(root),
+ "the root itself is a directory, not an attachment")
+ // Traversal back out of the root must not pass.
+ #expect(!AppImageAttachmentStore.contains(
+ root.appendingPathComponent("../../etc/passwd")))
+ }
+
+ /// A symlink planted inside the root must not smuggle a target outside it.
+ @Test func asymlinkOutOfTheStoreIsRejected() throws {
+ let manager = FileManager.default
+ let root = AppImageAttachmentStore.root
+ .appendingPathComponent("pid-\(getpid())", isDirectory: true)
+ .appendingPathComponent("trust-\(UUID().uuidString)", isDirectory: true)
+ try manager.createDirectory(at: root, withIntermediateDirectories: true)
+ defer { try? manager.removeItem(at: root) }
+ let outside = manager.temporaryDirectory
+ .appendingPathComponent("outside-\(UUID().uuidString).png")
+ try Data("secret".utf8).write(to: outside)
+ defer { try? manager.removeItem(at: outside) }
+
+ let link = root.appendingPathComponent("link.png")
+ try manager.createSymbolicLink(at: link, withDestinationURL: outside)
+ #expect(!AppImageAttachmentStore.contains(link),
+ "a symlink pointed the store at a file outside it")
+ }
+
+ /// Staging copies rather than referencing: the source may be a file the
+ /// user is about to move, rename or delete, and a run that reads it later
+ /// would then read nothing.
+ @Test func stagingCopiesTheSourceAndRemovingItLeavesNothingBehind() throws {
+ let manager = FileManager.default
+ let source = manager.temporaryDirectory
+ .appendingPathComponent("source-\(UUID().uuidString).png")
+ try Data("pretend png".utf8).write(to: source)
+ defer { try? manager.removeItem(at: source) }
+
+ let store = AppImageAttachmentStore()
+ let attachment = try store.stage(source)
+ #expect(AppImageAttachmentStore.contains(attachment.fileURL))
+ #expect(manager.fileExists(atPath: attachment.fileURL.path))
+
+ try manager.removeItem(at: source)
+ #expect(manager.fileExists(atPath: attachment.fileURL.path),
+ "the staged copy died with its source")
+
+ store.remove(attachment)
+ #expect(!manager.fileExists(atPath: attachment.fileURL.path),
+ "removing an attachment left its bytes on disk")
+ }
+}
diff --git a/Tests/TurboFieldfareApp/Core/Inference/AppImageAttachmentTests.swift b/Tests/TurboFieldfareApp/Core/Inference/AppImageAttachmentTests.swift
new file mode 100644
index 00000000..38ad2dd1
--- /dev/null
+++ b/Tests/TurboFieldfareApp/Core/Inference/AppImageAttachmentTests.swift
@@ -0,0 +1,25 @@
+import Foundation
+import Testing
+@testable import TurboFieldfareAppCore
+
+@Suite struct AppImageAttachmentTests {
+ @Test func stagesThroughBoundedImmutableCopy() throws {
+ let root = FileManager.default.temporaryDirectory
+ .appendingPathComponent(UUID().uuidString, isDirectory: true)
+ defer { try? FileManager.default.removeItem(at: root) }
+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
+ let source = root.appendingPathComponent("source.png")
+ try Data("fixture".utf8).write(to: source)
+ let store = AppImageAttachmentStore(
+ directoryURL: root.appendingPathComponent("staged", isDirectory: true))
+
+ let attachment = try store.stage(source)
+
+ #expect(attachment.displayName == "source.png")
+ #expect(attachment.encodedBytes == 7)
+ #expect(try Data(contentsOf: attachment.fileURL) == Data("fixture".utf8))
+ let attributes = try FileManager.default.attributesOfItem(
+ atPath: attachment.fileURL.path)
+ #expect((attributes[.posixPermissions] as? NSNumber)?.intValue == 0o400)
+ }
+}
diff --git a/Tests/TurboFieldfareApp/Core/Inference/DecodeProtocolTests.swift b/Tests/TurboFieldfareApp/Core/Inference/DecodeProtocolTests.swift
index f8a1cfc7..042291b9 100644
--- a/Tests/TurboFieldfareApp/Core/Inference/DecodeProtocolTests.swift
+++ b/Tests/TurboFieldfareApp/Core/Inference/DecodeProtocolTests.swift
@@ -137,4 +137,27 @@ import TurboFieldfareDecodeProtocol
from: pipe.fileHandleForReading)
}
}
+ @Test func generationRequestRoundTripPreservesImageDescriptors() throws {
+ let attachment = DecodeImageAttachment(
+ id: UUID(),
+ path: "/tmp/staged-image",
+ displayName: "image.png",
+ encodedBytes: 123,
+ sha256: String(repeating: "b", count: 64))
+ let request = DecodeGenerationRequest(
+ prompt: "describe",
+ imageAttachments: [attachment],
+ maxNewTokens: 16,
+ maxContextTokens: 4096,
+ temperature: 0)
+ let pipe = Pipe()
+ try pipe.fileHandleForWriting.write(contentsOf: DecodeFrameCodec.encode(request))
+ try pipe.fileHandleForWriting.close()
+
+ let decoded = try DecodeFrameCodec.read(
+ DecodeGenerationRequest.self,
+ from: pipe.fileHandleForReading)
+ #expect(decoded.imageAttachments == [attachment])
+ }
+
}
diff --git a/Tests/TurboFieldfareApp/Core/Installation/AppVisionCompanionFixture.swift b/Tests/TurboFieldfareApp/Core/Installation/AppVisionCompanionFixture.swift
new file mode 100644
index 00000000..29d3db6f
--- /dev/null
+++ b/Tests/TurboFieldfareApp/Core/Installation/AppVisionCompanionFixture.swift
@@ -0,0 +1,77 @@
+import CryptoKit
+import Foundation
+import TurboFieldfare
+import TurboFieldfareFormat
+
+/// A text model with a valid companion pack installed beside it — the state in
+/// which the app may actually accept images.
+///
+/// Tests that need image input must build this rather than lean on the default
+/// model path: a developer machine with a real pack in `scratch/` made those
+/// tests pass for a reason that had nothing to do with the test.
+func makeVisionReadyModelInstall(_ tag: String) throws -> URL {
+ let text = try makeCompleteModelInstall(tag)
+ try installVisionCompanion(forTextModel: text)
+ return text
+}
+
+@discardableResult
+func installVisionCompanion(forTextModel text: URL) throws -> URL {
+ func digest(_ data: Data) -> String {
+ SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()
+ }
+
+ let textManifestData = try Data(
+ contentsOf: text.appendingPathComponent("manifest.json"))
+ let textManifestSHA = digest(textManifestData)
+ guard let object = try JSONSerialization.jsonObject(with: textManifestData)
+ as? [String: Any],
+ let sourceSnapshotHash = object["sourceSnapshotHash"] as? String else {
+ throw CocoaError(.fileReadCorruptFile)
+ }
+
+ let companion = try VisionPackLocation.companionURL(forTextModel: text)
+ try FileManager.default.createDirectory(
+ at: companion, withIntermediateDirectories: true)
+
+ let weights = Data(repeating: 0, count: 4_096)
+ let processor = Data("{}".utf8)
+ let files = [
+ GTurboVisionFormatV1.weightsFile: GTurboManifestFileV1(
+ size: UInt64(weights.count), sha256: digest(weights)),
+ GTurboVisionFormatV1.processorFile: GTurboManifestFileV1(
+ size: UInt64(processor.count), sha256: digest(processor)),
+ ]
+ let revision = String(repeating: "a", count: 40)
+ let manifest = GTurboVisionManifestV1(
+ modelID: "fixture/model", sourceRevision: revision,
+ sourceIndexSha256: String(repeating: "b", count: 64),
+ processorConfigSha256: digest(processor),
+ compatibleTextSourceSnapshotHash: sourceSnapshotHash,
+ compatibleTextManifestSha256: textManifestSHA,
+ files: files,
+ tensors: [.init(name: "vision.weight", executionPosition: 0,
+ offset: 0, size: 2, shape: [1], dtype: .bf16)])
+ let manifestData = try GTurboVisionManifestCodec.encode(manifest)
+ let manifestSHA = digest(manifestData)
+ let receipt = GTurboVisionReceiptV1(
+ manifestSha256: manifestSHA,
+ companionDirectoryPath: companion.standardizedFileURL.path,
+ compatibleTextManifestSha256: textManifestSHA,
+ sourceRepoID: "fixture/model", sourceRevision: revision,
+ verificationTimestamp: "fixture", toolVersion: "fixture",
+ files: files.merging([
+ GTurboVisionFormatV1.manifestFile: GTurboManifestFileV1(
+ size: UInt64(manifestData.count), sha256: manifestSHA),
+ ]) { _, new in new })
+
+ try weights.write(to: companion.appendingPathComponent(
+ GTurboVisionFormatV1.weightsFile))
+ try processor.write(to: companion.appendingPathComponent(
+ GTurboVisionFormatV1.processorFile))
+ try manifestData.write(to: companion.appendingPathComponent(
+ GTurboVisionFormatV1.manifestFile))
+ try GTurboVisionReceiptCodec.encode(receipt).write(
+ to: companion.appendingPathComponent(GTurboVisionFormatV1.receiptFile))
+ return companion
+}
diff --git a/Tests/TurboFieldfareApp/Core/Installation/AppVisionInstallProgressTests.swift b/Tests/TurboFieldfareApp/Core/Installation/AppVisionInstallProgressTests.swift
new file mode 100644
index 00000000..c19b2d65
--- /dev/null
+++ b/Tests/TurboFieldfareApp/Core/Installation/AppVisionInstallProgressTests.swift
@@ -0,0 +1,74 @@
+import Foundation
+import Testing
+@testable import TurboFieldfareAppCore
+
+/// The companion download is 1.5 GB, so it needs the same answer to "how long
+/// is this going to take" as the model download: a percentage and a remaining
+/// time, not a bar on its own.
+@Suite struct AppVisionInstallProgressTests {
+ @MainActor
+ private func makeModel(_ events: [AppModelInstallEvent])
+ throws -> (AppModel, URL) {
+ let directory = try makeCompleteModelInstall("vision-progress")
+ let model = AppModel(
+ modelDirectory: directory,
+ client: MockLifecycleInferenceClient(),
+ visionInstaller: MockVisionPackInstallerClient(
+ events: events, holdOpen: true))
+ return (model, directory)
+ }
+
+ /// Generous, because this runs alongside the GPU suites: these assertions
+ /// are about what is reported, not about how fast it gets there.
+ @MainActor
+ private func waitUntil(_ reached: @MainActor () -> Bool) async {
+ let deadline = Date().addingTimeInterval(60)
+ while !reached(), Date() < deadline {
+ try? await Task.sleep(nanoseconds: 5_000_000)
+ }
+ }
+
+ @MainActor
+ @Test func downloadingReportsAFractionAndATimeEstimate() async throws {
+ let (model, directory) = try makeModel([
+ .checking,
+ .copyingPayload(reusedBytes: 0,
+ downloadedThisRunBytes: 200_000_000,
+ totalBytes: 1_600_000_000),
+ ])
+ defer { try? FileManager.default.removeItem(at: directory) }
+
+ model.installVisionPack()
+ await waitUntil { model.visionInstallProgressFraction != nil }
+
+ let fraction = try #require(model.visionInstallProgressFraction,
+ "the download never reported progress")
+ #expect(abs(fraction - 0.125) < 0.001)
+ // The estimator needs a warmup before it will commit to a number, but
+ // the user must be told that rather than shown nothing.
+ #expect(model.visionInstallETAText != nil,
+ "the companion download showed no time estimate at all")
+ #expect(model.visionInstallETAPresentation != .hidden)
+ model.cancelVisionInstall()
+ }
+
+ /// Once the bytes stop moving the estimate is meaningless and must go.
+ @MainActor
+ @Test func theEstimateIsClearedOnceDownloadingEnds() async throws {
+ let (model, directory) = try makeModel([
+ .copyingPayload(reusedBytes: 0,
+ downloadedThisRunBytes: 200_000_000,
+ totalBytes: 1_600_000_000),
+ .finalizing,
+ ])
+ defer { try? FileManager.default.removeItem(at: directory) }
+
+ model.installVisionPack()
+ await waitUntil { model.visionInstallState == .finalizing }
+ try #require(model.visionInstallState == .finalizing,
+ "the install never reached finalizing")
+ #expect(model.visionInstallETAText == nil)
+ #expect(model.visionInstallETAPresentation == .hidden)
+ model.cancelVisionInstall()
+ }
+}
diff --git a/Tests/TurboFieldfareApp/Core/Installation/AppVisionPackLayoutProbeTests.swift b/Tests/TurboFieldfareApp/Core/Installation/AppVisionPackLayoutProbeTests.swift
new file mode 100644
index 00000000..ea4ac725
--- /dev/null
+++ b/Tests/TurboFieldfareApp/Core/Installation/AppVisionPackLayoutProbeTests.swift
@@ -0,0 +1,92 @@
+import Foundation
+import Testing
+@testable import TurboFieldfareAppCore
+
+/// "This model cannot host a companion pack" and "the pack on disk is damaged"
+/// are different answers and need different states.
+///
+/// `VisionPackLocation.companionURL` throws for exactly one reason — a directory
+/// name that does not end in `.gturbo` — and reporting that as `.partial`
+/// printed a raw `invalidTextModelPath(...)` under "Needs repair" and offered a
+/// Repair button for a pack that could never be located.
+@Suite struct AppVisionPackLayoutProbeTests {
+ @Test func adirectoryThatCannotHostAPackIsNotReportedAsDamaged() throws {
+ let root = try Self.makeTemporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let model = root.appendingPathComponent("gemma4-model", isDirectory: true)
+ try FileManager.default.createDirectory(at: model, withIntermediateDirectories: true)
+
+ let status = AppVisionPackInstallationProbe.status(at: model)
+
+ #expect(status == .unsupportedLayout)
+ if case .partial(let message) = status {
+ Issue.record("a non-.gturbo layout was reported as damaged: \(message)")
+ }
+ }
+
+ /// The `.gturbo` layout with no companion beside it is the ordinary
+ /// "not installed yet" case, and has to stay distinguishable from the one
+ /// above — that is the whole point of the new state.
+ @Test func agturboDirectoryWithNoCompanionIsMissingRatherThanUnsupported() throws {
+ let root = try Self.makeTemporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let model = root.appendingPathComponent("gemma4.gturbo", isDirectory: true)
+ try FileManager.default.createDirectory(at: model, withIntermediateDirectories: true)
+
+ #expect(AppVisionPackInstallationProbe.status(at: model) == .missing)
+ }
+
+ /// A layout with nowhere to put a pack cannot be repaired by downloading
+ /// one, so the install action must not be offered.
+ @MainActor
+ @Test func alayoutThatCannotHostAPackIsNotOfferedAnInstall() throws {
+ let root = try Self.makeTemporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let model = root.appendingPathComponent("gemma4-model", isDirectory: true)
+ try FileManager.default.createDirectory(at: model, withIntermediateDirectories: true)
+
+ let app = AppModel(modelDirectory: model)
+
+ #expect(app.visionInstallationStatus == .unsupportedLayout)
+ #expect(!app.canInstallVisionPack,
+ "a pack was offered for a directory that cannot hold one")
+ #expect(!app.isVisionPackInstalled)
+ }
+
+ @MainActor
+ @Test func unsupportedHardwareIsNotOfferedAVisionInstall() throws {
+ let model = try makeCompleteModelInstall("unsupported-vision-hardware")
+ defer { try? FileManager.default.removeItem(at: model) }
+ let installer = MockVisionPackInstallerClient(events: [.checking])
+ let supported = AppModel(
+ modelDirectory: model,
+ visionInstaller: installer,
+ visionRuntimeSupported: true)
+ let unsupported = AppModel(
+ modelDirectory: model,
+ visionInstaller: installer,
+ visionRuntimeSupported: false)
+
+ #expect(supported.canInstallVisionPack,
+ "the fixture did not otherwise qualify for installation")
+ #expect(!unsupported.canInstallVisionPack)
+ unsupported.installVisionPack()
+ #expect(unsupported.visionInstallState == .idle,
+ "unsupported hardware started a companion download")
+
+ unsupported.visionInstallState = .readyToActivate(model)
+ #expect(!unsupported.canActivateVisionPack)
+ unsupported.activateVisionPack()
+ #expect(installer.activationCount == 0,
+ "unsupported hardware started companion activation")
+ }
+
+ private static func makeTemporaryDirectory() throws -> URL {
+ let directory = FileManager.default.temporaryDirectory
+ .appendingPathComponent("vision-layout-probe-\(UUID().uuidString)",
+ isDirectory: true)
+ try FileManager.default.createDirectory(
+ at: directory, withIntermediateDirectories: true)
+ return directory
+ }
+}
diff --git a/Tests/TurboFieldfareApp/Core/Installation/CancellableDetachedWorkTests.swift b/Tests/TurboFieldfareApp/Core/Installation/CancellableDetachedWorkTests.swift
new file mode 100644
index 00000000..b222d3cf
--- /dev/null
+++ b/Tests/TurboFieldfareApp/Core/Installation/CancellableDetachedWorkTests.swift
@@ -0,0 +1,75 @@
+import Foundation
+import Synchronization
+import Testing
+@testable import TurboFieldfareAppCore
+
+/// Cancelling work that runs off the calling task.
+///
+/// The vision pack's activation hash ran inside a bare `Task.detached`, which
+/// inherits nothing — so its cooperative `Task.checkCancellation()` tested a
+/// flag no one ever set. Cancel did nothing: the multi-minute hash ran to the
+/// end and the pack activated anyway, while the UI sat on "Cancelling" with
+/// every model action disabled. The suite's own mock hid it by running the
+/// check inline in the caller's task, where cancellation does propagate.
+@Suite struct CancellableDetachedWorkTests {
+ private let client = RepackVisionPackInstallerClient()
+
+ /// The regression: without the forwarding this hangs until the body
+ /// finishes on its own and returns normally, instead of throwing.
+ @Test func cancellingTheCallerCancelsTheDetachedBody() async throws {
+ let started = Mutex(false)
+ let observedCancellation = Mutex(false)
+
+ let task = Task {
+ try await client.runCancellableDetached {
+ started.withLock { $0 = true }
+ // Stands in for the verification hash: cooperative, and long
+ // enough that it cannot finish before the cancel lands. Bounded
+ // so that losing the forwarding fails this test instead of
+ // hanging it — the body then simply returns.
+ let deadline = Date().addingTimeInterval(3)
+ while !Task.isCancelled, Date() < deadline {
+ usleep(1_000)
+ }
+ guard Task.isCancelled else { return }
+ observedCancellation.withLock { $0 = true }
+ try Task.checkCancellation()
+ }
+ }
+
+ let deadline = Date().addingTimeInterval(5)
+ while !started.withLock({ $0 }), Date() < deadline {
+ try await Task.sleep(for: .milliseconds(5))
+ }
+ #expect(started.withLock { $0 }, "the body never ran")
+
+ task.cancel()
+ await #expect(throws: CancellationError.self) { try await task.value }
+ #expect(observedCancellation.withLock { $0 },
+ "the detached body never saw the cancellation")
+ }
+
+ /// Work that is not cancelled still runs and returns its value: forwarding
+ /// cancellation must not turn into cancelling everything.
+ @Test func uncancelledWorkReturnsItsValue() async throws {
+ let ran = Mutex(false)
+
+ let value = try await client.runCancellableDetached { () -> Int in
+ ran.withLock { $0 = true }
+ return 41 + 1
+ }
+
+ #expect(value == 42)
+ #expect(ran.withLock { $0 })
+ }
+
+ /// A failure inside the body reaches the caller unchanged, rather than
+ /// being flattened into a cancellation.
+ @Test func aFailureInTheBodyPropagates() async throws {
+ struct Failure: Error, Equatable {}
+
+ await #expect(throws: Failure.self) {
+ try await client.runCancellableDetached { throw Failure() }
+ }
+ }
+}
diff --git a/Tests/TurboFieldfareApp/Core/State/AppImageAddConcurrencyTests.swift b/Tests/TurboFieldfareApp/Core/State/AppImageAddConcurrencyTests.swift
new file mode 100644
index 00000000..54f13fd5
--- /dev/null
+++ b/Tests/TurboFieldfareApp/Core/State/AppImageAddConcurrencyTests.swift
@@ -0,0 +1,134 @@
+import Foundation
+import Testing
+@testable import TurboFieldfareAppCore
+
+/// Two image adds can be in flight at once — the file picker and a drop, or a
+/// drop and a paste — and `canRun` is gated on none of them being in flight.
+///
+/// `isAddingImages` was a Bool, so whichever batch finished first cleared it
+/// while the other was still copying: Generate reopened, the run snapshotted a
+/// partial set, and the remaining images were appended afterwards where
+/// `removeImage` and `clearImages` are no-ops. It is a count now, and the risk a
+/// count carries is the opposite one — an unbalanced decrement that leaves
+/// Generate disabled forever — so both directions are pinned here.
+@Suite struct AppImageAddConcurrencyTests {
+ @MainActor
+ @Test func overlappingAddsAllLandAndReopenGenerateExactlyOnce() async throws {
+ let directory = try makeVisionReadyModelInstall("image-add-overlap")
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let staging = try Self.makeTemporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: staging) }
+
+ let model = AppModel(
+ modelDirectory: directory,
+ attachmentStore: AppImageAttachmentStore(directoryURL: staging))
+ model.maxContextTokens = AppContextLengthOption.sixtyFourK.tokens
+ try #require(model.maximumImageAttachments >= 3)
+
+ let first = try Self.writePNG(named: "first.png", in: staging)
+ let second = try Self.writePNG(named: "second.png", in: staging)
+ let third = try Self.writePNG(named: "third.png", in: staging)
+
+ // Both batches admitted before either can finish: this is the exact
+ // interleaving the Bool got wrong.
+ model.addImages([first, second])
+ model.addImages([third])
+ #expect(model.isAddingImages)
+ #expect(!model.canRun, "Generate was live while images were still copying")
+
+ try await Self.untilIdle(model)
+
+ #expect(model.imageAttachments.count == 3,
+ "only \(model.imageAttachments.count) of 3 images survived two overlapping adds")
+ #expect(!model.isAddingImages,
+ "the counter never returned to zero, so Generate stays disabled forever")
+ }
+
+ /// A failing batch has to give its count back too. The error path decrements
+ /// on its own line rather than through the success path's `defer`, which is
+ /// exactly the kind of asymmetry that strands the counter above zero.
+ @MainActor
+ @Test func afailedBatchStillReleasesItsCount() async throws {
+ let directory = try makeVisionReadyModelInstall("image-add-failure")
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let staging = try Self.makeTemporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: staging) }
+
+ let model = AppModel(
+ modelDirectory: directory,
+ attachmentStore: AppImageAttachmentStore(directoryURL: staging))
+
+ model.addImages([staging.appendingPathComponent("does-not-exist.png")])
+ #expect(model.isAddingImages)
+
+ try await Self.untilIdle(model)
+
+ #expect(!model.isAddingImages,
+ "a failed staging batch left the counter above zero")
+ #expect(model.imageAttachments.isEmpty)
+ #expect(model.imageAttachmentError != nil, "the failure was not reported")
+ }
+
+ /// Interleaving a data paste with a file add exercises the second entry
+ /// point into the counter.
+ @MainActor
+ @Test func adataPasteAndAFileAddShareTheSameCount() async throws {
+ let directory = try makeVisionReadyModelInstall("image-add-mixed")
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let staging = try Self.makeTemporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: staging) }
+
+ let model = AppModel(
+ modelDirectory: directory,
+ attachmentStore: AppImageAttachmentStore(directoryURL: staging))
+ model.maxContextTokens = AppContextLengthOption.sixtyFourK.tokens
+ try #require(model.maximumImageAttachments >= 2)
+
+ let file = try Self.writePNG(named: "from-disk.png", in: staging)
+ model.addImages([file])
+ model.addImageData(try Self.pngData(), displayName: "pasted.png")
+ #expect(model.isAddingImages)
+ #expect(!model.canRun)
+
+ try await Self.untilIdle(model)
+
+ #expect(model.imageAttachments.count == 2)
+ #expect(!model.isAddingImages)
+ }
+
+ /// Polls rather than sleeps: staging runs on a detached task and reports
+ /// back on the main actor, so yielding until the counter settles is the
+ /// deterministic wait. The bound is a failure, not a timeout to tune.
+ @MainActor
+ private static func untilIdle(_ model: AppModel) async throws {
+ for _ in 0..<2_000 {
+ if !model.isAddingImages { return }
+ try await Task.sleep(nanoseconds: 5_000_000)
+ }
+ Issue.record("image staging never finished")
+ }
+
+ private static func makeTemporaryDirectory() throws -> URL {
+ let directory = FileManager.default.temporaryDirectory
+ .appendingPathComponent("image-add-\(UUID().uuidString)", isDirectory: true)
+ try FileManager.default.createDirectory(
+ at: directory, withIntermediateDirectories: true)
+ return directory
+ }
+
+ /// The smallest thing `ImageMetadataReader` will accept: a real 1x1 PNG.
+ private static func pngData() throws -> Data {
+ let base64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42m"
+ + "NkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=="
+ guard let data = Data(base64Encoded: base64) else {
+ throw CocoaError(.fileReadCorruptFile)
+ }
+ return data
+ }
+
+ private static func writePNG(named name: String, in directory: URL) throws -> URL {
+ let url = directory.appendingPathComponent(name)
+ try pngData().write(to: url)
+ return url
+ }
+}
diff --git a/Tests/TurboFieldfareApp/Core/State/AppImageAttachmentLifetimeTests.swift b/Tests/TurboFieldfareApp/Core/State/AppImageAttachmentLifetimeTests.swift
new file mode 100644
index 00000000..c10c1655
--- /dev/null
+++ b/Tests/TurboFieldfareApp/Core/State/AppImageAttachmentLifetimeTests.swift
@@ -0,0 +1,548 @@
+import Darwin
+import Foundation
+import Testing
+import TurboFieldfare
+@testable import TurboFieldfareAppCore
+
+/// Who owns a staged image file, and when it is deleted. Every case here used
+/// to leak a full-size copy or delete one that was still on screen.
+@Suite(.serialized) struct AppImageAttachmentLifetimeTests {
+ /// `addImages` is gated on the vision runtime, and it is the only way in:
+ /// `imageAttachments` is read-only from outside, which is what keeps the
+ /// ownership rules in one place.
+ private func withVisionEnabled<T>(_ body: () throws -> T) rethrows -> T {
+ let previous = ProcessInfo.processInfo.environment[
+ "TURBO_FIELDFARE_VISION_RUNTIME"]
+ setenv("TURBO_FIELDFARE_VISION_RUNTIME", "1", 1)
+ defer {
+ if let previous {
+ setenv("TURBO_FIELDFARE_VISION_RUNTIME", previous, 1)
+ } else {
+ unsetenv("TURBO_FIELDFARE_VISION_RUNTIME")
+ }
+ }
+ return try body()
+ }
+
+ @MainActor
+ private func attach(_ model: AppModel, _ urls: [URL]) async {
+ withVisionEnabled { model.addImages(urls) }
+ let deadline = Date().addingTimeInterval(5)
+ while model.isAddingImages, Date() < deadline {
+ try? await Task.sleep(nanoseconds: 5_000_000)
+ }
+ }
+
+ private func makeStore() -> (root: URL, store: AppImageAttachmentStore) {
+ let root = FileManager.default.temporaryDirectory
+ .appendingPathComponent("attachments-\(UUID().uuidString)", isDirectory: true)
+ return (root, AppImageAttachmentStore(
+ directoryURL: root.appendingPathComponent("staged", isDirectory: true)))
+ }
+
+ private func stagedFileCount(_ store: AppImageAttachmentStore) -> Int {
+ guard let walker = FileManager.default.enumerator(
+ at: store.directoryURL,
+ includingPropertiesForKeys: [.isRegularFileKey]) else { return 0 }
+ var count = 0
+ for case let url as URL in walker {
+ if (try? url.resourceValues(forKeys: [.isRegularFileKey]))?
+ .isRegularFile == true { count += 1 }
+ }
+ return count
+ }
+
+ private func writeSource(_ root: URL, _ name: String, _ bytes: String) throws -> URL {
+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
+ let url = root.appendingPathComponent(name)
+ try Data(bytes.utf8).write(to: url)
+ return url
+ }
+
+ /// Adding images is all-or-nothing, so a batch that fails partway used to
+ /// leave the copies it had already made referenced by nothing at all.
+ @MainActor
+ @Test func aFailedBatchLeavesNoStagedFilesBehind() async throws {
+ let (root, store) = makeStore()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let good = try writeSource(root, "good.png", "fixture")
+ let missing = root.appendingPathComponent("not-there.png")
+
+ let directory = try makeVisionReadyModelInstall("lifetime-failed-batch")
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let model = AppModel(modelDirectory: directory, attachmentStore: store)
+ await attach(model, [good, missing])
+
+ #expect(model.imageAttachments.isEmpty)
+ #expect(model.imageAttachmentError != nil, "the failure must be reported")
+ #expect(stagedFileCount(store) == 0,
+ "the images staged before the failure were orphaned")
+ }
+
+ /// The transcript renders from the files it was handed. Clearing the
+ /// composer used to delete them out from under a finished answer.
+ @Test func aRetainedImageSurvivesTheComposerDeletingItsCopy() throws {
+ let (root, store) = makeStore()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let source = try writeSource(root, "source.png", "fixture")
+ let staged = try store.stage(source)
+
+ let retained = try store.retain(staged)
+ #expect(retained.fileURL != staged.fileURL)
+ #expect(retained.sha256 == staged.sha256)
+ #expect(retained.id == staged.id)
+
+ store.remove(staged)
+ #expect(!FileManager.default.fileExists(atPath: staged.fileURL.path))
+ #expect(try Data(contentsOf: retained.fileURL) == Data("fixture".utf8),
+ "the transcript's copy was deleted with the composer's")
+
+ // A link, not a second copy: one inode, and the last link frees it.
+ var link = stat()
+ #expect(lstat(retained.fileURL.path, &link) == 0)
+ #expect(link.st_nlink == 1)
+ store.remove(retained)
+ #expect(!FileManager.default.fileExists(atPath: retained.fileURL.path))
+ }
+
+ /// A cleared prompt used to leave the images attached, so the next Run
+ /// silently sent them with a completely different message.
+ @MainActor
+ @Test func clearingTheSentPromptAlsoDropsItsImages() async throws {
+ let (root, store) = makeStore()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let source = try writeSource(root, "source.png", "fixture")
+
+ let directory = try makeVisionReadyModelInstall("lifetime-clear")
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let client = MockInferenceClient(response: "answer", tokenDelayNanos: 1)
+ let model = AppModel(modelDirectory: directory, client: client,
+ attachmentStore: store)
+ model.loadState = .ready(modelDirectory: directory, loadSeconds: 1)
+ model.setSentPromptBehavior(.clear)
+ await attach(model, [source])
+ #expect(model.imageAttachments.count == 1)
+ model.promptText = "describe it"
+ model.maxNewTokensOverride = 1
+ model.run()
+
+ #expect(model.promptText.isEmpty)
+ #expect(model.imageAttachments.isEmpty,
+ "images outlived the prompt they were sent with")
+ // The transcript still has them, from its own files.
+ #expect(model.outputImageAttachments.count == 1)
+ let shown = try #require(model.outputImageAttachments.first)
+ #expect(try Data(contentsOf: shown.fileURL) == Data("fixture".utf8))
+
+ for _ in 0..<200 where model.isRunning {
+ try? await Task.sleep(nanoseconds: 5_000_000)
+ }
+ // Clearing the transcript is what finally frees them.
+ model.clearOutput()
+ #expect(model.outputImageAttachments.isEmpty)
+ #expect(stagedFileCount(store) == 0)
+ }
+
+ /// What the test above could not see. It asserted the composer was emptied
+ /// and the transcript still rendered, both of which were true while every
+ /// image run under this setting failed: the request still pointed at the
+ /// composer's paths, and `.clear` unlinked them before the run opened them.
+ /// The transcript's copies are hard links at *different* paths, so they
+ /// never covered for it. Fails on the old code now that the mock opens what
+ /// it is handed.
+ @MainActor
+ @Test func aClearedPromptLeavesTheRunAbleToOpenItsImages() async throws {
+ let (root, store) = makeStore()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let source = try writeSource(root, "source.png", "fixture")
+
+ let directory = try makeVisionReadyModelInstall("lifetime-clear-runs")
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let client = MockInferenceClient(response: "answer", tokenDelayNanos: 1)
+ let model = AppModel(modelDirectory: directory, client: client,
+ attachmentStore: store)
+ model.loadState = .ready(modelDirectory: directory, loadSeconds: 1)
+ model.setSentPromptBehavior(.clear)
+ await attach(model, [source])
+ model.promptText = "describe it"
+ model.maxNewTokensOverride = 1
+ model.run()
+
+ for _ in 0..<400 where model.isRunning {
+ try? await Task.sleep(nanoseconds: 5_000_000)
+ }
+ #expect(model.error == nil,
+ "the run could not open the images the composer had just deleted")
+ #expect(!model.outputText.isEmpty, "the run produced nothing")
+ }
+
+ /// Without its own reference nothing guarantees the files outlive the
+ /// composer, so the run is refused instead of started against files that
+ /// are about to be removed. It must not fall back to the composer's own
+ /// attachment either: that gave one file two owners, and whichever side
+ /// cleaned up first deleted the other's image.
+ @MainActor
+ @Test func aRunIsRefusedWhenTheTranscriptCannotTakeItsOwnReference() async throws {
+ let (root, store) = makeStore()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let source = try writeSource(root, "source.png", "fixture")
+
+ let directory = try makeVisionReadyModelInstall("lifetime-retain-fails")
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let client = MockInferenceClient(response: "answer", tokenDelayNanos: 1)
+ let model = AppModel(modelDirectory: directory, client: client,
+ attachmentStore: store)
+ model.loadState = .ready(modelDirectory: directory, loadSeconds: 1)
+ await attach(model, [source])
+ model.promptText = "describe it"
+
+ // A regular file where `retain` needs to create a directory, so the
+ // hard link cannot be made and every retain fails the same way.
+ try Data().write(to: store.directoryURL
+ .appendingPathComponent("retained", isDirectory: false))
+
+ model.run()
+
+ #expect(!model.isRunning, "the run started without stable references")
+ #expect(model.error != nil, "the refusal was silent")
+ #expect(model.outputImageAttachments.isEmpty,
+ "the transcript aliased the composer's own file")
+ #expect(model.imageAttachments.count == 1,
+ "a refused run must leave the composer's images alone")
+ let staged = try #require(model.imageAttachments.first)
+ #expect(FileManager.default.fileExists(atPath: staged.fileURL.path),
+ "a refused run deleted the composer's staged copy")
+ }
+
+ /// Every early return in `addImages` owns the promise directory. The
+ /// staging task's `defer` is the only other thing that deletes it, and a
+ /// return above that task means the task never exists — while the sweep
+ /// covers only the staging root, so nothing in the app ever reclaims it.
+ @MainActor
+ @Test func aDropRefusedDuringARunIsExplainedAndDiscardsItsPromiseDirectory() async throws {
+ let (root, store) = makeStore()
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ let directory = try makeVisionReadyModelInstall("lifetime-promise-leak")
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let client = MockInferenceClient(response: "answer", tokenDelayNanos: 1)
+ client.holdsDuringPrefill = true
+ let model = AppModel(modelDirectory: directory, client: client,
+ attachmentStore: store)
+ model.loadState = .ready(modelDirectory: directory, loadSeconds: 1)
+ model.promptText = "hello"
+ model.run()
+ #expect(model.isRunning)
+
+ let promises = root.appendingPathComponent("promises", isDirectory: true)
+ let dropped = try writeSource(promises, "dropped.png", "promised")
+ withVisionEnabled {
+ model.addImages([dropped], discardingSourceDirectory: promises)
+ }
+
+ #expect(model.imageAttachmentError != nil,
+ "the drop vanished with nothing said about it")
+ #expect(!FileManager.default.fileExists(atPath: promises.path),
+ "the promise directory outlived the drop that created it")
+ model.cancel()
+ }
+
+ /// Staging copies the files the request will carry, so starting a run while
+ /// it is in flight sent a request without those images and then landed them
+ /// on the next message instead.
+ @MainActor
+ @Test func aRunCannotStartWhileItsImagesAreStillStaging() async throws {
+ let (root, store) = makeStore()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let source = try writeSource(root, "source.png", "fixture")
+
+ let directory = try makeVisionReadyModelInstall("lifetime-staging-race")
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let model = AppModel(modelDirectory: directory,
+ client: MockInferenceClient(tokenDelayNanos: 1),
+ attachmentStore: store)
+ model.loadState = .ready(modelDirectory: directory, loadSeconds: 1)
+ model.promptText = "describe it"
+ #expect(model.canRun)
+
+ withVisionEnabled { model.addImages([source]) }
+ #expect(model.isAddingImages)
+ #expect(!model.canRun,
+ "a run could start while its own images were still being copied")
+
+ let deadline = Date().addingTimeInterval(5)
+ while model.isAddingImages, Date() < deadline {
+ try? await Task.sleep(nanoseconds: 5_000_000)
+ }
+ #expect(model.canRun)
+ #expect(model.imageAttachments.count == 1)
+ }
+
+ /// Two adds in flight at once — the picker and a drop — each sized itself
+ /// against the count it saw at admission, so the second to land appended
+ /// past the cap. The surplus copies also have to be deleted, or the clamp
+ /// just trades an over-full composer for staged files nothing references.
+ @MainActor
+ @Test func overlappingAddsCannotPushPastTheCap() async throws {
+ let (root, store) = makeStore()
+ defer { try? FileManager.default.removeItem(at: root) }
+
+ let directory = try makeVisionReadyModelInstall("lifetime-overlapping-adds")
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let model = AppModel(modelDirectory: directory,
+ client: MockInferenceClient(tokenDelayNanos: 1),
+ attachmentStore: store)
+ let capacity = model.maximumImageAttachments
+ let first = try (0..<capacity).map {
+ try writeSource(root, "first-\($0).png", "fixture-\($0)")
+ }
+ let second = try (0..<capacity).map {
+ try writeSource(root, "second-\($0).png", "other-\($0)")
+ }
+
+ // Both batches admit themselves against a composer that is still empty.
+ withVisionEnabled { model.addImages(first) }
+ withVisionEnabled { model.addImages(second) }
+
+ let deadline = Date().addingTimeInterval(10)
+ while model.isAddingImages, Date() < deadline {
+ try? await Task.sleep(nanoseconds: 5_000_000)
+ }
+ try? await Task.sleep(nanoseconds: 100_000_000)
+
+ #expect(model.imageAttachments.count == capacity,
+ "the second batch appended past the cap")
+ #expect(stagedFileCount(store) == capacity,
+ "the copies that did not fit were left staged and unreferenced")
+ }
+
+ /// With the prompt kept, the composer keeps its images too — and clearing
+ /// them must still not disturb the answer already on screen.
+ @MainActor
+ @Test func keepingTheSentPromptKeepsItsImagesWithoutSharingFiles() async throws {
+ let (root, store) = makeStore()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let source = try writeSource(root, "source.png", "fixture")
+
+ let directory = try makeVisionReadyModelInstall("lifetime-keep")
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let client = MockInferenceClient(response: "answer", tokenDelayNanos: 1)
+ let model = AppModel(modelDirectory: directory, client: client,
+ attachmentStore: store)
+ model.loadState = .ready(modelDirectory: directory, loadSeconds: 1)
+ model.setSentPromptBehavior(.keep)
+ await attach(model, [source])
+ model.promptText = "describe it"
+ model.maxNewTokensOverride = 1
+ model.run()
+ for _ in 0..<200 where model.isRunning {
+ try? await Task.sleep(nanoseconds: 5_000_000)
+ }
+
+ #expect(model.imageAttachments.count == 1)
+ model.clearImages()
+ #expect(model.imageAttachments.isEmpty)
+ let shown = try #require(model.outputImageAttachments.first)
+ #expect(try Data(contentsOf: shown.fileURL) == Data("fixture".utf8),
+ "clearing the composer deleted the transcript's image")
+ }
+
+ /// Quitting is the one moment every staged file is certainly unwanted, and
+ /// nothing called `removeAll()` at all.
+ @MainActor
+ @Test func releasingEverythingEmptiesTheStore() async throws {
+ let (root, store) = makeStore()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let source = try writeSource(root, "source.png", "fixture")
+ let directory = try makeVisionReadyModelInstall("lifetime-release-all")
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let model = AppModel(modelDirectory: directory, attachmentStore: store)
+ await attach(model, [source, source])
+ #expect(stagedFileCount(store) == 2)
+
+ model.releaseAllAttachments()
+ #expect(model.imageAttachments.isEmpty)
+ #expect(!FileManager.default.fileExists(atPath: store.directoryURL.path))
+ }
+
+ /// A run killed before it could clean up leaves its whole directory. Only a
+ /// later run can reclaim it, and only if it can tell live from dead.
+ @Test func sweepReclaimsDeadRunsAndSparesLiveOnes() throws {
+ let manager = FileManager.default
+ let root = manager.temporaryDirectory
+ .appendingPathComponent("attachment-sweep-\(UUID().uuidString)",
+ isDirectory: true)
+ defer { try? manager.removeItem(at: root) }
+ let dead = root.appendingPathComponent("pid-4194300", isDirectory: true)
+ let live = root.appendingPathComponent("pid-\(getpid())", isDirectory: true)
+ let stray = root.appendingPathComponent(UUID().uuidString, isDirectory: true)
+ for directory in [dead, live, stray] {
+ try manager.createDirectory(at: directory, withIntermediateDirectories: true)
+ try Data([0x1]).write(to: directory.appendingPathComponent("image"))
+ }
+
+ let reclaimed = AppImageAttachmentStore.sweepAbandoned(in: root)
+ #expect(reclaimed.contains("pid-4194300"))
+ #expect(reclaimed.contains(stray.lastPathComponent))
+ #expect(!manager.fileExists(atPath: dead.path))
+ #expect(manager.fileExists(atPath: live.appendingPathComponent("image").path),
+ "the sweep deleted a live run's images")
+ }
+}
+
+/// Images can arrive with no file behind them: copied from another app, or
+/// dragged from one that only promises to write the bytes later. Both used to
+/// be refused with an instruction to go and find a file.
+@Suite(.serialized) struct AppPastedImageTests {
+ private func withVisionEnabled<T>(_ body: () throws -> T) rethrows -> T {
+ let previous = ProcessInfo.processInfo.environment[
+ "TURBO_FIELDFARE_VISION_RUNTIME"]
+ setenv("TURBO_FIELDFARE_VISION_RUNTIME", "1", 1)
+ defer {
+ if let previous {
+ setenv("TURBO_FIELDFARE_VISION_RUNTIME", previous, 1)
+ } else {
+ unsetenv("TURBO_FIELDFARE_VISION_RUNTIME")
+ }
+ }
+ return try body()
+ }
+
+ private func makeStore() -> (root: URL, store: AppImageAttachmentStore) {
+ let root = FileManager.default.temporaryDirectory
+ .appendingPathComponent("pasted-\(UUID().uuidString)", isDirectory: true)
+ return (root, AppImageAttachmentStore(
+ directoryURL: root.appendingPathComponent("staged", isDirectory: true)))
+ }
+
+ @Test func stagingBytesProducesTheSameSealedCopyAsAFile() throws {
+ let (root, store) = makeStore()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let bytes = Data("pretend png".utf8)
+
+ let attachment = try store.stage(data: bytes, displayName: "Pasted image.png")
+ #expect(attachment.displayName == "Pasted image.png")
+ #expect(attachment.encodedBytes == bytes.count)
+ #expect(try Data(contentsOf: attachment.fileURL) == bytes)
+ let attributes = try FileManager.default.attributesOfItem(
+ atPath: attachment.fileURL.path)
+ #expect((attributes[.posixPermissions] as? NSNumber)?.intValue == 0o400,
+ "a pasted image must be sealed like any other")
+ }
+
+ @Test func pastedBytesAreBoundedTheSameWayAFileIs() throws {
+ let (root, store) = makeStore()
+ defer { try? FileManager.default.removeItem(at: root) }
+ #expect(throws: VisionImageError.self) {
+ _ = try store.stage(data: Data(), displayName: "empty.png")
+ }
+ let limit = VisionImageLimits().maximumEncodedBytes
+ #expect(throws: VisionImageError.self) {
+ _ = try store.stage(
+ data: Data(repeating: 0x41, count: limit + 1),
+ displayName: "huge.png")
+ }
+ }
+
+ @MainActor
+ @Test func pastedImagesJoinTheComposerAndRespectItsCap() async throws {
+ let (root, store) = makeStore()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let directory = try makeVisionReadyModelInstall("pasted-cap")
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let model = AppModel(modelDirectory: directory, attachmentStore: store)
+ // The smallest context the app offers, so the cap is reached without
+ // staging dozens of files.
+ model.maxContextTokens = AppContextLengthOption.fourK.tokens
+ let capacity = model.maximumImageAttachments
+
+ for index in 0..<(capacity + 1) {
+ withVisionEnabled {
+ model.addImageData(Data("image \(index)".utf8),
+ displayName: "Pasted image.png")
+ }
+ let deadline = Date().addingTimeInterval(5)
+ while model.isAddingImages, Date() < deadline {
+ try? await Task.sleep(nanoseconds: 5_000_000)
+ }
+ }
+
+ #expect(model.imageAttachments.count == capacity)
+ #expect(model.imageAttachmentError != nil,
+ "the one past the cap was accepted silently")
+ model.releaseAllAttachments()
+ }
+}
+
+/// The runtime flag says this build can use images; the companion pack says
+/// this model can. Gating the composer on the flag alone offered an
+/// Add-images button with no tower behind it, and the failure only appeared
+/// when the user pressed Generate.
+@Suite(.serialized) struct AppImageAvailabilityTests {
+ private func withVisionEnabled<T>(_ body: () throws -> T) rethrows -> T {
+ let previous = ProcessInfo.processInfo.environment[
+ "TURBO_FIELDFARE_VISION_RUNTIME"]
+ setenv("TURBO_FIELDFARE_VISION_RUNTIME", "1", 1)
+ defer {
+ if let previous {
+ setenv("TURBO_FIELDFARE_VISION_RUNTIME", previous, 1)
+ } else {
+ unsetenv("TURBO_FIELDFARE_VISION_RUNTIME")
+ }
+ }
+ return try body()
+ }
+
+ @MainActor
+ @Test func imageInputNeedsTheCompanionAndNotJustTheFlag() throws {
+ let directory = try makeCompleteModelInstall("image-availability")
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let model = AppModel(modelDirectory: directory)
+ #expect(model.isModelInstalled)
+ #expect(!model.isVisionPackInstalled)
+
+ withVisionEnabled {
+ #expect(model.visionRuntimeEnabled)
+ #expect(!model.isImageInputAvailable,
+ "the composer offered images with no companion installed")
+ }
+ #expect(!model.isImageInputAvailable)
+ }
+
+ /// The app always releases the image tower after each image, so nothing in
+ /// the UI can ask for the other policy. It used to be a Memory setting; the
+ /// figure that would have justified it — about 1 GB of page cache held —
+ /// is charged to no process and so could never be shown honestly beside the
+ /// memory it was traded against.
+ @MainActor
+ @Test func theAppAlwaysReleasesTheImageTower() throws {
+ let directory = try makeVisionReadyModelInstall("residency")
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let model = AppModel(modelDirectory: directory,
+ client: MockLifecycleInferenceClient())
+ #expect(model.runtimeOptions.visionResidencyPolicy == .onDemand)
+ model.promptText = "go"
+ #expect(try model.makeRequest().runtimeOptions
+ .visionResidencyPolicy == .onDemand,
+ "a run asked for a residency the app no longer offers")
+ }
+
+ /// The switch is only meaningful once the tower exists.
+ @MainActor
+ @Test func residencyIsOnlyOfferedWithTheCompanionInstalled() throws {
+ let withPack = try makeVisionReadyModelInstall("residency-with")
+ let withoutPack = try makeCompleteModelInstall("residency-without")
+ defer {
+ try? FileManager.default.removeItem(at: withPack)
+ try? FileManager.default.removeItem(at: withoutPack)
+ }
+ setenv("TURBO_FIELDFARE_VISION_RUNTIME", "1", 1)
+ defer { unsetenv("TURBO_FIELDFARE_VISION_RUNTIME") }
+
+ #expect(AppModel(modelDirectory: withPack).isImageInputAvailable)
+ #expect(!AppModel(modelDirectory: withoutPack).isImageInputAvailable)
+ #expect(!AppModel(modelDirectory: withPack, visionRuntimeSupported: false)
+ .isImageInputAvailable,
+ "an installed pack exposed image input on unsupported hardware")
+ }
+}
diff --git a/Tests/TurboFieldfareApp/Core/State/AppImageCapacityTests.swift b/Tests/TurboFieldfareApp/Core/State/AppImageCapacityTests.swift
new file mode 100644
index 00000000..40b3d70d
--- /dev/null
+++ b/Tests/TurboFieldfareApp/Core/State/AppImageCapacityTests.swift
@@ -0,0 +1,211 @@
+import Foundation
+import Testing
+import TurboFieldfare
+@testable import TurboFieldfareAppCore
+
+/// The app used to allow four images no matter the context, while the server
+/// derived a budget from it. The same set of images was therefore accepted over
+/// the API and refused in the app. Both now answer from one rule, so these
+/// tests are as much about the rule being shared as about the numbers.
+@Suite struct AppImageCapacityTests {
+ @MainActor
+ @Test(arguments: AppContextLengthOption.allCases)
+ func capacityFollowsTheContext(option: AppContextLengthOption) throws {
+ let directory = try makeVisionReadyModelInstall("capacity-\(option.tokens)")
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let model = AppModel(modelDirectory: directory)
+ model.maxContextTokens = option.tokens
+
+ let expected = VisionImageTokenBudget.capacity(
+ maxContext: option.tokens,
+ reservedTextTokens: AppModel.reservedPromptTokens)
+ #expect(model.maximumImageAttachments == max(1, expected))
+ // A bigger context must never allow fewer images.
+ #expect(model.maximumImageAttachments >= 1)
+ }
+
+ @MainActor
+ @Test func alargerContextAllowsMoreImages() throws {
+ let directory = try makeVisionReadyModelInstall("capacity-growth")
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let model = AppModel(modelDirectory: directory)
+
+ model.maxContextTokens = AppContextLengthOption.fourK.tokens
+ let small = model.maximumImageAttachments
+ model.maxContextTokens = AppContextLengthOption.sixtyFourK.tokens
+ let large = model.maximumImageAttachments
+ #expect(large > small,
+ "raising the context did not raise the image capacity")
+ // The old fixed limit is genuinely gone, not merely renamed.
+ #expect(large > 4)
+ }
+
+ /// The composer and the request validator must not disagree: an attachment
+ /// set the composer accepted has to pass validation.
+ @MainActor
+ @Test func whatTheComposerAcceptsTheRequestAccepts() throws {
+ let directory = try makeVisionReadyModelInstall("capacity-agreement")
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let model = AppModel(modelDirectory: directory)
+ model.maxContextTokens = AppContextLengthOption.eightK.tokens
+
+ let attachments = (0..<model.maximumImageAttachments).map { index in
+ AppImageAttachment(
+ fileURL: URL(fileURLWithPath: "/tmp/image-\(index).png"),
+ displayName: "image-\(index).png",
+ encodedBytes: 1,
+ sha256: String(repeating: "0", count: 64))
+ }
+ let request = AppGenerationRequest(
+ modelDirectory: directory,
+ prompt: "describe these",
+ imageAttachments: attachments,
+ maxContextTokens: model.maxContextTokens)
+ try request.validate(requireModelDirectory: false)
+ }
+
+ /// And one image past what the context can hold is refused rather than
+ /// discovered at generation time.
+ @MainActor
+ @Test func beyondTheContextTheRequestIsRefused() throws {
+ let directory = try makeVisionReadyModelInstall("capacity-refusal")
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let context = AppContextLengthOption.fourK.tokens
+ let capacity = VisionImageTokenBudget.capacity(
+ maxContext: context, reservedTextTokens: 0)
+ let attachments = (0...capacity).map { index in
+ AppImageAttachment(
+ fileURL: URL(fileURLWithPath: "/tmp/image-\(index).png"),
+ displayName: "image-\(index).png",
+ encodedBytes: 1,
+ sha256: String(repeating: "0", count: 64))
+ }
+ let request = AppGenerationRequest(
+ modelDirectory: directory,
+ prompt: "describe these",
+ imageAttachments: attachments,
+ maxContextTokens: context)
+ #expect(throws: AppInferenceError.self) {
+ try request.validate(requireModelDirectory: false)
+ }
+ }
+
+ /// Choosing more images than fit must say so. Silently keeping the first
+ /// few left the user believing every image they picked was attached.
+ @MainActor
+ @Test func choosingTooManyImagesReportsWhatWasDropped() async throws {
+ let root = FileManager.default.temporaryDirectory
+ .appendingPathComponent("capacity-\(UUID().uuidString)", isDirectory: true)
+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: root) }
+ let directory = try makeVisionReadyModelInstall("capacity-truncation")
+ defer { try? FileManager.default.removeItem(at: directory) }
+
+ let store = AppImageAttachmentStore(
+ directoryURL: root.appendingPathComponent("staged", isDirectory: true))
+ let model = AppModel(modelDirectory: directory, attachmentStore: store)
+ model.maxContextTokens = AppContextLengthOption.fourK.tokens
+ let capacity = model.maximumImageAttachments
+
+ var urls: [URL] = []
+ for index in 0...capacity {
+ let url = root.appendingPathComponent("image-\(index).png")
+ try Data("fixture \(index)".utf8).write(to: url)
+ urls.append(url)
+ }
+
+ let previous: String? = nil
+ model.addImages(urls)
+ if let previous {
+ _ = previous
+ } else {
+ _ = previous
+ }
+ let deadline = Date().addingTimeInterval(60)
+ while model.isAddingImages, Date() < deadline {
+ try? await Task.sleep(nanoseconds: 5_000_000)
+ }
+
+ #expect(model.imageAttachments.count == capacity)
+ #expect(model.imageAttachmentError != nil,
+ "images were dropped without saying so")
+ model.releaseAllAttachments()
+ }
+}
+
+/// Findings from reviewing this session's own Mac app changes.
+@Suite struct AppImageReviewRegressionTests {
+ @MainActor
+ @Test func theComposerCapsOnTheContextARunWillActuallyUse() async throws {
+ let directory = try makeVisionReadyModelInstall("review-capacity")
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let model = AppModel(modelDirectory: directory,
+ client: MockLifecycleInferenceClient())
+ model.maxContextTokens = AppContextLengthOption.fourK.tokens
+ model.loadModel()
+ let deadline = Date().addingTimeInterval(60)
+ while !model.loadState.isReady, Date() < deadline {
+ try? await Task.sleep(nanoseconds: 5_000_000)
+ }
+ try #require(model.loadState.isReady)
+ let loadedCapacity = model.maximumImageAttachments
+
+ // Raising the setting without reloading must not raise what the
+ // composer accepts, or it accepts images the request then refuses.
+ model.maxContextTokens = AppContextLengthOption.sixtyFourK.tokens
+ #expect(model.maximumImageAttachments == loadedCapacity,
+ "the composer offered capacity the loaded session cannot serve")
+ #expect(model.effectiveMaxContextTokens
+ == AppContextLengthOption.fourK.tokens)
+ }
+
+ /// A companion operation renames the pack directory, so a readiness refresh
+ /// during one can briefly report no image support. Deleting the user's
+ /// staged images on that would be data loss.
+ @MainActor
+ @Test func amidCompanionOperationRefreshKeepsStagedImages() async throws {
+ let root = FileManager.default.temporaryDirectory
+ .appendingPathComponent("review-\(UUID().uuidString)", isDirectory: true)
+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
+ defer { try? FileManager.default.removeItem(at: root) }
+ let source = root.appendingPathComponent("source.png")
+ try Data("fixture".utf8).write(to: source)
+ let directory = try makeVisionReadyModelInstall("review-operation")
+ defer { try? FileManager.default.removeItem(at: directory) }
+
+ let store = AppImageAttachmentStore(
+ directoryURL: root.appendingPathComponent("staged", isDirectory: true))
+ let model = AppModel(modelDirectory: directory,
+ client: MockLifecycleInferenceClient(),
+ attachmentStore: store)
+ let previous: String? = nil
+ defer {
+ if let previous { setenv("TURBO_FIELDFARE_VISION_RUNTIME", previous, 1) }
+ else { unsetenv("TURBO_FIELDFARE_VISION_RUNTIME") }
+ }
+ model.addImages([source])
+ var deadline = Date().addingTimeInterval(60)
+ while model.isAddingImages, Date() < deadline {
+ try? await Task.sleep(nanoseconds: 5_000_000)
+ }
+ try #require(model.imageAttachments.count == 1)
+
+ // The pack goes away underneath, as it does mid-rename, while an
+ // operation is in flight.
+ let companion = try VisionPackLocation.companionURL(forTextModel: directory)
+ try FileManager.default.removeItem(at: companion)
+ model.visionInstallState = .discarding
+ try #require(model.isVisionCompanionOperationInProgress)
+ model.refreshVisionInstallReadiness()
+
+ #expect(model.imageAttachments.count == 1,
+ "a refresh during a companion operation deleted staged images")
+
+ // Once the operation ends and support really is gone, they go: an
+ // attachment nothing can encode is worse than none.
+ model.visionInstallState = .idle
+ model.refreshVisionInstallReadiness()
+ #expect(model.imageAttachments.isEmpty)
+ model.releaseAllAttachments()
+ }
+}
diff --git a/Tests/TurboFieldfareApp/Core/State/AppModelLoadPhaseOrderTests.swift b/Tests/TurboFieldfareApp/Core/State/AppModelLoadPhaseOrderTests.swift
new file mode 100644
index 00000000..0e0e4b25
--- /dev/null
+++ b/Tests/TurboFieldfareApp/Core/State/AppModelLoadPhaseOrderTests.swift
@@ -0,0 +1,112 @@
+import Foundation
+import Testing
+@testable import TurboFieldfareAppCore
+
+/// Load phases are emitted in order by the runtime but applied through
+/// independently created main-actor tasks, and ordering between those is not
+/// guaranteed. A late `.loading` overwriting `.ready` leaves the UI showing a
+/// phase the runtime has already finished, with Run disabled.
+@Suite struct AppModelLoadPhaseOrderTests {
+ @MainActor
+ @Test func aLatePhaseNeverOverwritesANewerOne() async throws {
+ let model = AppModel(client: MockLifecycleInferenceClient())
+ let directory = FileManager.default.temporaryDirectory
+ model.modelPathText = directory.path
+
+ model.applyLoadState(.loading(.validatingDirectory), generation: 0, sequence: 1)
+ model.applyLoadState(.loading(.tokenizer), generation: 0, sequence: 2)
+ // Arrives out of order, which is exactly what used to happen.
+ model.applyLoadState(.ready(modelDirectory: directory, loadSeconds: 1),
+ generation: 0, sequence: 4)
+ model.applyLoadState(.loading(.preparingRunner), generation: 0, sequence: 3)
+
+ #expect(model.loadState.isReady,
+ "a stale phase overwrote the ready state")
+ }
+
+ /// In-order phases must still all be applied.
+ @MainActor
+ @Test func phasesInOrderAreAllApplied() async throws {
+ let model = AppModel(client: MockLifecycleInferenceClient())
+ let directory = FileManager.default.temporaryDirectory
+ model.modelPathText = directory.path
+
+ model.applyLoadState(.loading(.validatingDirectory), generation: 0, sequence: 1)
+ #expect(model.loadState == .loading(.validatingDirectory))
+ model.applyLoadState(.loading(.verifyingWeights), generation: 0, sequence: 2)
+ #expect(model.loadState == .loading(.verifyingWeights))
+ model.applyLoadState(.loading(.preparingRunner), generation: 0, sequence: 3)
+ #expect(model.loadState == .loading(.preparingRunner))
+ model.applyLoadState(.ready(modelDirectory: directory, loadSeconds: 1),
+ generation: 0, sequence: 4)
+ #expect(model.loadState.isReady)
+ }
+
+ /// The same race against the other outcome, which the ordering guard did
+ /// not cover: `.failed` is raised by the model itself at sequence 0, so it
+ /// never advanced the counter, and a phase emitted just before the throw
+ /// but delivered just after it passed the check and put the UI back into a
+ /// load. With no task left to cancel and a state that is neither
+ /// `.notLoaded` nor `.failed`, both Cancel and Load are disabled — a
+ /// spinner with no way out.
+ @MainActor
+ @Test func aLatePhaseNeverReopensAFailedLoad() async throws {
+ // A real install, because `canLoadModel` is gated on `isModelInstalled`:
+ // pointed at a bare temporary directory this asserted a Load button that
+ // could never be enabled for a reason that has nothing to do with phase
+ // ordering.
+ let directory = try makeCompleteModelInstall("load-phase-order-late-phase")
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let model = AppModel(modelDirectory: directory,
+ client: MockLifecycleInferenceClient())
+
+ model.applyLoadState(.loading(.validatingDirectory), generation: 0, sequence: 1)
+ model.applyLoadState(.failed(.modelLoadFailed("bad companion pack")),
+ generation: 0)
+ model.applyLoadState(.loading(.mappingImageTower), generation: 0, sequence: 2)
+
+ #expect(model.loadState.isFailed,
+ "a phase emitted before the failure reopened the load")
+ #expect(model.canLoadModel,
+ "the load could be neither cancelled nor restarted")
+ }
+
+ /// The seal lasts exactly one load: the next `beginLoad` resets the counter,
+ /// so sealing must not make a later load ignore its own phases.
+ @MainActor
+ @Test func aFailedLoadDoesNotSealTheNextOne() async throws {
+ let client = MockLifecycleInferenceClient()
+ let directory = try makeCompleteModelInstall("load-phase-order-after-failure")
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let model = AppModel(modelDirectory: directory, client: client)
+
+ model.applyLoadState(.failed(.modelLoadFailed("first attempt")), generation: 0)
+ #expect(model.loadState.isFailed)
+
+ model.loadModel()
+ let deadline = Date().addingTimeInterval(5)
+ while !model.loadState.isReady, Date() < deadline {
+ try? await Task.sleep(nanoseconds: 5_000_000)
+ }
+ #expect(model.loadState.isReady, "the next load's phases were sealed out")
+ }
+
+ /// A real load must still end ready, with the sequence reset for the next.
+ @MainActor
+ @Test func aRealLoadEndsReadyAndTheNextOneStartsClean() async throws {
+ let client = MockLifecycleInferenceClient()
+ let directory = try makeCompleteModelInstall("load-phase-order")
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let model = AppModel(modelDirectory: directory, client: client)
+
+ for _ in 0..<3 {
+ model.loadModel()
+ let deadline = Date().addingTimeInterval(5)
+ while !model.loadState.isReady, Date() < deadline {
+ try? await Task.sleep(nanoseconds: 5_000_000)
+ }
+ #expect(model.loadState.isReady)
+ model.loadState = .notLoaded
+ }
+ }
+}
diff --git a/Tests/TurboFieldfareApp/Core/State/AppModelTests.swift b/Tests/TurboFieldfareApp/Core/State/AppModelTests.swift
index b5a149da..fd5da17b 100644
--- a/Tests/TurboFieldfareApp/Core/State/AppModelTests.swift
+++ b/Tests/TurboFieldfareApp/Core/State/AppModelTests.swift
@@ -13,7 +13,8 @@ import Testing
#expect(request.temperature == 0.2)
#expect(request.topK == 64)
#expect(request.topP == 0.95)
- #expect(request.maxNewTokens == 4_096)
+ #expect(request.maxNewTokens == 8_192,
+ "the reply limit follows the default context, 8K since 2026-08-17")
#expect(request.repetitionPenalty == 1)
#expect(!request.isPureGreedy)
#expect(request.runtimeOptions.expertCacheSlots == 16)
@@ -94,7 +95,9 @@ import Testing
model.applyLoadState(.ready(modelDirectory: directory, loadSeconds: 0))
#expect(!model.hasStaleLoadedRuntime)
- model.maxContextTokens = AppContextLengthOption.eightK.tokens
+ // Away from the default, which is 8K: setting the value it already has
+ // would prove nothing.
+ model.maxContextTokens = AppContextLengthOption.sixteenK.tokens
#expect(model.hasStaleLoadedRuntime)
}
diff --git a/Tests/TurboFieldfareApp/Core/State/AppPresentationVisionGateTests.swift b/Tests/TurboFieldfareApp/Core/State/AppPresentationVisionGateTests.swift
new file mode 100644
index 00000000..59f1a33b
--- /dev/null
+++ b/Tests/TurboFieldfareApp/Core/State/AppPresentationVisionGateTests.swift
@@ -0,0 +1,84 @@
+import Foundation
+import Testing
+@testable import TurboFieldfareAppCore
+
+/// The banner offers exactly the model actions the model will actually perform.
+///
+/// `canLoadModel`, `canReloadModel` and `canUnloadModel` all refuse while a
+/// companion operation is in flight, but the presentation snapshot carried no
+/// vision state — so this resolved to "Installed · Not loaded" with a `.load`
+/// action, and `ModelActionBanner` rendered it as a fully enabled button whose
+/// click did nothing for the whole 1.5 GB transfer.
+@Suite struct AppPresentationVisionGateTests {
+ private static let modelDirectory = URL(
+ fileURLWithPath: "/tmp/TurboFieldfare/gemma4.gturbo", isDirectory: true)
+
+ private func snapshot(
+ loadState: AppModelLoadState = .notLoaded,
+ hasStaleRuntime: Bool = false,
+ companionOperationInProgress: Bool
+ ) -> AppPresentationSnapshot {
+ AppPresentationSnapshot(
+ requiresInstallation: false,
+ installState: .idle,
+ installReadiness: .checking,
+ loadState: loadState,
+ hasStaleRuntime: hasStaleRuntime,
+ isRunning: false,
+ isGenerationCancellationPending: false,
+ generationPhase: .idle,
+ isVisionCompanionOperationInProgress: companionOperationInProgress)
+ }
+
+ @Test func anUnloadedModelOffersLoadWhenNoCompanionOperationRuns() {
+ let state = AppPresentationState.resolve(
+ snapshot(companionOperationInProgress: false))
+ #expect(state.primaryAction == .load)
+ #expect(state.conversationAction == .load)
+ }
+
+ /// The case the banner got wrong: unloaded — which every companion
+ /// operation requires — with a transfer running.
+ @Test func noModelActionIsOfferedWhileACompanionOperationRuns() {
+ let state = AppPresentationState.resolve(
+ snapshot(companionOperationInProgress: true))
+ #expect(state.primaryAction == nil,
+ "the banner would render an enabled button for \(state.label)")
+ #expect(state.conversationAction == nil)
+ #expect(state.showsActivity)
+ }
+
+ /// Not just the unloaded case: a stale runtime otherwise offers Reload, and
+ /// `canReloadModel` refuses for the same reason.
+ @Test func astaleRuntimeOffersNoReloadWhileACompanionOperationRuns() {
+ let ready = AppModelLoadState.ready(
+ modelDirectory: Self.modelDirectory, loadSeconds: 1)
+
+ let during = AppPresentationState.resolve(
+ snapshot(loadState: ready,
+ hasStaleRuntime: true,
+ companionOperationInProgress: true))
+ #expect(during.primaryAction == nil)
+
+ let idle = AppPresentationState.resolve(
+ snapshot(loadState: ready,
+ hasStaleRuntime: true,
+ companionOperationInProgress: false))
+ #expect(idle.primaryAction == .reload,
+ "without a companion operation the stale-runtime prompt has to survive")
+ }
+
+ /// Every action the banner surfaces has to be one the model would run.
+ @Test func everySurfacedActionIsOneTheModelWouldPerform() {
+ let states: [AppModelLoadState] = [
+ .notLoaded,
+ .ready(modelDirectory: Self.modelDirectory, loadSeconds: 1),
+ ]
+ for loadState in states {
+ let state = AppPresentationState.resolve(
+ snapshot(loadState: loadState, companionOperationInProgress: true))
+ #expect(state.primaryAction == nil && state.secondaryAction == nil,
+ "\(loadState) offered \(String(describing: state.primaryAction)) during a companion operation")
+ }
+ }
+}
diff --git a/Tests/TurboFieldfareApp/Core/State/AppVisionActivationTests.swift b/Tests/TurboFieldfareApp/Core/State/AppVisionActivationTests.swift
new file mode 100644
index 00000000..17b41006
--- /dev/null
+++ b/Tests/TurboFieldfareApp/Core/State/AppVisionActivationTests.swift
@@ -0,0 +1,123 @@
+import Foundation
+import Testing
+import TurboFieldfare
+import TurboFieldfareRepackCore
+@testable import TurboFieldfareAppCore
+
+/// Activation reads about 1.5 GB to verify the pack before it goes live. It
+/// used to do that as an uncancellable, progress-free, app-wide block.
+@Suite struct AppVisionActivationTests {
+ @MainActor
+ private func model(_ installer: MockVisionPackInstallerClient) -> AppModel {
+ let model = AppModel(visionInstaller: installer)
+ model.visionInstallState = .readyToActivate(
+ FileManager.default.temporaryDirectory)
+ return model
+ }
+
+ @MainActor
+ @Test func activationReportsHowFarItsVerificationHasGot() async throws {
+ let installer = MockVisionPackInstallerClient(
+ preparedValid: true, activationProgress: [0.25, 0.5, 0.75, 1])
+ let model = model(installer)
+ model.activateVisionPack()
+
+ var seen: [Double] = []
+ // Generous, because this runs alongside the GPU suites: the assertions
+ // below are about ordering and cleanup, not about how fast it got there.
+ let deadline = Date().addingTimeInterval(60)
+ while model.isInstallingVisionPack, Date() < deadline {
+ if let fraction = model.visionInstallProgressFraction,
+ seen.last != fraction {
+ seen.append(fraction)
+ }
+ try? await Task.sleep(nanoseconds: 5_000_000)
+ }
+ try #require(!model.isInstallingVisionPack, "activation never finished")
+ #expect(!seen.isEmpty, "activation showed no progress at all")
+ #expect(seen == seen.sorted(), "progress went backwards: \(seen)")
+ #expect(model.visionActivationProgress == nil,
+ "progress outlived the activation")
+ }
+
+ /// The only long phase is the hash, and it runs before anything is renamed,
+ /// so abandoning it leaves the prepared pack exactly as it was.
+ @MainActor
+ @Test func activationCanBeCancelledAndLeavesThePackActivatable() async throws {
+ let installer = MockVisionPackInstallerClient(
+ preparedValid: true,
+ activationProgress: Array(repeating: 0.1, count: 200))
+ let model = model(installer)
+ model.activateVisionPack()
+ #expect(model.canCancelVisionInstall,
+ "activation offered no way out")
+
+ try await Task.sleep(nanoseconds: 60_000_000)
+ model.cancelVisionInstall()
+ let deadline = Date().addingTimeInterval(60)
+ while model.isInstallingVisionPack, Date() < deadline {
+ try? await Task.sleep(nanoseconds: 5_000_000)
+ }
+ #expect(!model.isInstallingVisionPack, "cancelling activation never landed")
+ #expect(model.visionActivationProgress == nil)
+
+ // Activating again is allowed: nothing was consumed.
+ #expect(installer.activationCount == 1)
+ model.visionInstallState = .readyToActivate(
+ FileManager.default.temporaryDirectory)
+ #expect(model.canActivateVisionPack)
+ }
+
+ /// A download that finished and verifies is activatable whatever happened
+ /// afterwards; presenting it as "needs attention" hid Activate behind a
+ /// Resume that only repeats work already done.
+ @MainActor
+ @Test func aValidPreparedDownloadStillOffersActivateAfterAFailure() async throws {
+ // `.recoverable` is only reachable when a saved download exists on
+ // disk, so the fixture has to be real.
+ let root = FileManager.default.temporaryDirectory
+ .appendingPathComponent("vision-activate-\(UUID().uuidString)",
+ isDirectory: true)
+ defer { try? FileManager.default.removeItem(at: root) }
+ let text = root.appendingPathComponent("model.gturbo", isDirectory: true)
+ try FileManager.default.createDirectory(at: text, withIntermediateDirectories: true)
+ let companion = try VisionPackLocation.companionURL(forTextModel: text)
+ let partial = companion.deletingLastPathComponent()
+ .appendingPathComponent(companion.lastPathComponent + ".partial",
+ isDirectory: true)
+ try FileManager.default.createDirectory(
+ at: partial, withIntermediateDirectories: true)
+
+ let installer = MockVisionPackInstallerClient(preparedValid: true)
+ let model = AppModel(modelDirectory: text, visionInstaller: installer)
+ #expect(model.hasPartialVisionPackDownload)
+ model.finishVisionInstallFailure(
+ RepackError.configurationInvalid(detail: "network died"),
+ generation: 0)
+
+ guard case .readyToActivate = model.visionInstallState else {
+ Issue.record("a verifiable download was hidden behind this state")
+ return
+ }
+ }
+
+ /// But a failure *during* verification must not send the user back to
+ /// Activate, or the same corrupt pack is offered forever.
+ @MainActor
+ @Test func averificationFailureDoesNotOfferActivateAgain() async throws {
+ let installer = MockVisionPackInstallerClient(
+ preparedValid: true,
+ activationError: .configurationInvalid(detail: "hash mismatch"))
+ let model = model(installer)
+ model.activateVisionPack()
+ let deadline = Date().addingTimeInterval(60)
+ while model.isInstallingVisionPack, Date() < deadline {
+ try? await Task.sleep(nanoseconds: 5_000_000)
+ }
+ try #require(!model.isInstallingVisionPack, "activation never finished")
+
+ if case .readyToActivate = model.visionInstallState {
+ Issue.record("a pack that failed verification was offered for activation again")
+ }
+ }
+}
diff --git a/Tests/TurboFieldfareApp/Core/State/AppVisionPackRemovalConfirmationTests.swift b/Tests/TurboFieldfareApp/Core/State/AppVisionPackRemovalConfirmationTests.swift
new file mode 100644
index 00000000..7d89bef4
--- /dev/null
+++ b/Tests/TurboFieldfareApp/Core/State/AppVisionPackRemovalConfirmationTests.swift
@@ -0,0 +1,62 @@
+import Foundation
+import Testing
+@testable import TurboFieldfareAppCore
+
+/// Deleting the companion pack throws away 1.14 GB, and the only way back is
+/// downloading it again — so it asks first.
+///
+/// The Inspector hides its image-support block once the pack is installed, which
+/// left its confirmation-guarded Remove button on an unreachable branch: the
+/// Model menu item was the only path, and it called `removeVisionPack` straight
+/// through. The menu now goes through `requestVisionPackRemoval`, and the window
+/// presents the dialog.
+@Suite struct AppVisionPackRemovalConfirmationTests {
+ @MainActor
+ @Test func requestingRemovalAsksRatherThanDeleting() throws {
+ let directory = try makeVisionReadyModelInstall("removal-confirm")
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let model = AppModel(modelDirectory: directory)
+
+ try #require(model.canRemoveVisionPack)
+ #expect(!model.isConfirmingVisionPackRemoval)
+
+ model.requestVisionPackRemoval()
+
+ #expect(model.isConfirmingVisionPackRemoval,
+ "the menu item deleted the pack without asking")
+ #expect(model.isVisionPackInstalled,
+ "the pack was removed before the confirmation was answered")
+ }
+
+ /// Answering the dialog is what performs the removal, and the flag has to
+ /// drop with it or the dialog returns on the next state change.
+ @MainActor
+ @Test func confirmingClearsTheRequestAndRemoves() throws {
+ let directory = try makeVisionReadyModelInstall("removal-confirmed")
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let model = AppModel(modelDirectory: directory)
+
+ model.requestVisionPackRemoval()
+ try #require(model.isConfirmingVisionPackRemoval)
+
+ model.removeVisionPack()
+
+ #expect(!model.isConfirmingVisionPackRemoval)
+ }
+
+ /// A removal that cannot run must not raise a dialog that would do nothing:
+ /// a loaded session blocks every companion operation.
+ @MainActor
+ @Test func norequestIsRaisedWhenRemovalIsRefused() throws {
+ // No companion beside the model, so there is nothing to remove.
+ let directory = try makeCompleteModelInstall("removal-refused")
+ defer { try? FileManager.default.removeItem(at: directory) }
+ let model = AppModel(modelDirectory: directory)
+
+ try #require(!model.canRemoveVisionPack)
+ model.requestVisionPackRemoval()
+
+ #expect(!model.isConfirmingVisionPackRemoval,
+ "a dialog was raised for a removal that would be refused anyway")
+ }
+}
diff --git a/Tests/TurboFieldfareApp/Core/Support/MockInferenceClient.swift b/Tests/TurboFieldfareApp/Core/Support/MockInferenceClient.swift
index ebef2700..c7e7ba3c 100644
--- a/Tests/TurboFieldfareApp/Core/Support/MockInferenceClient.swift
+++ b/Tests/TurboFieldfareApp/Core/Support/MockInferenceClient.swift
@@ -9,6 +9,10 @@ final class MockInferenceClient: AppInferenceClient, @unchecked Sendable {
var failureMessage: String?
var prefillSteps: Int = 3
+ var opensAttachments = true
+ /// Holds the stream inside prefill so a cancel cannot race past it.
+ var holdsDuringPrefill = false
+
private let lock = NSLock()
private var activeTask: Task<Void, Never>?
private var activeGenerationID: UUID?
@@ -35,6 +39,16 @@ final class MockInferenceClient: AppInferenceClient, @unchecked Sendable {
return
}
+ if opensAttachments,
+ let unreadable = request.imageAttachments.first(where: { !Self.canOpen($0.fileURL) }) {
+ let appError = AppInferenceError.invalidRequest(
+ "Image \(unreadable.displayName) could not be opened at "
+ + unreadable.fileURL.path)
+ continuation.yield(.failed(appError, partial: nil))
+ continuation.finish(throwing: appError)
+ return
+ }
+
lock.lock()
if activeTask != nil {
lock.unlock()
@@ -58,6 +72,12 @@ final class MockInferenceClient: AppInferenceClient, @unchecked Sendable {
}
}
+ private static func canOpen(_ url: URL) -> Bool {
+ guard let handle = try? FileHandle(forReadingFrom: url) else { return false }
+ try? handle.close()
+ return true
+ }
+
func cancel() {
lock.lock()
let task = activeTask
@@ -108,6 +128,9 @@ final class MockInferenceClient: AppInferenceClient, @unchecked Sendable {
}
try? await Task.sleep(nanoseconds: tokenDelayNanos)
continuation.yield(.prefillProgress(done: step + 1, total: prefillSteps))
+ while holdsDuringPrefill, !Task.isCancelled {
+ try? await Task.sleep(nanoseconds: 2_000_000)
+ }
}
prefillEndDate = Date()
diff --git a/Tests/TurboFieldfareApp/Core/Support/MockVisionPackInstallerClient.swift b/Tests/TurboFieldfareApp/Core/Support/MockVisionPackInstallerClient.swift
new file mode 100644
index 00000000..6433507b
--- /dev/null
+++ b/Tests/TurboFieldfareApp/Core/Support/MockVisionPackInstallerClient.swift
@@ -0,0 +1,100 @@
+import Foundation
+import Synchronization
+import TurboFieldfareRepackCore
+@testable import TurboFieldfareAppCore
+
+final class MockVisionPackInstallerClient: AppVisionPackInstallerClient, Sendable {
+ let descriptor: AppModelInstallDescriptor
+ let requirement: AppModelInstallRequirement
+ let events: [AppModelInstallEvent]
+ let holdOpen: Bool
+ let preparedValid: Bool
+ let activationError: RepackError?
+ /// Fractions the activation reports before it finishes, with a pause after
+ /// each so a cancel can land mid-verification.
+ let activationProgress: [Double]
+ private let task = Mutex<Task<Void, Never>?>(nil)
+ private let activations = Mutex(0)
+
+ var activationCount: Int { activations.withLock { $0 } }
+
+ init(
+ descriptor: AppModelInstallDescriptor = .visionCompanion,
+ requirement: AppModelInstallRequirement = AppModelInstallRequirement(
+ probePath: "/",
+ requiredBytes: 1,
+ availableBytes: UInt64.max),
+ events: [AppModelInstallEvent] = [],
+ holdOpen: Bool = false,
+ preparedValid: Bool = false,
+ activationError: RepackError? = nil,
+ activationProgress: [Double] = []
+ ) {
+ self.descriptor = descriptor
+ self.requirement = requirement
+ self.events = events
+ self.holdOpen = holdOpen
+ self.preparedValid = preparedValid
+ self.activationError = activationError
+ self.activationProgress = activationProgress
+ }
+
+ func checkInstallRequirement(
+ textModelDirectory: URL
+ ) throws -> AppModelInstallRequirement {
+ requirement
+ }
+
+ func install(
+ textModelDirectory: URL
+ ) -> AsyncThrowingStream<AppModelInstallEvent, Error> {
+ AsyncThrowingStream { continuation in
+ let task = Task { [events, holdOpen] in
+ do {
+ for event in events {
+ try Task.checkCancellation()
+ continuation.yield(event)
+ await Task.yield()
+ }
+ if holdOpen {
+ try await Task.sleep(for: .seconds(60))
+ }
+ continuation.finish()
+ } catch is CancellationError {
+ continuation.finish(throwing: CancellationError())
+ } catch {
+ continuation.finish(throwing: error)
+ }
+ }
+ self.task.withLock { $0 = task }
+ continuation.onTermination = { [weak self] _ in
+ self?.task.withLock { active in
+ active?.cancel()
+ active = nil
+ }
+ }
+ }
+ }
+
+ func discardPartialInstall(textModelDirectory: URL) async throws {}
+ func removeInstalled(textModelDirectory: URL) async throws {}
+ func preparedInstallIsValid(textModelDirectory: URL) -> Bool { preparedValid }
+ func activatePreparedInstall(
+ textModelDirectory: URL,
+ onVerifyProgress: (@Sendable (Double) -> Void)?
+ ) async throws -> URL {
+ activations.withLock { $0 += 1 }
+ for fraction in activationProgress {
+ try Task.checkCancellation()
+ onVerifyProgress?(fraction)
+ try await Task.sleep(for: .milliseconds(30))
+ }
+ try Task.checkCancellation()
+ if let activationError { throw activationError }
+ return textModelDirectory
+ }
+
+ func cancel() {
+ task.withLock { $0?.cancel() }
+ }
+}
diff --git a/Tests/TurboFieldfareApp/Core/VisionPackLockAgreementTests.swift b/Tests/TurboFieldfareApp/Core/VisionPackLockAgreementTests.swift
new file mode 100644
index 00000000..e94320cc
--- /dev/null
+++ b/Tests/TurboFieldfareApp/Core/VisionPackLockAgreementTests.swift
@@ -0,0 +1,141 @@
+import Darwin
+import Foundation
+import Testing
+@testable import TurboFieldfare
+@testable import TurboFieldfareRepackCore
+
+/// The runtime's shared lease and the installer's exclusive lock live in
+/// different modules and derive their lock path independently. Nothing fails
+/// loudly when those derivations disagree — the two sides simply lock different
+/// files and stop excluding each other, which is how a companion pack gets
+/// replaced underneath a runtime that is mmap'ing it.
+@Suite struct VisionPackLockAgreementTests {
+ private static func makeParent(_ label: String) throws -> URL {
+ let parent = FileManager.default.temporaryDirectory
+ .appendingPathComponent("\(label)-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(
+ at: parent, withIntermediateDirectories: false)
+ return parent
+ }
+
+ @Test func bothSidesDeriveTheSameLockPath() throws {
+ let parent = try Self.makeParent("lock-agreement")
+ defer { try? FileManager.default.removeItem(at: parent) }
+ let companion = parent.appendingPathComponent("model.vision.gturbo")
+
+ let mutation = try VisionPackMutationLock.lockPath(
+ outputDirectory: companion.path)
+ let lease = VisionPackUseLease.lockURL(for: companion).path
+ #expect(mutation == lease)
+ }
+
+ /// An explicit companion path routed through a symlinked parent — what a
+ /// `--vision-pack` override or a relocated model directory produces. The
+ /// two sides used to resolve it differently, so both locks succeeded and
+ /// neither excluded the other.
+ @Test func symlinkedParentsStillAgree() throws {
+ let real = try Self.makeParent("lock-agreement-real")
+ let link = FileManager.default.temporaryDirectory
+ .appendingPathComponent("lock-agreement-link-\(UUID().uuidString)")
+ try FileManager.default.createSymbolicLink(at: link, withDestinationURL: real)
+ defer {
+ try? FileManager.default.removeItem(at: link)
+ try? FileManager.default.removeItem(at: real)
+ }
+ let throughLink = link.appendingPathComponent("model.vision.gturbo")
+
+ let mutation = try VisionPackMutationLock.lockPath(
+ outputDirectory: throughLink.path)
+ let lease = VisionPackUseLease.lockURL(for: throughLink).path
+ #expect(mutation == lease)
+
+ // And the exclusion actually holds through the symlink.
+ let held = try VisionPackMutationLock.acquire(outputDirectory: throughLink.path)
+ #expect(throws: VisionPackError.self) {
+ _ = try VisionPackUseLease.acquireShared(
+ companionURL: throughLink, timeout: .milliseconds(200))
+ }
+ withExtendedLifetime(held) {}
+ }
+
+ /// A shared lease used to block indefinitely, so an installer that hung —
+ /// or crashed while another process held the lock — hung model load with
+ /// nothing to report. It has to give up and say why.
+ @Test func sharedLeaseTimesOutInsteadOfBlockingForever() throws {
+ let parent = try Self.makeParent("lock-timeout")
+ defer { try? FileManager.default.removeItem(at: parent) }
+ let companion = parent.appendingPathComponent("model.vision.gturbo")
+ let held = try VisionPackMutationLock.acquire(outputDirectory: companion.path)
+
+ let started = ContinuousClock.now
+ var message = ""
+ do {
+ _ = try VisionPackUseLease.acquireShared(
+ companionURL: companion, timeout: .milliseconds(300))
+ Issue.record("shared lease ignored the exclusive mutation lock")
+ } catch let error as VisionPackError {
+ message = "\(error)"
+ }
+ let elapsed = ContinuousClock.now - started
+ #expect(elapsed >= .milliseconds(250), "gave up before waiting")
+ #expect(elapsed < .seconds(3), "waited far past its timeout")
+ #expect(message.contains("being modified"),
+ "the error must say what is holding the pack: \(message)")
+ withExtendedLifetime(held) {}
+ }
+
+ /// Once the mutation finishes, readers get in.
+ @Test func sharedLeaseSucceedsAfterTheMutationReleases() throws {
+ let parent = try Self.makeParent("lock-release")
+ defer { try? FileManager.default.removeItem(at: parent) }
+ let companion = parent.appendingPathComponent("model.vision.gturbo")
+ var held: VisionPackMutationLock? =
+ try VisionPackMutationLock.acquire(outputDirectory: companion.path)
+ held = nil
+ _ = held
+
+ let lease = try VisionPackUseLease.acquireShared(
+ companionURL: companion, timeout: .milliseconds(300))
+ #expect(lease.lockFileURL.lastPathComponent
+ == ".model.vision.gturbo.use.lock")
+ // Two readers may hold it at once; only mutation is exclusive.
+ let second = try VisionPackUseLease.acquireShared(
+ companionURL: companion, timeout: .milliseconds(300))
+ withExtendedLifetime((lease, second)) {}
+ }
+
+ /// The lock file is replaced between `open` and `flock` — a reinstall
+ /// racing a load. Locking the unlinked inode excludes nothing, so it has to
+ /// be caught rather than reported as success.
+ @Test func aReplacedLockFileIsRejected() throws {
+ let parent = try Self.makeParent("lock-replaced")
+ defer { try? FileManager.default.removeItem(at: parent) }
+ let companion = parent.appendingPathComponent("model.vision.gturbo")
+ let path = VisionPackUseLease.lockURL(for: companion).path
+
+ // Stand in for the race: a descriptor on the old inode, then the path
+ // pointing at a new one.
+ let stale = open(path, O_RDWR | O_CREAT | O_NOFOLLOW | O_CLOEXEC, 0o600)
+ #expect(stale >= 0)
+ defer { close(stale) }
+ try FileManager.default.removeItem(atPath: path)
+ let fresh = open(path, O_RDWR | O_CREAT | O_NOFOLLOW | O_CLOEXEC, 0o600)
+ #expect(fresh >= 0)
+ defer { close(fresh) }
+
+ var staleInfo = stat()
+ var freshInfo = stat()
+ #expect(fstat(stale, &staleInfo) == 0)
+ #expect(fstat(fresh, &freshInfo) == 0)
+ #expect(staleInfo.st_ino != freshInfo.st_ino,
+ "the fixture did not actually replace the inode")
+
+ // A lease taken now must bind to the live inode, not the stale one.
+ let lease = try VisionPackUseLease.acquireShared(
+ companionURL: companion, timeout: .milliseconds(300))
+ var leaseInfo = stat()
+ #expect(lstat(lease.lockFileURL.path, &leaseInfo) == 0)
+ #expect(leaseInfo.st_ino == freshInfo.st_ino)
+ withExtendedLifetime(lease) {}
+ }
+}
diff --git a/Tests/TurboFieldfareApp/MacPresentation/MemoryFootprintExplanationTests.swift b/Tests/TurboFieldfareApp/MacPresentation/MemoryFootprintExplanationTests.swift
new file mode 100644
index 00000000..7a2336c9
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/MemoryFootprintExplanationTests.swift
@@ -0,0 +1,56 @@
+import Foundation
+import Testing
+@testable import TurboFieldfareMacPresentation
+
+@MainActor
+@Suite struct MemoryFootprintExplanationTests {
+ private static let chargedBytes: UInt64 = 168_296_448
+
+ @Test func chargedLineNamesExpertSlotsNeverTheExpertPool() {
+ let text = MemoryFootprintExplanation.text(chargedBytes: Self.chargedBytes)
+ #expect(text.contains("expert slots"))
+ // "experts" would claim the 12.9 GB routed pool is inside the footprint.
+ // Only the 16 pread slot buffers are.
+ #expect(!text.contains("experts"))
+ #expect(text.contains("the KV cache, working buffers and expert slots."))
+ }
+
+ @Test func theExplanationIsTheChargedLineAndTheExclusion() {
+ let text = MemoryFootprintExplanation.text(chargedBytes: Self.chargedBytes)
+ #expect(text == """
+ \(MetricFormat.memory(Self.chargedBytes)) charged to the app \u{2014} the KV cache, \
+ working buffers and expert slots.
+
+ The model's weights and the image tower are not counted here: the GPU reads them \
+ straight from disk, and macOS keeps them as cached files it can drop at any moment, \
+ charged to no app. To see them: Activity Monitor > Memory > Cached Files.
+ """)
+ }
+
+ /// The tower is wording, never a live figure: a number in this popover
+ /// invites adding it to the charged headline, and the diagnostics section
+ /// already carries the measured "Image tower mapped" row.
+ @Test func theTowerAppearsAsWordingWithNoFigure() {
+ let text = MemoryFootprintExplanation.text(chargedBytes: Self.chargedBytes)
+ #expect(text.contains("image tower"))
+ #expect(!text.contains("Image tower held"))
+ let charged = MetricFormat.memory(Self.chargedBytes)
+ let figures = text.components(separatedBy: .newlines)
+ .filter { $0.rangeOfCharacter(from: .decimalDigits) != nil }
+ #expect(figures.allSatisfy { $0.contains(charged) },
+ "a figure other than the charged bytes appeared: \(figures)")
+ }
+
+ @Test func anUnsampledFootprintStillExplainsTheExclusion() {
+ let text = MemoryFootprintExplanation.text(chargedBytes: nil)
+ #expect(text.hasPrefix("\u{2014} charged to the app"))
+ #expect(text.contains(MemoryFootprintExplanation.exclusionNote))
+ }
+
+ @Test func theExclusionNoteCarriesNoFigureSoPeakRowsCanReuseIt() {
+ let note = MemoryFootprintExplanation.exclusionNote
+ #expect(!note.contains("charged to the app"))
+ #expect(note.contains("Activity Monitor > Memory > Cached Files."))
+ #expect(note.rangeOfCharacter(from: .decimalDigits) == nil)
+ }
+}
diff --git a/Tests/TurboFieldfareApp/MacPresentation/OutputPaneImageBudgetTests.swift b/Tests/TurboFieldfareApp/MacPresentation/OutputPaneImageBudgetTests.swift
new file mode 100644
index 00000000..f8ba5d6d
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/OutputPaneImageBudgetTests.swift
@@ -0,0 +1,277 @@
+import AppKit
+import CoreGraphics
+import Foundation
+import ImageIO
+import Testing
+import UniformTypeIdentifiers
+@testable import TurboFieldfareMacPresentation
+
+/// The decode budget the output pane draws attached images under.
+///
+/// Both the composer's thumbnail row and the transcript's inline images decode
+/// through `TranscriptImageLoader.thumbnail`, so these cover both call sites at
+/// once — the transcript path is the one that shipped unguarded.
+///
+/// The budget is injected rather than shipped: proving the refusal at the real
+/// 96 MB ceiling would mean materialising about 100 MB of pixels inside the
+/// test, which is the memory rule the ceiling exists to keep.
+/// Serialized because the decode cache is one process-wide `NSCache`: the two
+/// cache tests each clear it on entry and on exit, so run in parallel one wipes
+/// the entry the other has just stored and is about to read back. Pre-existing,
+/// and it fails on this suite alone.
+@Suite(.serialized) struct OutputPaneImageBudgetTests {
+ /// One ceiling covers every format, because the reduction that used to
+ /// make JPEG cheap now happens in our own filter rather than in ImageIO.
+ /// The same pixels are therefore refused whichever container they arrive
+ /// in — and refusing them is right, since the runtime refuses them too.
+ @Test func aSourceOverTheCeilingIsRefusedInEveryFormat() throws {
+ let side = 320
+ let decodedBytes = side * side * 4
+ let budget = TranscriptImageLoader.Budget(
+ maximumSourcePixels: 50_000_000,
+ maximumSourceDimension: 32_768,
+ maximumDecodedBytes: decodedBytes / 2,
+ allowedTypeIdentifiers: Self.supportedTypes)
+
+ let directory = try Self.makeTemporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: directory) }
+
+ let png = directory.appendingPathComponent("square.png")
+ let jpeg = directory.appendingPathComponent("square.jpg")
+ try Self.writeSolidImage(width: side, height: side, type: .png, to: png)
+ try Self.writeSolidImage(width: side, height: side, type: .jpeg, to: jpeg)
+
+ #expect(TranscriptImageLoader.thumbnail(
+ at: png, maximumPixelSize: 64, budget: budget) == nil,
+ "a \(side)x\(side) PNG needs \(decodedBytes) decoded bytes against a \(decodedBytes / 2)-byte ceiling, so ImageIO must never be asked for it")
+ #expect(TranscriptImageLoader.thumbnail(
+ at: jpeg, maximumPixelSize: 64, budget: budget) == nil,
+ "the same pixels as a JPEG cost the same to hold, so the container must not change the answer")
+ }
+
+ /// The accepted path still has to produce a bounded tile, or the budget
+ /// would be buying nothing: a source many times the requested size comes
+ /// back at the requested size, not at its own.
+ @Test func anAcceptedSourceComesBackBoundedByTheRequestedSize() throws {
+ let directory = try Self.makeTemporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: directory) }
+
+ let url = directory.appendingPathComponent("small.png")
+ try Self.writeSolidImage(width: 64, height: 64, type: .png, to: url)
+
+ let image = try #require(TranscriptImageLoader.thumbnail(
+ at: url, maximumPixelSize: 16, budget: Self.generousBudget),
+ "a 64x64 PNG is far under every ceiling and has to load")
+ // `size` rather than the representation's pixel count: the transcript
+ // lays the image out from `size`, and the snapshot representation
+ // reports backing-scaled pixels, which differ per display.
+ #expect(image.size.width > 0 && image.size.width <= 16,
+ "the tile came back \(image.size.width) wide, so the requested 16-pixel bound was not applied")
+ }
+
+ /// The dimension and pixel caps are separate refusals from the byte
+ /// ceiling; a source can sit under the decoded-byte ceiling and still be
+ /// a shape the app will not draw.
+ @Test func sourcesOverTheDimensionOrPixelCapAreRefused() throws {
+ let directory = try Self.makeTemporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: directory) }
+
+ let url = directory.appendingPathComponent("small.png")
+ try Self.writeSolidImage(width: 64, height: 64, type: .png, to: url)
+
+ let overDimension = TranscriptImageLoader.Budget(
+ maximumSourcePixels: 50_000_000,
+ maximumSourceDimension: 32,
+ maximumDecodedBytes: 1 << 30,
+ allowedTypeIdentifiers: Self.supportedTypes)
+ #expect(TranscriptImageLoader.thumbnail(
+ at: url, maximumPixelSize: 16, budget: overDimension) == nil,
+ "a 64-pixel edge is over a 32-pixel dimension cap")
+
+ let overPixels = TranscriptImageLoader.Budget(
+ maximumSourcePixels: 1_000,
+ maximumSourceDimension: 32_768,
+ maximumDecodedBytes: 1 << 30,
+ allowedTypeIdentifiers: Self.supportedTypes)
+ #expect(TranscriptImageLoader.thumbnail(
+ at: url, maximumPixelSize: 16, budget: overPixels) == nil,
+ "4096 pixels is over a 1000-pixel cap")
+ }
+
+ /// Refusal and unreadability have to arrive the same way, because that is
+ /// the value both call sites already draw a placeholder for: a missing file
+ /// or a file that is not an image returns nil rather than throwing or
+ /// handing back an empty image the transcript would draw as a broken tile.
+ @Test func unreadableSourcesReturnNilRatherThanAnEmptyImage() throws {
+ let directory = try Self.makeTemporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: directory) }
+
+ let missing = directory.appendingPathComponent("absent.png")
+ #expect(TranscriptImageLoader.thumbnail(
+ at: missing, maximumPixelSize: 16, budget: Self.generousBudget) == nil)
+
+ let notAnImage = directory.appendingPathComponent("notes.png")
+ try Data("this is not a PNG".utf8).write(to: notAnImage)
+ #expect(TranscriptImageLoader.thumbnail(
+ at: notAnImage, maximumPixelSize: 16, budget: Self.generousBudget) == nil)
+ }
+
+ private static let generousBudget = TranscriptImageLoader.Budget(
+ maximumSourcePixels: 50_000_000,
+ maximumSourceDimension: 32_768,
+ maximumDecodedBytes: 1 << 30,
+ allowedTypeIdentifiers: Self.supportedTypes)
+
+ /// Decoding is what costs: `kCGImageSourceCreateThumbnailFromImageAlways`
+ /// pays a full decode for most formats, and it ran again on every redraw —
+ /// on the main thread, inside the render pass, at the moment Run was
+ /// pressed. Deleting the file between calls is how a hit is proved: a miss
+ /// has nothing left to read.
+ @Test func aDecodedThumbnailIsServedFromTheCacheOnTheSecondCall() throws {
+ let directory = try Self.makeTemporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: directory) }
+ TranscriptImageLoader.clearCache()
+ defer { TranscriptImageLoader.clearCache() }
+
+ let url = directory.appendingPathComponent("cached.png")
+ try Self.writeSolidImage(width: 64, height: 64, type: .png, to: url)
+ let key = "digest-of-cached-png"
+
+ #expect(TranscriptImageLoader.thumbnail(
+ at: url, maximumPixelSize: 32, budget: Self.permissiveBudget,
+ cacheKey: key) != nil)
+
+ try FileManager.default.removeItem(at: url)
+
+ #expect(TranscriptImageLoader.thumbnail(
+ at: url, maximumPixelSize: 32, budget: Self.permissiveBudget,
+ cacheKey: key) != nil,
+ "the second call decoded again instead of reusing the first")
+ // The size is part of the identity: the transcript asks for 720 and the
+ // composer for 96, and neither may be served the other's pixels.
+ #expect(TranscriptImageLoader.thumbnail(
+ at: url, maximumPixelSize: 720, budget: Self.permissiveBudget,
+ cacheKey: key) == nil,
+ "a different requested size was served from the wrong entry")
+ }
+
+ /// Cached copies are keyed on contents and released on demand, so a cleared
+ /// transcript does not leave decoded images held beside a resident model.
+ @Test func clearingTheCacheForcesTheNextCallToDecodeAgain() throws {
+ let directory = try Self.makeTemporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: directory) }
+ TranscriptImageLoader.clearCache()
+ defer { TranscriptImageLoader.clearCache() }
+
+ let url = directory.appendingPathComponent("cleared.png")
+ try Self.writeSolidImage(width: 64, height: 64, type: .png, to: url)
+ let key = "digest-of-cleared-png"
+
+ #expect(TranscriptImageLoader.thumbnail(
+ at: url, maximumPixelSize: 32, budget: Self.permissiveBudget,
+ cacheKey: key) != nil)
+ TranscriptImageLoader.clearCache()
+ try FileManager.default.removeItem(at: url)
+
+ #expect(TranscriptImageLoader.thumbnail(
+ at: url, maximumPixelSize: 32, budget: Self.permissiveBudget,
+ cacheKey: key) == nil,
+ "a cleared cache still answered from a decoded copy")
+ }
+
+ /// Without a key there is nothing to key on, so the caller must keep
+ /// getting a fresh read rather than another caller's image.
+ @Test func aCallWithoutAKeyIsNeverCached() throws {
+ let directory = try Self.makeTemporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: directory) }
+ TranscriptImageLoader.clearCache()
+ defer { TranscriptImageLoader.clearCache() }
+
+ let url = directory.appendingPathComponent("uncached.png")
+ try Self.writeSolidImage(width: 64, height: 64, type: .png, to: url)
+
+ #expect(TranscriptImageLoader.thumbnail(
+ at: url, maximumPixelSize: 32, budget: Self.permissiveBudget) != nil)
+ try FileManager.default.removeItem(at: url)
+ #expect(TranscriptImageLoader.thumbnail(
+ at: url, maximumPixelSize: 32, budget: Self.permissiveBudget) == nil,
+ "an unkeyed call was answered from the cache")
+ }
+
+ private static let permissiveBudget = TranscriptImageLoader.Budget(
+ maximumSourcePixels: 50_000_000,
+ maximumSourceDimension: 32_768,
+ maximumDecodedBytes: 96 * 1_024 * 1_024,
+ allowedTypeIdentifiers: Self.supportedTypes)
+
+ /// The runtime's allowlist, restated rather than imported so that widening
+ /// `VisionImageLimits` shows up here as a failing test instead of as a
+ /// silently larger decode surface.
+ private static let supportedTypes: Set<String> = [
+ "public.jpeg", "public.png", "public.heic", "public.heif",
+ "public.tiff", "com.compuserve.gif", "public.heics",
+ ]
+
+ /// A format the pack was never validated against must not reach ImageIO's
+ /// decoder for it. Every other limit here was copied from the runtime; the
+ /// type list was not, so a camera RAW or EXR was decoded at full size inside
+ /// the process holding the model and only then refused by the run.
+ ///
+ /// BMP stands in for the whole excluded set: ImageIO can both write and read
+ /// it, so the only thing separating it from the PNG below is the allowlist.
+ @Test func aFormatOutsideTheAllowlistIsRefusedBeforeDecoding() throws {
+ let directory = try Self.makeTemporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: directory) }
+
+ let bmp = directory.appendingPathComponent("swatch.bmp")
+ try Self.writeSolidImage(width: 64, height: 64, type: .bmp, to: bmp)
+ #expect(TranscriptImageLoader.thumbnail(
+ at: bmp, maximumPixelSize: 16, budget: Self.generousBudget) == nil,
+ "BMP is outside the runtime's allowlist, so it must not be decoded")
+
+ let png = directory.appendingPathComponent("swatch.png")
+ try Self.writeSolidImage(width: 64, height: 64, type: .png, to: png)
+ #expect(TranscriptImageLoader.thumbnail(
+ at: png, maximumPixelSize: 16, budget: Self.generousBudget) != nil,
+ "the same pixels as a PNG are inside the allowlist and must load")
+ }
+
+ /// The extension is not the format. ImageIO sniffs the bytes, so a file
+ /// named `.png` that holds BMP has to be refused on what it is.
+ @Test func theAllowlistFollowsTheBytesRatherThanTheExtension() throws {
+ let directory = try Self.makeTemporaryDirectory()
+ defer { try? FileManager.default.removeItem(at: directory) }
+
+ let disguised = directory.appendingPathComponent("actually-bmp.png")
+ try Self.writeSolidImage(width: 64, height: 64, type: .bmp, to: disguised)
+ #expect(TranscriptImageLoader.thumbnail(
+ at: disguised, maximumPixelSize: 16, budget: Self.generousBudget) == nil,
+ "the .png name must not admit BMP bytes to the decoder")
+ }
+
+ private static func makeTemporaryDirectory() throws -> URL {
+ let directory = FileManager.default.temporaryDirectory
+ .appendingPathComponent("output-pane-budget-\(UUID().uuidString)",
+ isDirectory: true)
+ try FileManager.default.createDirectory(
+ at: directory, withIntermediateDirectories: true)
+ return directory
+ }
+
+ private static func writeSolidImage(
+ width: Int, height: Int, type: UTType, to url: URL
+ ) throws {
+ let colorSpace = try #require(CGColorSpace(name: CGColorSpace.sRGB))
+ let bitmap = try #require(CGContext(
+ data: nil, width: width, height: height, bitsPerComponent: 8,
+ bytesPerRow: width * 4, space: colorSpace,
+ bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue))
+ bitmap.setFillColor(CGColor(gray: 0.5, alpha: 1))
+ bitmap.fill(CGRect(x: 0, y: 0, width: width, height: height))
+ let image = try #require(bitmap.makeImage())
+ let destination = try #require(CGImageDestinationCreateWithURL(
+ url as CFURL, type.identifier as CFString, 1, nil))
+ CGImageDestinationAddImage(destination, image, nil)
+ #expect(CGImageDestinationFinalize(destination))
+ }
+}
diff --git a/Tests/TurboFieldfareApp/MacPresentation/TranscriptPromptPrefixRebuildTests.swift b/Tests/TurboFieldfareApp/MacPresentation/TranscriptPromptPrefixRebuildTests.swift
new file mode 100644
index 00000000..80f5e409
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/TranscriptPromptPrefixRebuildTests.swift
@@ -0,0 +1,108 @@
+import AppKit
+import Foundation
+import Testing
+@testable import TurboFieldfareMacPresentation
+
+/// The image strip is built asynchronously and applied when it lands, so the
+/// identifier the controller is told about decides whether it ever gets drawn.
+///
+/// The coordinator used to record the final identifier up front, alongside an
+/// empty prefix, and only then start the build. When the built prefix arrived it
+/// carried that same identifier — so prompt, identifier, response and finalized
+/// state all matched, `needsRebuild` was false, `storage.length == 0` was false,
+/// and the strip was dropped. These tests pin both halves of the rule the fix
+/// relies on.
+@Suite @MainActor struct TranscriptPromptPrefixRebuildTests {
+ private func makePrefix(_ text: String) -> NSAttributedString {
+ NSAttributedString(string: text)
+ }
+
+ /// The failure mode, stated as a rule: same identifier, different prefix, no
+ /// rebuild. This is why the identifier must not be recorded before the
+ /// prefix it names exists.
+ @Test func areusedIdentifierDoesNotRedrawAChangedPrefix() {
+ let controller = InstructionTranscriptDocumentController()
+ let storage = NSMutableAttributedString()
+
+ _ = controller.synchronize(
+ storage: storage, prompt: "describe this", response: "",
+ isTerminal: false, promptPrefix: NSAttributedString(),
+ promptPrefixIdentifier: "image-a")
+
+ let late = controller.synchronize(
+ storage: storage, prompt: "describe this", response: "",
+ isTerminal: false, promptPrefix: makePrefix("[image]\n"),
+ promptPrefixIdentifier: "image-a")
+
+ #expect(late.mutation == .none,
+ "reusing the identifier redrew, so the coordinator's contract can be relaxed")
+ #expect(!storage.string.contains("[image]"))
+ }
+
+ /// The contract the coordinator now honours: the identifier stays empty
+ /// until the prefix exists, so the build landing is a change and rebuilds.
+ @Test func anidentifierArrivingWithItsPrefixRedraws() {
+ let controller = InstructionTranscriptDocumentController()
+ let storage = NSMutableAttributedString()
+
+ let initial = controller.synchronize(
+ storage: storage, prompt: "describe this", response: "",
+ isTerminal: false, promptPrefix: NSAttributedString(),
+ promptPrefixIdentifier: "")
+ #expect(initial.mutation == .rebuilt)
+ #expect(!storage.string.contains("[image]"))
+
+ let built = controller.synchronize(
+ storage: storage, prompt: "describe this", response: "",
+ isTerminal: false, promptPrefix: makePrefix("[image]\n"),
+ promptPrefixIdentifier: "image-a")
+
+ #expect(built.mutation == .rebuilt,
+ "the built image strip never reached the transcript")
+ #expect(storage.string.contains("[image]"))
+ #expect(storage.string.contains("describe this"))
+ }
+
+ /// A transcript that is already finished is the case with no rescue: there
+ /// is no first token to flip the prefill placeholder and force a rebuild, so
+ /// the late prefix has to redraw on its own.
+ @Test func afinishedTurnStillPicksUpItsImagesWhenTheyArriveLate() {
+ let controller = InstructionTranscriptDocumentController()
+ let storage = NSMutableAttributedString()
+
+ _ = controller.synchronize(
+ storage: storage, prompt: "describe this", response: "a cat",
+ isTerminal: true, promptPrefix: NSAttributedString(),
+ promptPrefixIdentifier: "")
+
+ let built = controller.synchronize(
+ storage: storage, prompt: "describe this", response: "a cat",
+ isTerminal: true, promptPrefix: makePrefix("[image]\n"),
+ promptPrefixIdentifier: "image-a")
+
+ #expect(built.mutation != .none)
+ #expect(storage.string.contains("[image]"),
+ "a finished image turn re-rendered with no images at all")
+ }
+
+ /// Changing the attachments changes the identifier, so the old strip must
+ /// come off even before the replacement is built.
+ @Test func clearingTheAttachmentsClearsTheStrip() {
+ let controller = InstructionTranscriptDocumentController()
+ let storage = NSMutableAttributedString()
+
+ _ = controller.synchronize(
+ storage: storage, prompt: "describe this", response: "",
+ isTerminal: false, promptPrefix: makePrefix("[image]\n"),
+ promptPrefixIdentifier: "image-a")
+ #expect(storage.string.contains("[image]"))
+
+ let cleared = controller.synchronize(
+ storage: storage, prompt: "describe this", response: "",
+ isTerminal: false, promptPrefix: NSAttributedString(),
+ promptPrefixIdentifier: "")
+
+ #expect(cleared.mutation == .rebuilt)
+ #expect(!storage.string.contains("[image]"))
+ }
+}
diff --git a/Tests/TurboFieldfareApp/MacPresentation/TranscriptScrollFollowTests.swift b/Tests/TurboFieldfareApp/MacPresentation/TranscriptScrollFollowTests.swift
new file mode 100644
index 00000000..788495e0
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/TranscriptScrollFollowTests.swift
@@ -0,0 +1,171 @@
+import Testing
+import CoreGraphics
+@testable import TurboFieldfareMacPresentation
+
+/// The transcript's auto-follow, which has now been wrong in both directions:
+/// pinned so hard the reader could not scroll during prefill, then released so
+/// eagerly that a prompt with several images stayed scrolled off the top.
+@Suite struct TranscriptScrollFollowTests {
+ /// Images finish laying out after the scroll and grow the document. The
+ /// view is left above the bottom through nobody's doing, and the follow
+ /// must re-anchor rather than conclude the reader took over. This is the
+ /// reported bug: several images, and the newest turn never comes into view.
+ @Test func growingContentKeepsTheFollowAlive() {
+ var follow = TranscriptScrollFollow()
+ follow.beginRun()
+ // First scroll: the document is short, the view sits at the bottom.
+ let firstScroll = follow.shouldScrollToBottom(origin: 0, documentHeight: 400)
+ #expect(firstScroll)
+ follow.recordScroll(origin: 0, documentHeight: 400)
+
+ // Four thumbnails land, each taller than the last tick's document.
+ var height: CGFloat = 400
+ for _ in 0..<4 {
+ height += 260
+ let keepsFollowing = follow.shouldScrollToBottom(
+ origin: 0, documentHeight: height)
+ #expect(keepsFollowing,
+ "the follow gave up when an image grew the document to \(height)")
+ // The view stays pinned to the bottom of the taller document.
+ follow.recordScroll(origin: height - 400, documentHeight: height)
+ }
+ #expect(follow.isFollowing)
+ }
+
+ /// The other direction: a reader scrolling back must end the follow at
+ /// once, even mid-prefill, and even though no live-scroll notification is
+ /// posted for keyboard or scrollbar movement.
+ @Test func aReaderScrollingEndsTheFollow() {
+ var follow = TranscriptScrollFollow()
+ follow.beginRun()
+ _ = follow.shouldScrollToBottom(origin: 600, documentHeight: 1_000)
+ follow.recordScroll(origin: 600, documentHeight: 1_000)
+
+ // Same document, different origin: nothing but a reader can do that.
+ #expect(follow.readerMoved(origin: 200, documentHeight: 1_000))
+ let afterReaderScroll = follow.shouldScrollToBottom(
+ origin: 200, documentHeight: 1_000)
+ #expect(!afterReaderScroll)
+ #expect(!follow.isFollowing, "the follow survived a reader scroll")
+ // And it stays ended once the document starts growing again.
+ let afterGrowth = follow.shouldScrollToBottom(origin: 200, documentHeight: 1_400)
+ #expect(!afterGrowth)
+ }
+
+ /// Growth and a reader scroll in the same tick resolve as growth. The
+ /// alternative is worse: dropping the follow on a coincidence puts the user
+ /// back in the bug this exists for, and the next tick catches the scroll
+ /// anyway once the document settles.
+ @Test func simultaneousGrowthAndScrollFavoursTheFollow() {
+ var follow = TranscriptScrollFollow()
+ follow.beginRun()
+ follow.recordScroll(origin: 100, documentHeight: 1_000)
+ #expect(!follow.readerMoved(origin: 40, documentHeight: 1_600))
+ let stillFollows = follow.shouldScrollToBottom(origin: 40, documentHeight: 1_600)
+ #expect(stillFollows)
+ }
+
+ /// Sub-pixel jitter is not a scroll. Layout rounding moves the origin by
+ /// fractions, and a follow that gave up on that would be no follow at all.
+ @Test func roundingIsNotAScroll() {
+ var follow = TranscriptScrollFollow()
+ follow.beginRun()
+ follow.recordScroll(origin: 100, documentHeight: 1_000)
+ #expect(!follow.readerMoved(origin: 100.2, documentHeight: 1_000.1))
+ let survivesJitter = follow.shouldScrollToBottom(
+ origin: 100.2, documentHeight: 1_000.1)
+ #expect(survivesJitter)
+ }
+
+ /// A new run always wins: it is the thing the user just asked for, and the
+ /// previous run's geometry says nothing about this one.
+ @Test func aNewRunRestartsTheFollowFromNoBaseline() {
+ var follow = TranscriptScrollFollow()
+ follow.beginRun()
+ follow.recordScroll(origin: 800, documentHeight: 2_000)
+ _ = follow.shouldScrollToBottom(origin: 100, documentHeight: 2_000)
+ #expect(!follow.isFollowing)
+
+ follow.beginRun()
+ #expect(follow.isFollowing)
+ // No baseline yet, so nothing counts as a reader scroll.
+ #expect(!follow.readerMoved(origin: 0, documentHeight: 50))
+ let scrollsForNewRun = follow.shouldScrollToBottom(origin: 0, documentHeight: 50)
+ #expect(scrollsForNewRun)
+ }
+
+ /// Ending on the answer's first text is what hands control back; a follow
+ /// that never ended is the "cannot scroll during generation" complaint.
+ @Test func endStopsTheFollowOutright() {
+ var follow = TranscriptScrollFollow()
+ follow.beginRun()
+ follow.end()
+ #expect(!follow.isFollowing)
+ let afterEnd = follow.shouldScrollToBottom(origin: 0, documentHeight: 10_000)
+ #expect(!afterEnd)
+ }
+}
+
+/// The composer's attachment tiles. Aspect-fitting them gave a row of
+/// mismatched heights — a wide screenshot came out a third the height of a
+/// portrait photo — and the remove badge, pinned to the tile's corner, floated
+/// clear of the short ones.
+@Suite struct AttachmentTileGeometryTests {
+ private let tile = CGSize(width: 48, height: 48)
+
+ /// What fitting did, kept as the reason the view no longer uses it.
+ @Test func fittingProducesMismatchedHeights() {
+ let wide = TranscriptImageTile.fittedSize(
+ CGSize(width: 3_024, height: 1_000), within: tile)
+ let tall = TranscriptImageTile.fittedSize(
+ CGSize(width: 1_000, height: 3_024), within: tile)
+ #expect(wide.height < tall.height / 2,
+ "these two fitted to comparable heights, so the row was never ragged")
+ }
+
+ /// Filling gives every attachment the same tile, whatever its shape, and
+ /// covers it completely so no background shows through.
+ @Test func fillingGivesEveryShapeTheSameTile() {
+ for source in [CGSize(width: 3_024, height: 1_000),
+ CGSize(width: 1_000, height: 3_024),
+ CGSize(width: 512, height: 512),
+ CGSize(width: 8_000, height: 6_000)] {
+ let filled = TranscriptImageTile.filledSize(source, within: tile)
+ #expect(filled.width >= tile.width - 0.01
+ && filled.height >= tile.height - 0.01,
+ "\(source) left part of the tile uncovered: \(filled)")
+ // Aspect preserved: one dimension matches exactly, the other spills.
+ let ratio = filled.width / filled.height
+ let sourceRatio = source.width / source.height
+ #expect(abs(ratio - sourceRatio) < 0.01,
+ "\(source) was distorted to \(filled)")
+ }
+ }
+
+ /// A degenerate image must not produce a zero or infinite tile.
+ @Test func adegenerateSourceStillFillsTheTile() {
+ let filled = TranscriptImageTile.filledSize(.zero, within: tile)
+ #expect(filled == tile)
+ }
+
+ /// Fitting bounds an image; it does not enlarge one. The transcript draws
+ /// at the returned size, so an unclamped scale turned a 64 pt icon into a
+ /// 240 pt canvas of the same 64 pixels — a 3.75x blur on every small
+ /// attachment.
+ @Test func fittingNeverEnlargesASourceSmallerThanTheTile() {
+ let transcriptTile = CGSize(width: 360, height: 240)
+ let icon = CGSize(width: 64, height: 64)
+ #expect(TranscriptImageTile.fittedSize(icon, within: transcriptTile) == icon,
+ "a source already inside the tile has to come back at its own size")
+
+ // One axis under, one axis over: the oversized axis still decides the
+ // scale, so this must shrink rather than pass through unchanged.
+ let wideAndShort = CGSize(width: 720, height: 100)
+ let fitted = TranscriptImageTile.fittedSize(wideAndShort, within: transcriptTile)
+ #expect(fitted.width <= transcriptTile.width + 0.01
+ && fitted.height <= transcriptTile.height + 0.01,
+ "\(wideAndShort) came back as \(fitted), outside the tile")
+ #expect(fitted.width < wideAndShort.width,
+ "an over-wide source still has to be scaled down")
+ }
+}
diff --git a/Tests/TurboFieldfareDecodeService/DecodeServiceOutboxTests.swift b/Tests/TurboFieldfareDecodeService/DecodeServiceOutboxTests.swift
index 55f42952..632a992f 100644
--- a/Tests/TurboFieldfareDecodeService/DecodeServiceOutboxTests.swift
+++ b/Tests/TurboFieldfareDecodeService/DecodeServiceOutboxTests.swift
@@ -32,6 +32,82 @@ import TurboFieldfareDecodeProtocol
#expect(event.error == "first")
}
+ /// Image encoding produces no progress or tokens, so the outbox must emit
+ /// memory-only events during that otherwise silent interval.
+ @Test func aSilentGenerationStillReportsMemory() throws {
+ let generationID = UUID()
+ let outbox = DecodeServiceOutbox(generationID: generationID)
+ let pipe = Pipe()
+ let writerFinished = DispatchSemaphore(value: 0)
+ let writer = Thread {
+ defer {
+ try? pipe.fileHandleForWriting.close()
+ writerFinished.signal()
+ }
+ try? outbox.runWriter(to: pipe.fileHandleForWriting)
+ }
+ writer.start()
+
+ let first = try DecodeFrameCodec.read(
+ DecodeServiceEvent.self, from: pipe.fileHandleForReading)
+ #expect(first.kind == .memory)
+ #expect(first.generationID == generationID)
+ #expect(try #require(first.currentMemoryBytes) > 0)
+
+ let second = try DecodeFrameCodec.read(
+ DecodeServiceEvent.self, from: pipe.fileHandleForReading)
+ #expect(second.kind == .memory)
+
+ outbox.publish(.prefillProgress(done: 4, total: 8))
+ var event = try DecodeFrameCodec.read(
+ DecodeServiceEvent.self, from: pipe.fileHandleForReading)
+ while event.kind == .memory {
+ event = try DecodeFrameCodec.read(
+ DecodeServiceEvent.self, from: pipe.fileHandleForReading)
+ }
+ #expect(event.kind == .prefill)
+ #expect(event.prefillDone == 4)
+ #expect(event.currentMemoryBytes != nil)
+
+ outbox.finish(error: AppInferenceError.cancelled)
+ #expect(writerFinished.wait(timeout: .now() + 5) == .success)
+ }
+
+ @Test func liveEventsCarryTheImageTowerFigure() throws {
+ let generationID = UUID()
+ let outbox = DecodeServiceOutbox(
+ generationID: generationID,
+ towerBytes: { 1_144_373_248 })
+ let pipe = Pipe()
+ let writerFinished = DispatchSemaphore(value: 0)
+ let writer = Thread {
+ defer {
+ try? pipe.fileHandleForWriting.close()
+ writerFinished.signal()
+ }
+ try? outbox.runWriter(to: pipe.fileHandleForWriting)
+ }
+ writer.start()
+
+ let idle = try DecodeFrameCodec.read(
+ DecodeServiceEvent.self, from: pipe.fileHandleForReading)
+ #expect(idle.kind == .memory)
+ #expect(idle.visionTowerMappedBytes == 1_144_373_248)
+
+ outbox.publish(.prefillProgress(done: 1, total: 2))
+ var event = try DecodeFrameCodec.read(
+ DecodeServiceEvent.self, from: pipe.fileHandleForReading)
+ while event.kind == .memory {
+ event = try DecodeFrameCodec.read(
+ DecodeServiceEvent.self, from: pipe.fileHandleForReading)
+ }
+ #expect(event.kind == .prefill)
+ #expect(event.visionTowerMappedBytes == 1_144_373_248)
+
+ outbox.finish(error: AppInferenceError.cancelled)
+ #expect(writerFinished.wait(timeout: .now() + 5) == .success)
+ }
+
private func firstTerminal(
from outbox: DecodeServiceOutbox,
published event: AppInferenceEvent,
diff --git a/Tests/TurboFieldfareDecodeService/DecodeSocketTrustTests.swift b/Tests/TurboFieldfareDecodeService/DecodeSocketTrustTests.swift
new file mode 100644
index 00000000..11df6d8a
--- /dev/null
+++ b/Tests/TurboFieldfareDecodeService/DecodeSocketTrustTests.swift
@@ -0,0 +1,133 @@
+import Darwin
+import Foundation
+import Testing
+import TurboFieldfareAppCore
+import TurboFieldfareDecodeProtocol
+
+/// The decode socket lives in a world-writable directory and carries model
+/// paths, attachment paths and generated text. Two rules keep it honest: only
+/// this user may connect, and only files this app staged may be opened.
+@Suite struct DecodeSocketTrustTests {
+ @Test func aConnectionFromThisUserIsAccepted() async throws {
+ let path = "/private/tmp/turbofieldfare-trust-\(UUID().uuidString).sock"
+ defer { unlink(path) }
+ let accepted = Mutex2<(input: FileHandle, output: FileHandle)?>(nil)
+ let listener = Thread {
+ accepted.set(try? DecodeUnixSocket.listenAndAccept(path: path))
+ }
+ listener.start()
+ let ready = Date().addingTimeInterval(5)
+ while !FileManager.default.fileExists(atPath: path), Date() < ready {
+ usleep(5_000)
+ }
+
+ // The socket file exists from bind(), which is before listen(), so a
+ // connect in that window is refused. The production client retries for
+ // the same reason.
+ let client = try connectWithRetry(path: path)
+ let deadline = Date().addingTimeInterval(5)
+ while accepted.get() == nil, Date() < deadline { usleep(5_000) }
+ #expect(accepted.get() != nil, "the owner's own connection was refused")
+ try? client.input.close()
+ try? client.output.close()
+ }
+
+ /// The socket is created before the app connects, so anyone can reach it in
+ /// that window. It must not be readable by other users at all.
+ @Test func theSocketIsNotReachableByOtherUsers() async throws {
+ let path = "/private/tmp/turbofieldfare-mode-\(UUID().uuidString).sock"
+ defer { unlink(path) }
+ let listener = Thread {
+ _ = try? DecodeUnixSocket.listenAndAccept(path: path)
+ }
+ listener.start()
+ let ready = Date().addingTimeInterval(5)
+ while !FileManager.default.fileExists(atPath: path), Date() < ready {
+ usleep(5_000)
+ }
+
+ var info = stat()
+ #expect(lstat(path, &info) == 0)
+ let mode = info.st_mode & 0o777
+ #expect(mode & 0o077 == 0,
+ "the socket is reachable by other users: \(String(mode, radix: 8))")
+
+ // Unblock the listener.
+ let client = try? connectWithRetry(path: path)
+ try? client?.input.close()
+ try? client?.output.close()
+ }
+
+ /// The service opens and hashes whatever path it is handed, so a path
+ /// outside the attachment store would make it an oracle for any file the
+ /// user can read.
+ @Test func onlyStagedAttachmentPathsAreAccepted() throws {
+ let root = AppImageAttachmentStore.root
+ let staged = root
+ .appendingPathComponent("pid-\(getpid())", isDirectory: true)
+ .appendingPathComponent(UUID().uuidString, isDirectory: true)
+ .appendingPathComponent("image.png")
+ #expect(AppImageAttachmentStore.contains(staged))
+
+ #expect(!AppImageAttachmentStore.contains(URL(fileURLWithPath: "/etc/passwd")))
+ #expect(!AppImageAttachmentStore.contains(
+ URL(fileURLWithPath: FileManager.default.temporaryDirectory.path)
+ .appendingPathComponent("elsewhere.png")))
+ #expect(!AppImageAttachmentStore.contains(root),
+ "the root itself is a directory, not an attachment")
+ // Traversal back out of the root must not pass.
+ #expect(!AppImageAttachmentStore.contains(
+ root.appendingPathComponent("../../etc/passwd")))
+ }
+
+ /// A symlink planted inside the root must not smuggle a target outside it.
+ @Test func aSymlinkOutOfTheStoreIsRejected() throws {
+ let manager = FileManager.default
+ let root = AppImageAttachmentStore.root
+ .appendingPathComponent("pid-\(getpid())", isDirectory: true)
+ .appendingPathComponent("trust-\(UUID().uuidString)", isDirectory: true)
+ try manager.createDirectory(at: root, withIntermediateDirectories: true)
+ defer { try? manager.removeItem(at: root) }
+ let outside = manager.temporaryDirectory
+ .appendingPathComponent("outside-\(UUID().uuidString).png")
+ try Data("secret".utf8).write(to: outside)
+ defer { try? manager.removeItem(at: outside) }
+
+ let link = root.appendingPathComponent("link.png")
+ try manager.createSymbolicLink(at: link, withDestinationURL: outside)
+ #expect(!AppImageAttachmentStore.contains(link),
+ "a symlink pointed the store at a file outside it")
+ }
+}
+
+private func connectWithRetry(
+ path: String,
+ timeout: TimeInterval = 10
+) throws -> (input: FileHandle, output: FileHandle) {
+ let deadline = Date().addingTimeInterval(timeout)
+ var lastError: Error?
+ while Date() < deadline {
+ do { return try DecodeUnixSocket.connect(path: path) }
+ catch { lastError = error; usleep(5_000) }
+ }
+ throw lastError ?? POSIXError(.ECONNREFUSED)
+}
+
+/// A tiny lock, because `Synchronization.Mutex` cannot hold a non-Sendable
+/// tuple of file handles.
+private final class Mutex2<Value>: @unchecked Sendable {
+ private let lock = NSLock()
+ private var value: Value
+
+ init(_ value: Value) { self.value = value }
+
+ func get() -> Value {
+ lock.lock(); defer { lock.unlock() }
+ return value
+ }
+
+ func set(_ newValue: Value) {
+ lock.lock(); defer { lock.unlock() }
+ value = newValue
+ }
+}
diff --git a/Tests/TurboFieldfareFormat/GTurboVisionFormatTests.swift b/Tests/TurboFieldfareFormat/GTurboVisionFormatTests.swift
new file mode 100644
index 00000000..753682a7
--- /dev/null
+++ b/Tests/TurboFieldfareFormat/GTurboVisionFormatTests.swift
@@ -0,0 +1,159 @@
+import Foundation
+import Testing
+@testable import TurboFieldfareFormat
+
+private enum VisionFormatFixture {
+ static let zeroSHA = String(repeating: "0", count: 64)
+
+ static func manifest(tensors: [GTurboVisionTensorRegionV1]? = nil)
+ -> GTurboVisionManifestV1 {
+ let defaultTensors = [
+ GTurboVisionTensorRegionV1(
+ name: "vision_tower.patch_embedder.input_proj.weight",
+ executionPosition: 0, offset: 0, size: 512,
+ shape: [16, 16], dtype: .bf16),
+ GTurboVisionTensorRegionV1(
+ name: "embed_vision.embedding_projection.weight",
+ executionPosition: 1, offset: GTurboVisionFormatV1.alignmentBytes,
+ size: 256, shape: [8, 8], dtype: .u32,
+ quantization: GTurboVisionQuantizationV1(
+ weightBits: 4, scheme: "affine", scaleType: "bf16",
+ biasType: "bf16", groupSize: 64)),
+ ]
+ return GTurboVisionManifestV1(
+ modelID: "fixture/model", sourceRevision: "fixture-revision",
+ sourceIndexSha256: zeroSHA, processorConfigSha256: zeroSHA,
+ compatibleTextSourceSnapshotHash: "fixture-text-snapshot",
+ compatibleTextManifestSha256: zeroSHA,
+ files: [
+ GTurboVisionFormatV1.weightsFile: GTurboManifestFileV1(
+ size: 2 * GTurboVisionFormatV1.alignmentBytes, sha256: zeroSHA),
+ GTurboVisionFormatV1.processorFile: GTurboManifestFileV1(
+ size: 2, sha256: zeroSHA),
+ ],
+ tensors: tensors ?? defaultTensors)
+ }
+
+ static func receipt() -> GTurboVisionReceiptV1 {
+ GTurboVisionReceiptV1(
+ manifestSha256: zeroSHA,
+ companionDirectoryPath: "/fixture/model.vision.gturbo",
+ compatibleTextManifestSha256: zeroSHA,
+ sourceRepoID: "fixture/model", sourceRevision: "fixture-revision",
+ verificationTimestamp: "2026-08-05T00:00:00Z",
+ toolVersion: "fixture",
+ files: [
+ GTurboVisionFormatV1.manifestFile: .init(size: 1, sha256: zeroSHA),
+ GTurboVisionFormatV1.weightsFile: .init(
+ size: 2 * GTurboVisionFormatV1.alignmentBytes, sha256: zeroSHA),
+ GTurboVisionFormatV1.processorFile: .init(size: 2, sha256: zeroSHA),
+ ])
+ }
+}
+
+@Suite struct GTurboVisionFormatCompatibilityTests {
+ @Test func manifestAndReceiptRoundTripDeterministically() throws {
+ let manifest = VisionFormatFixture.manifest()
+ let manifestData = try GTurboVisionManifestCodec.encode(manifest)
+ #expect(try GTurboVisionManifestCodec.decode(manifestData) == manifest)
+ #expect(try GTurboVisionManifestCodec.encode(manifest) == manifestData)
+
+ let receipt = VisionFormatFixture.receipt()
+ let receiptData = try GTurboVisionReceiptCodec.encode(receipt)
+ #expect(try GTurboVisionReceiptCodec.decode(receiptData) == receipt)
+ #expect(try GTurboVisionReceiptCodec.encode(receipt) == receiptData)
+ }
+
+ @Test func rejectsUnknownVersion() {
+ let original = VisionFormatFixture.manifest()
+ let changed = GTurboVisionManifestV1(
+ versionMajor: 2, modelID: original.modelID,
+ sourceRevision: original.sourceRevision,
+ sourceIndexSha256: original.sourceIndexSha256,
+ processorConfigSha256: original.processorConfigSha256,
+ compatibleTextSourceSnapshotHash: original.compatibleTextSourceSnapshotHash,
+ compatibleTextManifestSha256: original.compatibleTextManifestSha256,
+ files: original.files, tensors: original.tensors)
+ #expect(throws: GTurboFormatError.self) {
+ try GTurboVisionManifestCodec.encode(changed)
+ }
+ }
+
+ @Test func rejectsReorderedRegions() {
+ let original = VisionFormatFixture.manifest().tensors
+ let changed = [
+ GTurboVisionTensorRegionV1(
+ name: original[0].name, executionPosition: 1,
+ offset: original[0].offset, size: original[0].size,
+ shape: original[0].shape, dtype: original[0].dtype),
+ original[1],
+ ]
+ #expect(throws: GTurboFormatError.self) {
+ try GTurboVisionManifestCodec.encode(
+ VisionFormatFixture.manifest(tensors: changed))
+ }
+ }
+
+ @Test func rejectsMisalignedOverlappingAndOutOfFileRegions() {
+ let invalid: [GTurboVisionTensorRegionV1] = [
+ .init(name: "a", executionPosition: 0, offset: 1,
+ size: 2, shape: [1], dtype: .bf16),
+ .init(name: "b", executionPosition: 1,
+ offset: 2 * GTurboVisionFormatV1.alignmentBytes,
+ size: 2, shape: [1], dtype: .bf16),
+ ]
+ #expect(throws: GTurboFormatError.self) {
+ try GTurboVisionManifestCodec.encode(
+ VisionFormatFixture.manifest(tensors: invalid))
+ }
+ }
+
+ @Test func rejectsInvalidStorageSizeAndQuantization() {
+ let badSize = [GTurboVisionTensorRegionV1(
+ name: "a", executionPosition: 0, offset: 0,
+ size: 3, shape: [1], dtype: .bf16)]
+ #expect(throws: GTurboFormatError.self) {
+ try GTurboVisionManifestCodec.encode(
+ VisionFormatFixture.manifest(tensors: badSize))
+ }
+
+ let badQuant = [GTurboVisionTensorRegionV1(
+ name: "a", executionPosition: 0, offset: 0,
+ size: 4, shape: [1], dtype: .u32)]
+ #expect(throws: GTurboFormatError.self) {
+ try GTurboVisionManifestCodec.encode(
+ VisionFormatFixture.manifest(tensors: badQuant))
+ }
+ }
+
+ @Test func rejectsUnexpectedPayloadOrReceiptFile() {
+ let original = VisionFormatFixture.manifest()
+ var files = original.files
+ files["extra.bin"] = .init(size: 1, sha256: VisionFormatFixture.zeroSHA)
+ let changed = GTurboVisionManifestV1(
+ modelID: original.modelID, sourceRevision: original.sourceRevision,
+ sourceIndexSha256: original.sourceIndexSha256,
+ processorConfigSha256: original.processorConfigSha256,
+ compatibleTextSourceSnapshotHash: original.compatibleTextSourceSnapshotHash,
+ compatibleTextManifestSha256: original.compatibleTextManifestSha256,
+ files: files, tensors: original.tensors)
+ #expect(throws: GTurboFormatError.self) {
+ try GTurboVisionManifestCodec.encode(changed)
+ }
+
+ let receipt = VisionFormatFixture.receipt()
+ let missing = GTurboVisionReceiptV1(
+ manifestSha256: receipt.manifestSha256,
+ companionDirectoryPath: receipt.companionDirectoryPath,
+ compatibleTextManifestSha256: receipt.compatibleTextManifestSha256,
+ sourceRepoID: receipt.sourceRepoID,
+ sourceRevision: receipt.sourceRevision,
+ verificationTimestamp: receipt.verificationTimestamp,
+ toolVersion: receipt.toolVersion,
+ files: [GTurboVisionFormatV1.manifestFile:
+ receipt.files[GTurboVisionFormatV1.manifestFile]!])
+ #expect(throws: GTurboFormatError.self) {
+ try GTurboVisionReceiptCodec.encode(missing)
+ }
+ }
+}
diff --git a/Tests/TurboFieldfareFormat/GTurboVisionLockPathsTests.swift b/Tests/TurboFieldfareFormat/GTurboVisionLockPathsTests.swift
new file mode 100644
index 00000000..32651eeb
--- /dev/null
+++ b/Tests/TurboFieldfareFormat/GTurboVisionLockPathsTests.swift
@@ -0,0 +1,46 @@
+import Foundation
+import Testing
+import TurboFieldfareFormat
+
+/// Every reader and writer of a vision companion must derive the same lock
+/// file; these pin the shared derivation itself.
+@Suite struct GTurboVisionLockPathsTests {
+
+ @Test func lockFileIsADottedSiblingOfTheCompanion() throws {
+ let fm = FileManager.default
+ let root = fm.temporaryDirectory
+ .appendingPathComponent("lockpaths-\(UUID().uuidString)", isDirectory: true)
+ try fm.createDirectory(at: root, withIntermediateDirectories: true)
+ defer { try? fm.removeItem(at: root) }
+ let url = GTurboVisionLockPathsV1.useLockURL(
+ forCompanion: root.appendingPathComponent("pack.vision.gturbo"))
+ #expect(url.lastPathComponent == ".pack.vision.gturbo.use.lock")
+ #expect(url.deletingLastPathComponent().lastPathComponent
+ == root.lastPathComponent)
+ }
+
+ @Test func symlinkedParentDerivesTheSameLockFileAsThePhysicalPath() throws {
+ let fm = FileManager.default
+ let root = fm.temporaryDirectory
+ .appendingPathComponent("lockpaths-\(UUID().uuidString)", isDirectory: true)
+ let real = root.appendingPathComponent("real", isDirectory: true)
+ try fm.createDirectory(at: real, withIntermediateDirectories: true)
+ let link = root.appendingPathComponent("link")
+ try fm.createSymbolicLink(at: link, withDestinationURL: real)
+ defer { try? fm.removeItem(at: root) }
+ let viaReal = GTurboVisionLockPathsV1.useLockURL(
+ forCompanion: real.appendingPathComponent("p.gturbo"))
+ let viaLink = GTurboVisionLockPathsV1.useLockURL(
+ forCompanion: link.appendingPathComponent("p.gturbo"))
+ #expect(viaReal.path == viaLink.path)
+ }
+
+ @Test func nonexistentParentStillDerivesDeterministically() {
+ let a = GTurboVisionLockPathsV1.useLockURL(
+ forCompanion: URL(fileURLWithPath: "/nonexistent-lockpath-test/p.gturbo"))
+ let b = GTurboVisionLockPathsV1.useLockURL(
+ forCompanion: URL(fileURLWithPath: "/nonexistent-lockpath-test/x/../p.gturbo"))
+ #expect(a.path == b.path)
+ #expect(a.lastPathComponent == ".p.gturbo.use.lock")
+ }
+}
diff --git a/Tests/TurboFieldfareFormatCompatibility/Fixtures/v1/vision-manifest.json.base64 b/Tests/TurboFieldfareFormatCompatibility/Fixtures/v1/vision-manifest.json.base64
new file mode 100644
index 00000000..402e91c0
--- /dev/null
+++ b/Tests/TurboFieldfareFormatCompatibility/Fixtures/v1/vision-manifest.json.base64
@@ -0,0 +1 @@
+ewogICJhcnRpZmFjdEtpbmQiIDogImdlbW1hNF92aXNpb25fY29tcGFuaW9uIiwKICAiY29tcGF0aWJsZVRleHRNYW5pZmVzdFNoYTI1NiIgOiAiMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMCIsCiAgImNvbXBhdGlibGVUZXh0U291cmNlU25hcHNob3RIYXNoIiA6ICJmaXh0dXJlLXRleHQtc25hcHNob3QiLAogICJmaWxlcyIgOiB7CiAgICAicHJvY2Vzc29yX2NvbmZpZy5qc29uIiA6IHsKICAgICAgInNoYTI1NiIgOiAiMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMCIsCiAgICAgICJzaXplIiA6IDIKICAgIH0sCiAgICAidmlzaW9uX3dlaWdodHMuYmluIiA6IHsKICAgICAgInNoYTI1NiIgOiAiMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMCIsCiAgICAgICJzaXplIiA6IDMyNzY4CiAgICB9CiAgfSwKICAibWFnaWMiIDogIkdUVVJCTy1WSVNJT04iLAogICJtb2RlbElEIiA6ICJmaXh0dXJlL21vZGVsIiwKICAicHJvY2Vzc29yQ29uZmlnU2hhMjU2IiA6ICIwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwIiwKICAic291cmNlSW5kZXhTaGEyNTYiIDogIjAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAiLAogICJzb3VyY2VSZXZpc2lvbiIgOiAiZml4dHVyZS1yZXZpc2lvbiIsCiAgInRlbnNvcnMiIDogWwogICAgewogICAgICAiZHR5cGUiIDogImJmMTYiLAogICAgICAiZXhlY3V0aW9uUG9zaXRpb24iIDogMCwKICAgICAgImZpbGUiIDogInZpc2lvbl93ZWlnaHRzLmJpbiIsCiAgICAgICJuYW1lIiA6ICJ2aXNpb25fdG93ZXIucGF0Y2hfZW1iZWRkZXIuaW5wdXRfcHJvai53ZWlnaHQiLAogICAgICAib2Zmc2V0IiA6IDAsCiAgICAgICJzaGFwZSIgOiBbCiAgICAgICAgMTYsCiAgICAgICAgMTYKICAgICAgXSwKICAgICAgInNpemUiIDogNTEyCiAgICB9LAogICAgewogICAgICAiZHR5cGUiIDogInUzMiIsCiAgICAgICJleGVjdXRpb25Qb3NpdGlvbiIgOiAxLAogICAgICAiZmlsZSIgOiAidmlzaW9uX3dlaWdodHMuYmluIiwKICAgICAgIm5hbWUiIDogImVtYmVkX3Zpc2lvbi5lbWJlZGRpbmdfcHJvamVjdGlvbi53ZWlnaHQiLAogICAgICAib2Zmc2V0IiA6IDE2Mzg0LAogICAgICAicXVhbnRpemF0aW9uIiA6IHsKICAgICAgICAiYmlhc1R5cGUiIDogImJmMTYiLAogICAgICAgICJncm91cFNpemUiIDogNjQsCiAgICAgICAgInNjYWxlVHlwZSIgOiAiYmYxNiIsCiAgICAgICAgInNjaGVtZSIgOiAiYWZmaW5lIiwKICAgICAgICAid2VpZ2h0Qml0cyIgOiA0CiAgICAgIH0sCiAgICAgICJzaGFwZSIgOiBbCiAgICAgICAgOCwKICAgICAgICA4CiAgICAgIF0sCiAgICAgICJzaXplIiA6IDI1NgogICAgfQogIF0sCiAgInZlcnNpb25NYWpvciIgOiAxLAogICJ2ZXJzaW9uTWlub3IiIDogMAp9
diff --git a/Tests/TurboFieldfareFormatCompatibility/Fixtures/v1/vision-receipt.json.base64 b/Tests/TurboFieldfareFormatCompatibility/Fixtures/v1/vision-receipt.json.base64
new file mode 100644
index 00000000..de601103
--- /dev/null
+++ b/Tests/TurboFieldfareFormatCompatibility/Fixtures/v1/vision-receipt.json.base64
@@ -0,0 +1 @@
+ewogICJhcnRpZmFjdEtpbmQiIDogImdlbW1hNF92aXNpb25fY29tcGFuaW9uIiwKICAiY29tcGFuaW9uRGlyZWN0b3J5UGF0aCIgOiAiL2ZpeHR1cmUvbW9kZWwudmlzaW9uLmd0dXJibyIsCiAgImNvbXBhdGlibGVUZXh0TWFuaWZlc3RTaGEyNTYiIDogIjAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAiLAogICJmaWxlcyIgOiB7CiAgICAibWFuaWZlc3QuanNvbiIgOiB7CiAgICAgICJzaGEyNTYiIDogIjAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAiLAogICAgICAic2l6ZSIgOiAxCiAgICB9LAogICAgInByb2Nlc3Nvcl9jb25maWcuanNvbiIgOiB7CiAgICAgICJzaGEyNTYiIDogIjAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAiLAogICAgICAic2l6ZSIgOiAyCiAgICB9LAogICAgInZpc2lvbl93ZWlnaHRzLmJpbiIgOiB7CiAgICAgICJzaGEyNTYiIDogIjAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAiLAogICAgICAic2l6ZSIgOiAzMjc2OAogICAgfQogIH0sCiAgIm1hbmlmZXN0U2hhMjU2IiA6ICIwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwIiwKICAic2NoZW1hVmVyc2lvbiIgOiAxLAogICJzb3VyY2VSZXBvSUQiIDogImZpeHR1cmUvbW9kZWwiLAogICJzb3VyY2VSZXZpc2lvbiIgOiAiZml4dHVyZS1yZXZpc2lvbiIsCiAgInRvb2xWZXJzaW9uIiA6ICJmaXh0dXJlIiwKICAidmVyaWZpY2F0aW9uVGltZXN0YW1wIiA6ICIyMDI2LTA4LTA1VDAwOjAwOjAwWiIKfQ==
diff --git a/Tests/TurboFieldfareFormatCompatibility/GTurboFormatCompatibilityTests.swift b/Tests/TurboFieldfareFormatCompatibility/GTurboFormatCompatibilityTests.swift
index 73630a76..4d1aa2f2 100644
--- a/Tests/TurboFieldfareFormatCompatibility/GTurboFormatCompatibilityTests.swift
+++ b/Tests/TurboFieldfareFormatCompatibility/GTurboFormatCompatibilityTests.swift
@@ -159,6 +159,51 @@ import Testing
return stream.finalizeHexString()
}
+ @Test func visionCompanionCodecsMatchV1Fixtures() throws {
+ let zeroSHA = String(repeating: "0", count: 64)
+ let manifest = GTurboVisionManifestV1(
+ modelID: "fixture/model", sourceRevision: "fixture-revision",
+ sourceIndexSha256: zeroSHA, processorConfigSha256: zeroSHA,
+ compatibleTextSourceSnapshotHash: "fixture-text-snapshot",
+ compatibleTextManifestSha256: zeroSHA,
+ files: [
+ GTurboVisionFormatV1.weightsFile: .init(size: 32_768, sha256: zeroSHA),
+ GTurboVisionFormatV1.processorFile: .init(size: 2, sha256: zeroSHA),
+ ],
+ tensors: [
+ .init(
+ name: "vision_tower.patch_embedder.input_proj.weight",
+ executionPosition: 0, offset: 0, size: 512,
+ shape: [16, 16], dtype: .bf16),
+ .init(
+ name: "embed_vision.embedding_projection.weight",
+ executionPosition: 1, offset: 16_384, size: 256,
+ shape: [8, 8], dtype: .u32,
+ quantization: .init(
+ weightBits: 4, scheme: "affine", scaleType: "bf16",
+ biasType: "bf16", groupSize: 64)),
+ ])
+ let receipt = GTurboVisionReceiptV1(
+ manifestSha256: zeroSHA,
+ companionDirectoryPath: "/fixture/model.vision.gturbo",
+ compatibleTextManifestSha256: zeroSHA,
+ sourceRepoID: "fixture/model", sourceRevision: "fixture-revision",
+ verificationTimestamp: "2026-08-05T00:00:00Z",
+ toolVersion: "fixture",
+ files: [
+ GTurboVisionFormatV1.manifestFile: .init(size: 1, sha256: zeroSHA),
+ GTurboVisionFormatV1.weightsFile: .init(size: 32_768, sha256: zeroSHA),
+ GTurboVisionFormatV1.processorFile: .init(size: 2, sha256: zeroSHA),
+ ])
+
+ let manifestFixture = try frozenFixture("vision-manifest.json")
+ let receiptFixture = try frozenFixture("vision-receipt.json")
+ #expect(try GTurboVisionManifestCodec.encode(manifest) == manifestFixture)
+ #expect(try GTurboVisionReceiptCodec.encode(receipt) == receiptFixture)
+ #expect(try GTurboVisionManifestCodec.decode(manifestFixture) == manifest)
+ #expect(try GTurboVisionReceiptCodec.decode(receiptFixture) == receipt)
+ }
+
private func frozenFixture(_ name: String) throws -> Data {
let url = try #require(Bundle.module.url(
forResource: name, withExtension: "base64", subdirectory: "Fixtures/v1"))
diff --git a/Tests/TurboFieldfareRepack/Core/Command/RepackCLITests.swift b/Tests/TurboFieldfareRepack/Core/Command/RepackCLITests.swift
index fec5a75e..8408b4b3 100644
--- a/Tests/TurboFieldfareRepack/Core/Command/RepackCLITests.swift
+++ b/Tests/TurboFieldfareRepack/Core/Command/RepackCLITests.swift
@@ -77,4 +77,88 @@ struct RepackCLITests {
try? FileManager.default.removeItem(atPath: path)
}
}
+ @Test func visionActivationWithoutPreparedStateReportsAnError() throws {
+ let output = temporaryOutput("vision-missing-activation")
+ .replacingOccurrences(of: ".gturbo", with: ".vision.gturbo")
+ defer { clean(output) }
+ let result = try run([
+ "--activate-vision-install",
+ "--vision-output", output,
+ "--text-model", "/tmp/missing-text.gturbo",
+ ])
+
+ #expect(result.status == 1)
+ #expect(result.stderr.contains("no resumable install state exists"))
+ }
+
+ @Test func visionDiscardWithoutStateReportsAnError() throws {
+ let output = temporaryOutput("vision-missing-discard")
+ .replacingOccurrences(of: ".gturbo", with: ".vision.gturbo")
+ defer { clean(output) }
+ let result = try run([
+ "--discard-partial",
+ "--vision-output", output,
+ ])
+
+ #expect(result.status == 1)
+ #expect(result.stderr.contains("no resumable install state exists"))
+ }
+
+ @Test func visionRemovalWithoutInstalledPackReportsAnError() throws {
+ let output = temporaryOutput("vision-missing-remove")
+ .replacingOccurrences(of: ".gturbo", with: ".vision.gturbo")
+ defer { clean(output) }
+ let result = try run([
+ "--remove-vision-install",
+ "--vision-output", output,
+ ])
+
+ #expect(result.status == 1)
+ #expect(result.stderr.contains("no resumable install state exists"))
+ }
+
+ /// Discard is handled before the other vision modes, so accepting the
+ /// combination silently performed the discard and exited 0 without ever
+ /// removing, verifying or activating anything.
+ @Test func visionModesAreMutuallyExclusive() throws {
+ let output = temporaryOutput("vision-mode-clash")
+ .replacingOccurrences(of: ".gturbo", with: ".vision.gturbo")
+ defer { clean(output) }
+ for mode in ["--remove-vision-install", "--verify-vision-install",
+ "--activate-vision-install"] {
+ let result = try run(["--discard-partial", mode, "--vision-output", output])
+ #expect(result.status == 2, "\(mode) with --discard-partial was accepted")
+ #expect(result.stderr.contains("mutually exclusive"))
+ }
+ }
+
+ /// Verify and activate read an installed or prepared pack; a transfer flag
+ /// is a request they cannot honour, not a no-op.
+ @Test func verifyAndActivateRejectTransferFlags() throws {
+ let output = temporaryOutput("vision-flag-clash")
+ .replacingOccurrences(of: ".gturbo", with: ".vision.gturbo")
+ defer { clean(output) }
+ for mode in ["--verify-vision-install", "--activate-vision-install"] {
+ for flag in ["--overwrite", "--resume"] {
+ let result = try run([mode, "--vision-output", output,
+ "--text-model", "scratch/gemma4.gturbo", flag])
+ #expect(result.status == 2, "\(mode) accepted \(flag)")
+ }
+ }
+ }
+
+ @Test func remoteVisionResumeWithoutStateFailsBeforeNetwork() throws {
+ let output = temporaryOutput("vision-missing-resume")
+ .replacingOccurrences(of: ".gturbo", with: ".vision.gturbo")
+ defer { clean(output) }
+ let result = try run([
+ "--vision-output", output,
+ "--text-model", "/tmp/missing-text.gturbo",
+ "--resume",
+ ])
+
+ #expect(result.status == 1)
+ #expect(result.stderr.contains("no resumable install state exists"))
+ }
+
}
diff --git a/Tests/TurboFieldfareRepack/Core/Format/SafetensorsHostileHeaderTests.swift b/Tests/TurboFieldfareRepack/Core/Format/SafetensorsHostileHeaderTests.swift
new file mode 100644
index 00000000..f1e8b838
--- /dev/null
+++ b/Tests/TurboFieldfareRepack/Core/Format/SafetensorsHostileHeaderTests.swift
@@ -0,0 +1,116 @@
+import Foundation
+import Testing
+
+@testable import TurboFieldfareRepackCore
+
+/// Shard headers are attacker-shaped input: only `model.safetensors.index.json`
+/// is fingerprinted, so the per-shard JSON that drives every offset computation
+/// arrives unpinned. Each case here used to trap — an abort, not a failed
+/// download — because the arithmetic was unchecked.
+@Suite struct SafetensorsHostileHeaderTests {
+ private static func header(_ entries: [String: Any]) -> Data {
+ try! JSONSerialization.data(withJSONObject: entries, options: [.sortedKeys])
+ }
+
+ private static func parse(
+ _ entries: [String: Any],
+ fileSize: UInt64 = 1_024
+ ) throws -> Safetensors.Header {
+ try Safetensors.parseHeaderBytes(
+ path: "hostile.safetensors", fileSize: fileSize,
+ headerBytes: header(entries))
+ }
+
+ private static func entry(
+ dtype: String = "BF16",
+ shape: [Any],
+ offsets: [Any]
+ ) -> [String: Any] {
+ ["weight": ["dtype": dtype, "shape": shape, "data_offsets": offsets]]
+ }
+
+ @Test func dataOffsetsEndBeforeBeginIsRejected() throws {
+ #expect(throws: RepackError.self) {
+ _ = try Self.parse(Self.entry(shape: [2, 2], offsets: [512, 8]))
+ }
+ }
+
+ @Test func negativeOffsetsAreRejected() throws {
+ #expect(throws: RepackError.self) {
+ _ = try Self.parse(Self.entry(shape: [2, 2], offsets: [-1, 8]))
+ }
+ #expect(throws: RepackError.self) {
+ _ = try Self.parse(Self.entry(shape: [2, 2], offsets: [0, -8]))
+ }
+ }
+
+ @Test func negativeShapeExtentIsRejected() throws {
+ #expect(throws: RepackError.self) {
+ _ = try Self.parse(Self.entry(shape: [-2, 2], offsets: [0, 8]))
+ }
+ }
+
+ /// `payloadBase + begin` and `abs + size` both overflow here.
+ @Test func offsetsNearTheTopOfTheAddressSpaceAreRejected() throws {
+ let top = UInt64.max
+ #expect(throws: RepackError.self) {
+ _ = try Self.parse(Self.entry(shape: [2, 2], offsets: [top - 4, top]))
+ }
+ #expect(throws: RepackError.self) {
+ _ = try Self.parse(Self.entry(shape: [2, 2], offsets: [top, top]))
+ }
+ }
+
+ /// The shape product is folded before it is compared against the size, so a
+ /// header can make it overflow without any tensor being large.
+ @Test func shapeProductOverflowIsRejected() throws {
+ let big = UInt64(1) << 62
+ #expect(throws: RepackError.self) {
+ _ = try Self.parse(Self.entry(shape: [big, big, big], offsets: [0, 8]))
+ }
+ // Product fits, but multiplying by the element size does not.
+ #expect(throws: RepackError.self) {
+ _ = try Self.parse(Self.entry(shape: [UInt64.max], offsets: [0, 8]))
+ }
+ }
+
+ /// A file shorter than its own 8-byte length prefix underflowed the header
+ /// bound into ~2^64, which admitted any header size at all.
+ /// JSON has one number type, so a fractional or huge literal reaches the
+ /// parser as an ordinary number. Reading it as an integer truncates `1.5`
+ /// to 1 and saturates `1e30` at `UInt64.max`, either of which lets a header
+ /// describe a tensor other than the one it declares.
+ @Test func nonIntegerShapeOrOffsetIsRejected() throws {
+ #expect(throws: RepackError.self) {
+ _ = try Self.parse(Self.entry(shape: [1.5, 2], offsets: [0, 8]))
+ }
+ #expect(throws: RepackError.self) {
+ _ = try Self.parse(Self.entry(shape: [1e30, 2], offsets: [0, 8]))
+ }
+ #expect(throws: RepackError.self) {
+ _ = try Self.parse(Self.entry(shape: [2, 2], offsets: [0.5, 8]))
+ }
+ #expect(throws: RepackError.self) {
+ _ = try Self.parse(Self.entry(shape: [2, 2], offsets: [0, 1e30]))
+ }
+ }
+
+ @Test func fileShorterThanTheLengthPrefixIsRejected() throws {
+ for size: UInt64 in [0, 1, 7] {
+ #expect(throws: RepackError.self) {
+ _ = try Self.parse(Self.entry(shape: [2, 2], offsets: [0, 8]),
+ fileSize: size)
+ }
+ }
+ }
+
+ /// The checks must not have cost the ordinary case its acceptance.
+ @Test func wellFormedHeaderStillParses() throws {
+ let parsed = try Self.parse(Self.entry(shape: [2, 2], offsets: [0, 8]))
+ #expect(parsed.tensors.count == 1)
+ let tensor = try #require(parsed.tensors.first)
+ #expect(tensor.sizeBytes == 8)
+ #expect(tensor.shape == [2, 2])
+ #expect(tensor.absoluteOffset == parsed.payloadBaseOffset)
+ }
+}
diff --git a/Tests/TurboFieldfareRepack/Core/Planning/RangeCopyPlannerTests.swift b/Tests/TurboFieldfareRepack/Core/Planning/RangeCopyPlannerTests.swift
index 9200a955..2ed53350 100644
--- a/Tests/TurboFieldfareRepack/Core/Planning/RangeCopyPlannerTests.swift
+++ b/Tests/TurboFieldfareRepack/Core/Planning/RangeCopyPlannerTests.swift
@@ -118,4 +118,52 @@ struct RangeCopyPlannerTests {
fileSize: try Posix.fileSize(fd: fd, path: path),
headerBytes: headerData)
}
+ @Test func visionPlanIsBoundToTextManifestButNotAbsoluteOutputRoot() throws {
+ let firstRoot = temporaryRoot("vision-first")
+ let secondRoot = temporaryRoot("vision-second")
+ defer {
+ try? FileManager.default.removeItem(atPath: firstRoot)
+ try? FileManager.default.removeItem(atPath: secondRoot)
+ }
+ let source = SourceTensor(
+ name: "vision.weight",
+ shardPath: "model-00001.safetensors",
+ dtype: .bf16,
+ shape: [2],
+ absoluteOffset: 128,
+ sizeBytes: 4)
+ let plan = VisionPackPlan(
+ entries: [.init(
+ source: source,
+ executionPosition: 0,
+ fileOffset: 0,
+ quantSpec: nil,
+ groupSize: 64)],
+ weightsFileSize: 16_384,
+ sourcePayloadBytes: 4)
+ let binding = String(repeating: "a", count: 64)
+ let first = try RangeCopyPlanner.plan(
+ visionPackPlan: plan,
+ outputDirectory: firstRoot,
+ rangeChunkBytes: 4096,
+ textManifestSha256: binding)
+ let second = try RangeCopyPlanner.plan(
+ visionPackPlan: plan,
+ outputDirectory: secondRoot,
+ rangeChunkBytes: 4096,
+ textManifestSha256: binding)
+ let changedBinding = try RangeCopyPlanner.plan(
+ visionPackPlan: plan,
+ outputDirectory: secondRoot,
+ rangeChunkBytes: 4096,
+ textManifestSha256: String(repeating: "b", count: 64))
+
+ #expect(first.canonicalFingerprint == second.canonicalFingerprint)
+ #expect(first.canonicalFingerprint != changedBinding.canonicalFingerprint)
+ #expect(first.remoteBytesToDownload == 4)
+ #expect(first.expectedOutputs == [RemoteExpectedOutput(
+ relativePath: "vision_weights.bin",
+ size: 16_384)])
+ }
+
}
diff --git a/Tests/TurboFieldfareRepack/Core/Remote/VisionPackPrepareActivationTests.swift b/Tests/TurboFieldfareRepack/Core/Remote/VisionPackPrepareActivationTests.swift
new file mode 100644
index 00000000..fb3f7402
--- /dev/null
+++ b/Tests/TurboFieldfareRepack/Core/Remote/VisionPackPrepareActivationTests.swift
@@ -0,0 +1,523 @@
+import Darwin
+import Foundation
+import Testing
+@testable import TurboFieldfareFormat
+@testable import TurboFieldfareRepackCore
+
+// Nested inside RemotePayloadCopyTests so it inherits that suite's
+// serialization: FakeHFURLProtocol keeps its stub state in statics, and
+// .serialized only orders tests within one suite, so two top-level suites
+// sharing the stub raced and clobbered each other.
+extension RemotePayloadCopyTests {
+@Suite(.serialized)
+struct VisionPackPrepareActivationTests {
+ @Test func preparedPackWaitsForRuntimeThenActivatesWithoutDownload() throws {
+ let fixture = try makeFixture()
+ defer { fixture.remove() }
+
+ #expect(RemoteVisionPackInstaller.preparedInstallIsValid(
+ outputDirectory: fixture.output.path,
+ textModelDirectory: fixture.text.path,
+ verifyWeights: true))
+
+ let useDescriptor = try acquireSharedUseLock(fixture)
+ #expect(throws: RepackError.self) {
+ try activate(fixture)
+ }
+ #expect(FileManager.default.fileExists(atPath: fixture.paths.partialDirectory))
+ #expect(!FileManager.default.fileExists(atPath: fixture.output.path))
+ _ = flock(useDescriptor, LOCK_UN)
+
+ try activate(fixture)
+ #expect(FileManager.default.fileExists(atPath: fixture.output.path))
+ #expect(!FileManager.default.fileExists(atPath: fixture.paths.partialDirectory))
+ #expect(!FileManager.default.fileExists(atPath: fixture.paths.checkpointFile))
+
+ #expect(flock(useDescriptor, LOCK_SH | LOCK_NB) == 0)
+ _ = try VisionPackVerifier.verify(
+ directory: fixture.output,
+ textModelDirectory: fixture.text)
+ #expect(throws: RepackError.self) {
+ try RemoteVisionPackInstaller.removeInstalled(
+ outputDirectory: fixture.output.path)
+ }
+ #expect(FileManager.default.fileExists(atPath: fixture.output.path))
+ _ = flock(useDescriptor, LOCK_UN)
+ close(useDescriptor)
+
+ try RemoteVisionPackInstaller.removeInstalled(
+ outputDirectory: fixture.output.path)
+ #expect(!FileManager.default.fileExists(atPath: fixture.output.path))
+ #expect(FileManager.default.fileExists(atPath: fixture.text.path))
+ }
+
+ @Test(arguments: ["repo", "commit", "index"])
+ func activationRejectsStaleCheckpointSourceIdentity(field: String) throws {
+ let fixture = try makeFixture()
+ defer { fixture.remove() }
+ try fixture.writeCheckpoint(
+ resolvedCommit: field == "commit" ? String(repeating: "d", count: 40) : fixture.revision,
+ sourceIndexSHA256: field == "index" ? String(repeating: "e", count: 64) : fixture.sourceIndex)
+
+ #expect(throws: RepackError.self) {
+ if field == "repo" {
+ try RemoteVisionPackInstaller.activatePrepared(
+ outputDirectory: fixture.output.path,
+ textModelDirectory: fixture.text.path,
+ repoID: "fixture/other",
+ requestedRevision: fixture.requestedRevision)
+ } else {
+ try activate(fixture)
+ }
+ }
+ #expect(FileManager.default.fileExists(atPath: fixture.paths.partialDirectory))
+ #expect(!FileManager.default.fileExists(atPath: fixture.output.path))
+ }
+
+ @Test func corruptPayloadRequiresRepairInsteadOfActivationRetry() throws {
+ let fixture = try makeFixture()
+ defer { fixture.remove() }
+ let weightsPath = (fixture.paths.partialDirectory as NSString)
+ .appendingPathComponent(GTurboVisionFormatV1.weightsFile)
+ let descriptor = try Posix.openExistingRW(weightsPath)
+ defer { close(descriptor) }
+ var byte: UInt8 = 1
+ try withUnsafeBytes(of: &byte) {
+ try Posix.pwriteAll(
+ fd: descriptor,
+ path: weightsPath,
+ buf: $0.baseAddress!,
+ count: 1,
+ offset: 0)
+ }
+
+ #expect(RemoteVisionPackInstaller.preparedInstallIsValid(
+ outputDirectory: fixture.output.path,
+ textModelDirectory: fixture.text.path))
+ #expect(!RemoteVisionPackInstaller.preparedInstallIsValid(
+ outputDirectory: fixture.output.path,
+ textModelDirectory: fixture.text.path,
+ verifyWeights: true))
+ #expect(throws: RepackError.self) { try activate(fixture) }
+ #expect(FileManager.default.fileExists(atPath: fixture.paths.partialDirectory))
+ }
+
+ @Test(arguments: ["partial-path", "other-path", "other-manifest"])
+ func receiptBindingMismatchIsRejected(kind: String) throws {
+ let fixture = try makeFixture()
+ defer { fixture.remove() }
+ let receiptURL = URL(fileURLWithPath: fixture.paths.partialDirectory)
+ .appendingPathComponent(GTurboVisionFormatV1.receiptFile)
+ let original = try GTurboVisionReceiptCodec.decode(
+ Posix.readBoundedData(
+ receiptURL.path,
+ maximumBytes: GTurboVisionFormatV1.metadataMaxBytes))
+ let receipt = GTurboVisionReceiptV1(
+ manifestSha256: kind == "other-manifest"
+ ? String(repeating: "f", count: 64)
+ : original.manifestSha256,
+ companionDirectoryPath: kind == "partial-path"
+ ? fixture.paths.partialDirectory
+ : kind == "other-path"
+ ? fixture.output.path + ".other"
+ : original.companionDirectoryPath,
+ compatibleTextManifestSha256: original.compatibleTextManifestSha256,
+ sourceRepoID: original.sourceRepoID,
+ sourceRevision: original.sourceRevision,
+ verificationTimestamp: original.verificationTimestamp,
+ toolVersion: original.toolVersion,
+ files: original.files)
+ try GTurboVisionReceiptCodec.encode(receipt).write(to: receiptURL)
+
+ #expect(throws: RepackError.self) {
+ _ = try VisionPackVerifier.verify(
+ directory: URL(fileURLWithPath: fixture.paths.partialDirectory),
+ installedDirectory: fixture.output,
+ textModelDirectory: fixture.text)
+ }
+ }
+
+ @Test func changedTextManifestInvalidatesPreparedPack() throws {
+ let fixture = try makeFixture()
+ defer { fixture.remove() }
+ let manifestURL = fixture.text.appendingPathComponent("manifest.json")
+ var data = try Data(contentsOf: manifestURL)
+ data.append(0x20)
+ try data.write(to: manifestURL)
+
+ #expect(!RemoteVisionPackInstaller.preparedInstallIsValid(
+ outputDirectory: fixture.output.path,
+ textModelDirectory: fixture.text.path))
+ #expect(throws: RepackError.self) { try activate(fixture) }
+ #expect(FileManager.default.fileExists(atPath: fixture.paths.partialDirectory))
+ }
+
+ @Test func rerunFinishesInterruptedPostRenameCommit() throws {
+ let fixture = try makeFixture()
+ defer { fixture.remove() }
+ try Posix.rename(
+ from: fixture.paths.partialDirectory,
+ to: fixture.paths.finalDirectory)
+
+ try activate(fixture)
+
+ #expect(FileManager.default.fileExists(atPath: fixture.output.path))
+ #expect(!FileManager.default.fileExists(atPath: fixture.paths.checkpointFile))
+ _ = try VisionPackVerifier.verify(
+ directory: fixture.output,
+ textModelDirectory: fixture.text)
+ }
+
+ @Test func removalClearsInstalledPackAndSavedRepairButNotText() throws {
+ let fixture = try makeFixture()
+ defer { fixture.remove() }
+ try FileManager.default.copyItem(
+ atPath: fixture.paths.partialDirectory,
+ toPath: fixture.paths.finalDirectory)
+
+ try RemoteVisionPackInstaller.removeInstalled(
+ outputDirectory: fixture.output.path)
+
+ #expect(!FileManager.default.fileExists(atPath: fixture.paths.finalDirectory))
+ #expect(!FileManager.default.fileExists(atPath: fixture.paths.partialDirectory))
+ #expect(!FileManager.default.fileExists(atPath: fixture.paths.checkpointFile))
+ #expect(FileManager.default.fileExists(atPath: fixture.text.path))
+ }
+
+ @Test(arguments: ["partial-only", "checkpoint-only"])
+ func inconsistentSavedStateFailsBeforeNetwork(kind: String) async throws {
+ let parent = try temporaryParent("vision-inconsistent")
+ defer { try? FileManager.default.removeItem(at: parent) }
+ resetFakeHF()
+ let output = parent.appendingPathComponent("model.vision.gturbo")
+ let paths = try RemoteInstallPaths(outputDirectory: output.path)
+ if kind != "checkpoint-only" {
+ try FileManager.default.createDirectory(
+ atPath: paths.partialDirectory,
+ withIntermediateDirectories: true)
+ }
+ if kind != "partial-only" {
+ try RemoteInstallCheckpoint(
+ repoID: "fixture/model",
+ requestedRevision: "pinned",
+ resolvedCommit: String(repeating: "a", count: 40),
+ sourceIndexSHA256: String(repeating: "b", count: 64),
+ planFingerprint: String(repeating: "c", count: 64),
+ totalSourceBytes: 1).write(
+ to: paths.checkpointFile,
+ parentDirectory: paths.parentDirectory)
+ }
+ let installer = RemoteVisionPackInstaller(options: .init(
+ repoID: "fixture/model",
+ revision: "pinned",
+ textModelDirectory: parent.appendingPathComponent("text.gturbo").path,
+ outputDirectory: output.path,
+ minFreeReserveBytes: 0,
+ overwrite: true,
+ resume: true,
+ downloadSession: fakeHFSession(),
+ baseURL: URL(string: "https://hf.test")!))
+
+ await #expect(throws: RepackError.self) {
+ _ = try await installer.prepare()
+ }
+ #expect(FakeHFURLProtocol.requestCounts.isEmpty)
+ }
+
+ /// The partial directory is created before the checkpoint that identifies
+ /// its source, so a crash in that window leaves a directory carrying no
+ /// recoverable progress. Reporting it as corrupt state blocked even a fresh
+ /// install; it has to be reclaimed instead.
+ @Test func partialDirectoryWithoutACheckpointIsReclaimed() async throws {
+ let parent = try temporaryParent("vision-orphan-partial")
+ defer { try? FileManager.default.removeItem(at: parent) }
+ resetFakeHF()
+ let output = parent.appendingPathComponent("model.vision.gturbo")
+ let paths = try RemoteInstallPaths(outputDirectory: output.path)
+ try FileManager.default.createDirectory(
+ atPath: paths.partialDirectory, withIntermediateDirectories: true)
+ try Data("half a download".utf8).write(to: URL(fileURLWithPath:
+ (paths.partialDirectory as NSString).appendingPathComponent(".range.tmp")))
+
+ let installer = RemoteVisionPackInstaller(options: .init(
+ repoID: "fixture/model",
+ revision: "pinned",
+ textModelDirectory: parent.appendingPathComponent("text.gturbo").path,
+ outputDirectory: output.path,
+ minFreeReserveBytes: 0,
+ overwrite: true,
+ resume: false,
+ downloadSession: fakeHFSession(),
+ baseURL: URL(string: "https://hf.test")!))
+
+ // It still fails — there is no text model to bind to — but it must get
+ // past the saved-state check rather than stopping at it.
+ do {
+ _ = try await installer.prepare()
+ Issue.record("the fixture has no text model, so this cannot succeed")
+ } catch let error as RepackError {
+ if case .installStateCorrupt = error {
+ Issue.record("orphaned partial directory still blocks a fresh install")
+ }
+ }
+ }
+
+ @Test func corruptCheckpointFailsWithoutMutatingPreparedPack() throws {
+ let fixture = try makeFixture()
+ defer { fixture.remove() }
+ try Data("not-json".utf8).write(
+ to: URL(fileURLWithPath: fixture.paths.checkpointFile))
+
+ #expect(throws: RepackError.self) { try activate(fixture) }
+ #expect(FileManager.default.fileExists(atPath: fixture.paths.partialDirectory))
+ #expect(!FileManager.default.fileExists(atPath: fixture.output.path))
+ }
+
+ /// The partial directory doubles as download scratch, and the verifier
+ /// accepts the four pack entries and nothing else. A crash between the last
+ /// write and the installer's own cleanup therefore left a `.range.tmp` or
+ /// an interrupted `atomicWrite`'s `.tmp` beside them, and a complete 1.5 GB
+ /// download became permanently unactivatable.
+ @Test(arguments: [".range.tmp", "manifest.json.tmp", "turbofieldfare-range-x.tmp"])
+ func activationReclaimsLeftoverDownloadScratch(name: String) throws {
+ let fixture = try makeFixture()
+ defer { fixture.remove() }
+ let stray = (fixture.paths.partialDirectory as NSString)
+ .appendingPathComponent(name)
+ try Data("scratch".utf8).write(to: URL(fileURLWithPath: stray))
+
+ try activate(fixture)
+ #expect(FileManager.default.fileExists(atPath: fixture.output.path))
+ #expect(!FileManager.default.fileExists(atPath: stray))
+ #expect(!FileManager.default.fileExists(atPath: fixture.paths.partialDirectory))
+ }
+
+ /// The metadata cache is a directory, not a file, and is re-fetched on
+ /// every run, so it is scratch too.
+ @Test func activationReclaimsTheMetadataCacheDirectory() throws {
+ let fixture = try makeFixture()
+ defer { fixture.remove() }
+ try FileManager.default.createDirectory(
+ atPath: fixture.paths.metadataDirectory, withIntermediateDirectories: true)
+ try Data("{}".utf8).write(to: URL(fileURLWithPath:
+ (fixture.paths.metadataDirectory as NSString)
+ .appendingPathComponent("config.json")))
+
+ try activate(fixture)
+ #expect(FileManager.default.fileExists(atPath: fixture.output.path))
+ }
+
+ /// Reclaiming must not touch the pack itself.
+ @Test func reclaimingScratchKeepsEveryPackEntry() throws {
+ let fixture = try makeFixture()
+ defer { fixture.remove() }
+ let stray = (fixture.paths.partialDirectory as NSString)
+ .appendingPathComponent(".range.tmp")
+ try Data("scratch".utf8).write(to: URL(fileURLWithPath: stray))
+
+ let reclaimed = try RemoteVisionPackInstaller.reclaimPartialScratch(
+ directory: fixture.paths.partialDirectory)
+ #expect(reclaimed == [".range.tmp"])
+ let remaining = Set(try FileManager.default.contentsOfDirectory(
+ atPath: fixture.paths.partialDirectory))
+ #expect(remaining == RemoteVisionPackInstaller.packEntries)
+ }
+
+ /// Refusing an install over a pack that is already there used to end the
+ /// sentence at "already exists", which is the state a failed repair leaves
+ /// people in - with a saved partial sitting right next to it and no way
+ /// forward printed.
+ @Test func refusingAnExistingPackSaysHowToProceed() async throws {
+ let fixture = try makeFixture()
+ defer { fixture.remove() }
+ try activate(fixture)
+ #expect(FileManager.default.fileExists(atPath: fixture.output.path))
+
+ do {
+ _ = try await RemoteVisionPackInstaller(
+ options: installOptions(fixture, overwrite: false)).prepare()
+ Issue.record("expected the existing pack to refuse the install")
+ } catch let error as RepackError {
+ let message = error.description
+ #expect(message.contains("--overwrite"),
+ "the refusal has to name the flag that continues: \(message)")
+ }
+ }
+
+ /// The lock that decides activation was only taken at the end, so a loaded
+ /// model was discovered after the whole 1.09 GB transfer. Probing it first
+ /// turns that into a refusal before the first byte.
+ @Test func aLoadedModelIsFoundBeforeTheTransferNotAfterIt() async throws {
+ let fixture = try makeFixture()
+ defer { fixture.remove() }
+ try activate(fixture)
+ let useDescriptor = try acquireSharedUseLock(fixture)
+ defer {
+ _ = flock(useDescriptor, LOCK_UN)
+ close(useDescriptor)
+ }
+
+ do {
+ _ = try await RemoteVisionPackInstaller(
+ options: installOptions(fixture, overwrite: true)).prepare()
+ Issue.record("expected the held use lease to refuse the install")
+ } catch let error as RepackError {
+ guard case .installBusy = error else {
+ Issue.record("expected installBusy, got \(error)")
+ return
+ }
+ #expect(error.description.contains("loaded model"))
+ }
+ // Nothing was downloaded: the pack on disk is untouched and no partial
+ // was created beside it.
+ #expect(!FileManager.default.fileExists(atPath: fixture.paths.partialDirectory))
+ #expect(FileManager.default.fileExists(atPath: fixture.output.path))
+ }
+
+ private func installOptions(
+ _ fixture: VisionFixture, overwrite: Bool
+ ) -> RemoteVisionPackInstallOptions {
+ RemoteVisionPackInstallOptions(
+ repoID: fixture.repoID,
+ revision: fixture.requestedRevision,
+ textModelDirectory: fixture.text.path,
+ outputDirectory: fixture.output.path,
+ overwrite: overwrite)
+ }
+
+ private func activate(_ fixture: VisionFixture) throws {
+ try RemoteVisionPackInstaller.activatePrepared(
+ outputDirectory: fixture.output.path,
+ textModelDirectory: fixture.text.path,
+ repoID: fixture.repoID,
+ requestedRevision: fixture.requestedRevision)
+ }
+
+ private func acquireSharedUseLock(_ fixture: VisionFixture) throws -> Int32 {
+ let path = fixture.parent.appendingPathComponent(
+ ".model.vision.gturbo.use.lock").path
+ let descriptor = open(path, O_RDWR | O_CREAT | O_NOFOLLOW | O_CLOEXEC, 0o600)
+ guard descriptor >= 0, flock(descriptor, LOCK_SH | LOCK_NB) == 0 else {
+ if descriptor >= 0 { close(descriptor) }
+ throw RepackError.fileOpenFailed(path: path, errno: errno)
+ }
+ return descriptor
+ }
+
+ private func makeFixture() throws -> VisionFixture {
+ let parent = try temporaryParent("vision-prepare-activate")
+ let text = parent.appendingPathComponent("model.gturbo", isDirectory: true)
+ let output = parent.appendingPathComponent("model.vision.gturbo", isDirectory: true)
+ let paths = try RemoteInstallPaths(outputDirectory: output.path)
+ try FileManager.default.createDirectory(
+ atPath: paths.partialDirectory,
+ withIntermediateDirectories: true)
+
+ let textManifest = GTurboManifestV1(
+ flags: [:], modelID: "fixture/text", sourceSnapshotHash: "text-snapshot",
+ arch: GTurboManifestArchV1(
+ hiddenSize: 1, ffnIntermediate: 1, moeIntermediateSize: 1,
+ numHeads: 1, numKVHeads: 1, numFullKVHeads: 1,
+ headDim: 1, fullHeadDim: 1, vocabSize: 1,
+ slidingWindow: 1, finalLogitSoftcap: 1,
+ ropeTheta: 1, fullRopeTheta: 1, partialRotaryFactor: 1,
+ numLayers: 1, numExperts: 1, topKExperts: 1,
+ tieWordEmbeddings: true, attentionKEqV: true,
+ hiddenActivation: "gelu", fullAttentionLayerMask: [0]),
+ quant: nil, files: [:], expertsPerLayer: 1,
+ numLayers: 1, expertStride: 16_384,
+ bitWidthOverridesHonored: nil)
+ let textManifestData = try GTurboManifestCodec.encode(textManifest)
+ try FileManager.default.createDirectory(at: text, withIntermediateDirectories: false)
+ try textManifestData.write(to: text.appendingPathComponent("manifest.json"))
+ let textSHA = hash(textManifestData)
+
+ let weights = Data(repeating: 0, count: 16_384)
+ let processor = Data("{}".utf8)
+ let files = [
+ GTurboVisionFormatV1.weightsFile: GTurboManifestFileV1(
+ size: UInt64(weights.count), sha256: hash(weights)),
+ GTurboVisionFormatV1.processorFile: GTurboManifestFileV1(
+ size: UInt64(processor.count), sha256: hash(processor)),
+ ]
+ let revision = String(repeating: "a", count: 40)
+ let sourceIndex = String(repeating: "b", count: 64)
+ let manifest = GTurboVisionManifestV1(
+ modelID: "fixture/model", sourceRevision: revision,
+ sourceIndexSha256: sourceIndex,
+ processorConfigSha256: hash(processor),
+ compatibleTextSourceSnapshotHash: "text-snapshot",
+ compatibleTextManifestSha256: textSHA,
+ files: files,
+ tensors: [.init(
+ name: "vision.weight", executionPosition: 0,
+ offset: 0, size: 2, shape: [1], dtype: .bf16)])
+ let manifestData = try GTurboVisionManifestCodec.encode(manifest)
+ let manifestSHA = hash(manifestData)
+ let receipt = GTurboVisionReceiptV1(
+ manifestSha256: manifestSHA,
+ companionDirectoryPath: output.standardizedFileURL.path,
+ compatibleTextManifestSha256: textSHA,
+ sourceRepoID: "fixture/model", sourceRevision: revision,
+ verificationTimestamp: "fixture", toolVersion: "fixture",
+ files: files.merging([
+ GTurboVisionFormatV1.manifestFile: GTurboManifestFileV1(
+ size: UInt64(manifestData.count), sha256: manifestSHA)
+ ]) { _, new in new })
+ let partial = URL(fileURLWithPath: paths.partialDirectory)
+ try weights.write(to: partial.appendingPathComponent(GTurboVisionFormatV1.weightsFile))
+ try processor.write(to: partial.appendingPathComponent(GTurboVisionFormatV1.processorFile))
+ try manifestData.write(to: partial.appendingPathComponent(GTurboVisionFormatV1.manifestFile))
+ try GTurboVisionReceiptCodec.encode(receipt).write(
+ to: partial.appendingPathComponent(GTurboVisionFormatV1.receiptFile))
+ let fixture = VisionFixture(
+ parent: parent, text: text, output: output, paths: paths,
+ repoID: "fixture/model", requestedRevision: "pinned",
+ revision: revision, sourceIndex: sourceIndex)
+ try fixture.writeCheckpoint(
+ resolvedCommit: revision,
+ sourceIndexSHA256: sourceIndex)
+ return fixture
+ }
+
+ private func temporaryParent(_ tag: String) throws -> URL {
+ let parent = FileManager.default.temporaryDirectory
+ .appendingPathComponent("\(tag)-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(at: parent, withIntermediateDirectories: false)
+ return parent
+ }
+
+ private func hash(_ data: Data) -> String {
+ var stream = Sha256Stream()
+ data.withUnsafeBytes { stream.update($0) }
+ return stream.finalizeHexString()
+ }
+}
+}
+
+private struct VisionFixture {
+ let parent: URL
+ let text: URL
+ let output: URL
+ let paths: RemoteInstallPaths
+ let repoID: String
+ let requestedRevision: String
+ let revision: String
+ let sourceIndex: String
+
+ func writeCheckpoint(resolvedCommit: String, sourceIndexSHA256: String) throws {
+ try RemoteInstallCheckpoint(
+ repoID: repoID,
+ requestedRevision: requestedRevision,
+ resolvedCommit: resolvedCommit,
+ sourceIndexSHA256: sourceIndexSHA256,
+ planFingerprint: String(repeating: "c", count: 64),
+ totalSourceBytes: 2).write(
+ to: paths.checkpointFile,
+ parentDirectory: paths.parentDirectory)
+ }
+
+ func remove() {
+ try? FileManager.default.removeItem(at: parent)
+ }
+}
diff --git a/Tests/TurboFieldfareRepack/Core/System/VisionPackMutationLockTests.swift b/Tests/TurboFieldfareRepack/Core/System/VisionPackMutationLockTests.swift
new file mode 100644
index 00000000..94569b3c
--- /dev/null
+++ b/Tests/TurboFieldfareRepack/Core/System/VisionPackMutationLockTests.swift
@@ -0,0 +1,107 @@
+import Darwin
+import Foundation
+import Testing
+@testable import TurboFieldfareRepackCore
+
+@Suite struct VisionPackMutationLockTests {
+ @Test func mutationFailsWhileRuntimeHoldsSharedLease() throws {
+ let parent = FileManager.default.temporaryDirectory
+ .appendingPathComponent("vision-use-lock-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(
+ at: parent,
+ withIntermediateDirectories: false)
+ defer { try? FileManager.default.removeItem(at: parent) }
+ let output = parent.appendingPathComponent("model.vision.gturbo")
+ let lockPath = parent.appendingPathComponent(
+ ".model.vision.gturbo.use.lock").path
+ let descriptor = open(
+ lockPath,
+ O_RDWR | O_CREAT | O_NOFOLLOW | O_CLOEXEC,
+ 0o600)
+ #expect(descriptor >= 0)
+ defer {
+ _ = flock(descriptor, LOCK_UN)
+ close(descriptor)
+ }
+ #expect(flock(descriptor, LOCK_SH | LOCK_NB) == 0)
+
+ do {
+ _ = try VisionPackMutationLock.acquire(
+ outputDirectory: output.path)
+ Issue.record("exclusive mutation lock ignored the shared runtime lease")
+ } catch let error as RepackError {
+ guard case .installBusy = error else {
+ Issue.record("expected installBusy, got \(error)")
+ return
+ }
+ }
+ }
+
+ /// The message a user actually sees when a loaded model blocks a remove.
+ /// It used to say "another installer holds ...", so the one case people hit
+ /// sent them looking for a second install that does not exist.
+ @Test func aBlockedMutationNamesTheLoadedModelNotJustAnInstaller() throws {
+ let parent = FileManager.default.temporaryDirectory
+ .appendingPathComponent("vision-busy-text-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(
+ at: parent, withIntermediateDirectories: false)
+ defer { try? FileManager.default.removeItem(at: parent) }
+ let output = parent.appendingPathComponent("model.vision.gturbo")
+ let lockPath = parent.appendingPathComponent(
+ ".model.vision.gturbo.use.lock").path
+ let descriptor = open(
+ lockPath, O_RDWR | O_CREAT | O_NOFOLLOW | O_CLOEXEC, 0o600)
+ #expect(descriptor >= 0)
+ defer {
+ _ = flock(descriptor, LOCK_UN)
+ close(descriptor)
+ }
+ #expect(flock(descriptor, LOCK_SH | LOCK_NB) == 0)
+
+ do {
+ _ = try VisionPackMutationLock.acquire(outputDirectory: output.path)
+ Issue.record("expected the shared lease to block the mutation")
+ } catch let error as RepackError {
+ let message = error.description
+ #expect(message.contains("loaded model"),
+ "the message must name the holder people actually hit: \(message)")
+ #expect(message.contains("unload the model"),
+ "the message must say what to do: \(message)")
+ }
+ }
+
+ /// The installer's own lock has no reader side, so it keeps the plain
+ /// wording; widening every busy message would have been a lie in that case.
+ @Test func theInstallerLockKeepsItsOwnWording() {
+ #expect(RepackError.installBusy(path: "/tmp/x.install.lock").description
+ == "another installer holds /tmp/x.install.lock")
+ }
+
+ @Test func transactionLockCanCoexistWithRuntimeLeaseWithoutDeadlock() throws {
+ let parent = FileManager.default.temporaryDirectory
+ .appendingPathComponent("vision-lock-order-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(
+ at: parent,
+ withIntermediateDirectories: false)
+ defer { try? FileManager.default.removeItem(at: parent) }
+ let output = parent.appendingPathComponent("model.vision.gturbo")
+ let lockPath = parent.appendingPathComponent(
+ ".model.vision.gturbo.use.lock").path
+ let descriptor = open(
+ lockPath,
+ O_RDWR | O_CREAT | O_NOFOLLOW | O_CLOEXEC,
+ 0o600)
+ #expect(descriptor >= 0)
+ defer {
+ _ = flock(descriptor, LOCK_UN)
+ close(descriptor)
+ }
+ #expect(flock(descriptor, LOCK_SH | LOCK_NB) == 0)
+
+ let transaction = try InstallLock.acquire(outputDirectory: output.path)
+ #expect(throws: RepackError.self) {
+ _ = try VisionPackMutationLock.acquire(outputDirectory: output.path)
+ }
+ withExtendedLifetime(transaction) {}
+ }
+}
diff --git a/Tests/TurboFieldfareRepack/Core/Workflow/InstallProgressReporterTests.swift b/Tests/TurboFieldfareRepack/Core/Workflow/InstallProgressReporterTests.swift
new file mode 100644
index 00000000..4d122a3f
--- /dev/null
+++ b/Tests/TurboFieldfareRepack/Core/Workflow/InstallProgressReporterTests.swift
@@ -0,0 +1,66 @@
+import Foundation
+import Testing
+@testable import TurboFieldfareRepackCore
+
+/// The installer printed nothing between the command and "Installed" for a
+/// 14.6 GB transfer. Both installers already took a progress closure and
+/// `main.swift` passed none, so the data existed and never reached anyone.
+@Suite struct InstallProgressReporterTests {
+ @Test func everyPhaseProducesALine() {
+ let cases: [ModelInstallProgress] = [
+ .downloadingMetadata,
+ .planning(downloadBytes: 1_500_000_000, outputBytes: 1_200_000_000),
+ .reservingOutput(bytes: 1_200_000_000),
+ .copyingPayload(reusedBytes: 0, downloadedThisRunBytes: 600_000_000,
+ totalBytes: 1_200_000_000),
+ .hashingOutput("vision_weights.bin"),
+ .finalizing,
+ ]
+ for progress in cases {
+ #expect(InstallProgressReporter.line(for: progress) != nil,
+ "\(progress) reported nothing")
+ }
+ }
+
+ @Test func theCopyLineCarriesBytesAndPercent() {
+ let line = InstallProgressReporter.line(for: .copyingPayload(
+ reusedBytes: 0, downloadedThisRunBytes: 600_000_000,
+ totalBytes: 1_200_000_000))
+ #expect(line == "[install] 572.2 MiB of 1.1 GiB (50%)")
+ }
+
+ /// A resumed install has bytes it did not fetch, and saying so is the
+ /// difference between "stalled" and "already had half of it".
+ @Test func aResumedCopySaysWhatWasAlreadyOnDisk() {
+ let line = InstallProgressReporter.line(for: .copyingPayload(
+ reusedBytes: 400_000_000, downloadedThisRunBytes: 200_000_000,
+ totalBytes: 1_200_000_000))
+ #expect(line?.contains("already on disk") == true)
+ }
+
+ /// Rate limited within a phase, never across one: a 14.6 GB copy must not
+ /// scroll, and a phase change must not be swallowed by the throttle.
+ @Test func linesAreThrottledPerPhaseNotGlobally() {
+ final class Sink: @unchecked Sendable {
+ var lines: [String] = []
+ }
+ let sink = Sink()
+ let reporter = InstallProgressReporter(
+ minimumInterval: 2, write: { sink.lines.append($0) })
+ reporter.report(.copyingPayload(reusedBytes: 0, downloadedThisRunBytes: 1,
+ totalBytes: 100), now: 0)
+ reporter.report(.copyingPayload(reusedBytes: 0, downloadedThisRunBytes: 2,
+ totalBytes: 100), now: 0.5)
+ #expect(sink.lines.count == 1, "the copy counter was not throttled")
+ reporter.report(.finalizing, now: 0.6)
+ #expect(sink.lines.count == 2, "a phase change was throttled away")
+ reporter.report(.copyingPayload(reusedBytes: 0, downloadedThisRunBytes: 3,
+ totalBytes: 100), now: 3.0)
+ #expect(sink.lines.count == 3)
+ }
+
+ @Test func byteFormattingStaysReadable() {
+ #expect(InstallProgressReporter.bytes(512) == "512 B")
+ #expect(InstallProgressReporter.bytes(1_144_373_248) == "1.1 GiB")
+ }
+}
diff --git a/Tests/TurboFieldfareServer/HTTPServerTests.swift b/Tests/TurboFieldfareServer/HTTPServerTests.swift
index 379eddac..08f6d761 100644
--- a/Tests/TurboFieldfareServer/HTTPServerTests.swift
+++ b/Tests/TurboFieldfareServer/HTTPServerTests.swift
@@ -868,6 +868,35 @@ struct HTTPServerTests {
#expect(await server.acceptedConnectionCount == 0)
try await server.shutdown()
}
+ @Test func imageRequestLargerThanLegacyOneMiBLimitStreamsToBackend() async throws {
+ let server = TurboFieldfareHTTPServer(
+ modelID: "test-model",
+ queueLimit: 1,
+ backend: ScriptedServerBackend(),
+ visionCapability: "ready")
+ let channel = try await server.start(port: 0)
+ let port = try #require(channel.localAddress?.port)
+
+ let encoded = Data(repeating: 0x5a, count: 900_000).base64EncodedString()
+ var request = URLRequest(
+ url: URL(string: "http://127.0.0.1:\(port)/v1/chat/completions")!)
+ request.httpMethod = "POST"
+ request.setValue("application/json", forHTTPHeaderField: "content-type")
+ request.httpBody = Data("""
+ {"model":"test-model","messages":[{"role":"user","content":[
+ {"type":"image_url","image_url":{"url":"data:image/png;base64,\(encoded)"}},
+ {"type":"text","text":"describe"}
+ ]}]}
+ """.utf8)
+ #expect(try #require(request.httpBody?.count) > 1_048_576)
+
+ let (data, response) = try await URLSession.shared.data(for: request)
+ #expect((response as? HTTPURLResponse)?.statusCode == 200)
+ #expect(String(decoding: data, as: UTF8.self).contains(#""content":"hello""#))
+
+ try await server.shutdown()
+ }
+
}
private enum RawSocketError: Error {
@@ -875,7 +904,7 @@ private enum RawSocketError: Error {
case timeout
}
-private func connectedSocket(port: Int) throws -> Int32 {
+func connectedSocket(port: Int) throws -> Int32 {
let descriptor = Darwin.socket(AF_INET, SOCK_STREAM, 0)
guard descriptor >= 0 else {
throw RawSocketError.systemCall("socket", errno)
@@ -898,7 +927,7 @@ private func connectedSocket(port: Int) throws -> Int32 {
return descriptor
}
-private func writeAll(socket: Int32, text: String) throws {
+func writeAll(socket: Int32, text: String) throws {
let bytes = Array(text.utf8)
var written = 0
while written < bytes.count {
@@ -913,7 +942,7 @@ private func writeAll(socket: Int32, text: String) throws {
}
}
-private func httpRequest(port: Int, body: String, connection: String) -> String {
+func httpRequest(port: Int, body: String, connection: String) -> String {
"POST /v1/chat/completions HTTP/1.1\r\n"
+ "Host: 127.0.0.1:\(port)\r\n"
+ "Content-Type: application/json\r\n"
@@ -932,7 +961,7 @@ private func abortSocket(_ socket: Int32) {
Darwin.close(socket)
}
-private func readAvailable(socket: Int32, timeoutMilliseconds: Int32) throws -> String {
+func readAvailable(socket: Int32, timeoutMilliseconds: Int32) throws -> String {
var result: [UInt8] = []
var descriptor = pollfd(fd: socket, events: Int16(POLLIN), revents: 0)
while Darwin.poll(&descriptor, 1, timeoutMilliseconds) > 0 {
@@ -948,7 +977,7 @@ private func readAvailable(socket: Int32, timeoutMilliseconds: Int32) throws ->
return String(decoding: result, as: UTF8.self)
}
-private func readUntil(
+func readUntil(
socket: Int32,
timeoutMilliseconds: Int32,
condition: (String) -> Bool
diff --git a/Tests/TurboFieldfareServer/OpenAIValidationTests.swift b/Tests/TurboFieldfareServer/OpenAIValidationTests.swift
index 9db9560a..d46c11ef 100644
--- a/Tests/TurboFieldfareServer/OpenAIValidationTests.swift
+++ b/Tests/TurboFieldfareServer/OpenAIValidationTests.swift
@@ -756,7 +756,7 @@ struct ServerArgumentTests {
["--expert-cache-slots", "12"],
["--expert-cache-policy", "mru"],
["--prefill", "maybe"],
- ["--prefill-chunk-tokens", "256"],
+ ["--prefill-chunk-tokens", "512"],
["--rdadvise", "eager"],
])
func rejectsUnsupportedRuntimeValues(flag: [String]) throws {
@@ -764,4 +764,109 @@ struct ServerArgumentTests {
try ServerArguments.parse(["--model", "model.gturbo"] + flag)
}
}
+ @Test func imageDataURLPreservesOrderedMultimodalParts() throws {
+ let dataURL = "data:image/png;base64,iVBORw0KGgo="
+ let data = Data(#"""
+ {"model":"m","messages":[{"role":"user","content":[
+ {"type":"text","text":"before"},
+ {"type":"image_url","image_url":{"url":"\#(dataURL)","detail":"auto"}},
+ {"type":"text","text":"after"}
+ ]}]}
+ """#.utf8)
+ let request = try JSONDecoder().decode(OpenAIChatRequest.self, from: data)
+ let validated = try OpenAIRequestValidator.validate(request, modelID: "m")
+ let message = try #require(validated.multimodalMessages?.first)
+ #expect(message.content.count == 3)
+ #expect(validated.imageFiles.count == 1)
+ guard case .text("before") = message.content[0],
+ case .image = message.content[1],
+ case .text("after") = message.content[2] else {
+ Issue.record("content part order changed")
+ return
+ }
+ }
+
+ @Test func imageIdentitiesAlignWithMessagesAndPreserveOrder() throws {
+ let a = "data:image/png;base64,iVBORw0KGgo="
+ let b = "data:image/png;base64,iVBORw0KGgoAAAA="
+ let json = #"""
+ {"model":"m","messages":[
+ {"role":"user","content":[
+ {"type":"image_url","image_url":{"url":"\#(a)"}},
+ {"type":"image_url","image_url":{"url":"\#(b)"}},
+ {"type":"text","text":"compare"}]},
+ {"role":"assistant","content":"ok"},
+ {"role":"user","content":"and now"}
+ ]}
+ """#
+ let request = try JSONDecoder().decode(
+ OpenAIChatRequest.self, from: Data(json.utf8))
+ let validated = try OpenAIRequestValidator.validate(request, modelID: "m")
+ #expect(validated.imageIdentities.count == validated.messages.count)
+ #expect(validated.imageIdentities[0].count == 2)
+ #expect(validated.imageIdentities[1].isEmpty)
+ #expect(validated.imageIdentities[2].isEmpty)
+ #expect(validated.imageIdentities[0][0] != validated.imageIdentities[0][1])
+
+ // The same bytes must hash the same across separate requests, which is
+ // what lets a later turn recognise an earlier image.
+ let again = try OpenAIRequestValidator.validate(
+ try JSONDecoder().decode(OpenAIChatRequest.self, from: Data(json.utf8)),
+ modelID: "m")
+ #expect(again.imageIdentities == validated.imageIdentities)
+ #expect(again.imageFiles.keys.sorted(by: { $0.uuidString < $1.uuidString })
+ != validated.imageFiles.keys.sorted(by: { $0.uuidString < $1.uuidString }))
+ }
+
+ @Test func imageValidationRejectsUnsupportedRoleDetailAndScheme() throws {
+ for content in [
+ #"{"role":"assistant","content":[{"type":"image_url","image_url":{"url":"data:image/png;base64,iVBORw0KGgo="}}]}"#,
+ #"{"role":"user","content":[{"type":"image_url","image_url":{"url":"data:image/png;base64,iVBORw0KGgo=","detail":"high"}}]}"#,
+ #"{"role":"user","content":[{"type":"image_url","image_url":{"url":"https://example.com/image.png"}}]}"#,
+ ] {
+ let data = Data("{\"model\":\"m\",\"messages\":[\(content)]}".utf8)
+ let request = try JSONDecoder().decode(OpenAIChatRequest.self, from: data)
+ #expect(throws: ServerRequestError.self) {
+ try OpenAIRequestValidator.validate(request, modelID: "m")
+ }
+ }
+ }
+
+ @Test func manyImagesValidateAndKeepPositionalIdentity() throws {
+ func conversation(imagesPerTurn: Int, turns: Int) throws -> OpenAIChatRequest {
+ var messages: [String] = []
+ var seed = 0
+ for turn in 0..<turns {
+ var parts: [String] = []
+ for _ in 0..<imagesPerTurn {
+ seed += 1
+ let payload = String(repeating: "A", count: 4 * seed)
+ parts.append(
+ #"{"type":"image_url","image_url":{"url":"data:image/png;base64,\#(payload)"}}"#)
+ }
+ parts.append(#"{"type":"text","text":"turn \#(turn)"}"#)
+ messages.append("{\"role\":\"user\",\"content\":[\(parts.joined(separator: ","))]}")
+ messages.append("{\"role\":\"assistant\",\"content\":\"ok \(turn)\"}")
+ }
+ messages.removeLast()
+ let json = "{\"model\":\"m\",\"messages\":[\(messages.joined(separator: ","))]}"
+ return try JSONDecoder().decode(
+ OpenAIChatRequest.self, from: Data(json.utf8))
+ }
+
+ // Ten images across ten turns, each identified positionally.
+ let spread = try OpenAIRequestValidator.validate(
+ conversation(imagesPerTurn: 1, turns: 10), modelID: "m")
+ #expect(spread.imageFiles.count == 10)
+ #expect(spread.imageIdentities.count == spread.messages.count)
+ #expect(spread.imageIdentities.filter { !$0.isEmpty }.count == 10)
+
+ // And many in a single message.
+ let dense = try OpenAIRequestValidator.validate(
+ conversation(imagesPerTurn: 8, turns: 1), modelID: "m")
+ #expect(dense.imageFiles.count == 8)
+ #expect(dense.imageIdentities[0].count == 8)
+ #expect(Set(dense.imageIdentities[0]).count == 8)
+ }
+
}
diff --git a/Tests/TurboFieldfareServer/ServerImageTokenBudgetTests.swift b/Tests/TurboFieldfareServer/ServerImageTokenBudgetTests.swift
new file mode 100644
index 00000000..62a13809
--- /dev/null
+++ b/Tests/TurboFieldfareServer/ServerImageTokenBudgetTests.swift
@@ -0,0 +1,105 @@
+import Foundation
+import Testing
+@testable import TurboFieldfare
+@testable import TurboFieldfareServerCore
+
+@Suite("Server image token budget")
+struct ServerImageTokenBudgetTests {
+ @Test func eachImageCostsItsProjectedTokensPlusTwoMarkers() {
+ #expect(ServerImageTokenBudget.imageTokens(softTokenCounts: []) == 0)
+ #expect(ServerImageTokenBudget.imageTokens(softTokenCounts: [280]) == 282)
+ #expect(ServerImageTokenBudget.imageTokens(
+ softTokenCounts: [280, 280, 280, 280]) == 1_128)
+ #expect(ServerImageTokenBudget.imageTokens(
+ softTokenCounts: [1, 1, 1]) == 9)
+ }
+
+ @Test func budgetAdmitsExactlyUpToTheContextAndRejectsOneOver() {
+ // 100 text + (280 + 2) image = 382; must be strictly under the context.
+ #expect(ServerImageTokenBudget.fits(
+ softTokenCounts: [280], textTokens: 100, maxContext: 383))
+ #expect(!ServerImageTokenBudget.fits(
+ softTokenCounts: [280], textTokens: 100, maxContext: 382))
+ }
+
+ /// Clients routinely request the whole context as reply; pinned Pi 0.82.1
+ /// sends max_tokens 16384 — the entire default context — on every request.
+ /// The text path clamps rather than refusing, so the image budget must not
+ /// count the requested reply or it rejects requests the server would
+ /// otherwise serve, on any configured context.
+ @Test func aHugeRequestedReplyDoesNotRejectAPromptThatFits() {
+ #expect(ServerImageTokenBudget.fits(
+ softTokenCounts: [258], textTokens: 1_627, maxContext: 8_192))
+ }
+
+ /// The point of the change: how many images fit depends on the context, not
+ /// on a fixed number. A small context admits fewer than the old cap of four
+ /// and a large one admits far more.
+ @Test func admissibleImageCountScalesWithContext() {
+ func maximumFullSizeImages(context: Int) -> Int {
+ var count = 0
+ while ServerImageTokenBudget.fits(
+ softTokenCounts: Array(repeating: 280, count: count + 1),
+ textTokens: 200,
+ maxContext: context) {
+ count += 1
+ }
+ return count
+ }
+ #expect(maximumFullSizeImages(context: 4_096) == 13)
+ #expect(maximumFullSizeImages(context: 8_192) == 28)
+ #expect(maximumFullSizeImages(context: 65_536) == 231)
+ // A context too small for even one full-size image admits none.
+ #expect(maximumFullSizeImages(context: 400) == 0)
+ }
+
+ /// Small images cost proportionally less, so many of them fit where a few
+ /// full-size ones would not.
+ @Test func smallImagesCostLessThanFullSizeOnes() throws {
+ let config = VisionConfig()
+ // A 4:3 photo does not reach the theoretical maximum: the processed side
+ // rounds down to a multiple of patch x pooling, so it lands at 266 of
+ // the 280 ceiling. Only aspect ratios that tile exactly, such as the
+ // 42x60 patch grid, reach it.
+ let full = try Gemma4ImageGeometry(
+ sourceWidth: 4_032, sourceHeight: 3_024, config: config)
+ #expect(full.softTokenCount == 266)
+ #expect(full.softTokenCount <= config.maximumPooledTokens)
+
+ let small = try Gemma4ImageGeometry(
+ sourceWidth: 96, sourceHeight: 96, config: config)
+ #expect(small.softTokenCount < full.softTokenCount)
+ #expect(small.softTokenCount > 0)
+
+ let manySmall = Array(repeating: small.softTokenCount, count: 20)
+ let fewFull = Array(repeating: full.softTokenCount, count: 20)
+ #expect(ServerImageTokenBudget.imageTokens(softTokenCounts: manySmall)
+ < ServerImageTokenBudget.imageTokens(softTokenCounts: fewFull))
+ }
+
+ /// Only the prompt has to fit: the reply budget is deliberately not
+ /// counted, so what rejects a request is its images and text alone.
+ @Test func manySmallImagesStillHaveToFitTheContext() {
+ #expect(ServerImageTokenBudget.fits(
+ softTokenCounts: Array(repeating: 20, count: 50),
+ textTokens: 100, maxContext: 4_096))
+ #expect(!ServerImageTokenBudget.fits(
+ softTokenCounts: Array(repeating: 280, count: 20),
+ textTokens: 100, maxContext: 4_096))
+ }
+
+ @Test func rejectionNamesTheRealCostRatherThanACount() {
+ let error = ServerImageTokenBudget.rejection(
+ imageCount: 3, softTokenCounts: [280, 280, 280],
+ textTokens: 40, maxContext: 800)
+ guard case .invalid(let message, let param, let code) = error else {
+ Issue.record("expected an invalid-request rejection")
+ return
+ }
+ #expect(param == "messages")
+ #expect(code == "context_length_exceeded")
+ #expect(message.contains("846"))
+ #expect(message.contains("800"))
+ #expect(!message.contains("four"))
+ }
+}
diff --git a/Tests/TurboFieldfareServer/ServerInferenceTests.swift b/Tests/TurboFieldfareServer/ServerInferenceTests.swift
new file mode 100644
index 00000000..61f4acc9
--- /dev/null
+++ b/Tests/TurboFieldfareServer/ServerInferenceTests.swift
@@ -0,0 +1,209 @@
+import CoreGraphics
+import Foundation
+import ImageIO
+import Metal
+import Testing
+import UniformTypeIdentifiers
+@testable import TurboFieldfare
+@testable import TurboFieldfareServerCore
+
+@Suite("Server vision capability")
+struct ServerVisionCapabilityTests {
+ @Test func unsupportedHardwareDominatesPackAvailability() {
+ #expect(ServerModelSession.hardwareVisionCapability(
+ supportsVisionRuntime: false) == "unsupported")
+ #expect(ServerModelSession.hardwareVisionCapability(
+ supportsVisionRuntime: true) == nil)
+ }
+
+ @Test func unsupportedHardwareDoesNotInvalidateThePack() {
+ #expect(ServerModelSession.unavailableVisionCapability(
+ for: VisionRuntimeError.unsupportedKernel("requires M2")) == "unsupported")
+ #expect(ServerModelSession.unavailableVisionCapability(
+ for: VisionPackError.invalidMetadata("bad manifest")) == "invalid")
+ }
+}
+
+/// How a request's images are read on the way into a prefill.
+///
+/// The count that lays out an image's placeholder span and the encode that
+/// fills it have to come from one open file. Reading the file twice sniffed,
+/// metadata-parsed and marker-walked every image a second time per request,
+/// and the two opens could see two files: a staged file rewritten in between
+/// gave a count the laid-out span no longer matched.
+@Suite("Server request images")
+struct ServerRequestImagesTests {
+ /// A square source projects to 256 soft tokens and a 2:1 source to 253, so
+ /// writing one shape over the other moves the count without decoding a
+ /// pixel. The tests assert the relation rather than the numbers.
+ private static let plannedWidth = 96
+ private static let plannedHeight = 96
+ private static let rewrittenWidth = 128
+ private static let rewrittenHeight = 64
+
+ /// What an image's span was laid out for, beside what its encode read.
+ private struct EncodedImage {
+ let planned: Int
+ let encoded: Int
+ }
+
+ /// The full-prefill path: every image of the request encoded from the plan
+ /// its count came from, so a file rewritten after the request was planned
+ /// cannot move the count out from under the span already laid out for it.
+ @Test func aFullPrefillEncodesEveryImageFromThePlanItsCountCameFrom() throws {
+ let device = try #require(MTLCreateSystemDefaultDevice())
+ let preprocessor = Gemma4ImagePreprocessor(device: device)
+ let directory = try Self.makeStagingDirectory()
+ defer { try? FileManager.default.removeItem(at: directory) }
+
+ var imageFiles: [UUID: URL] = [:]
+ for index in 0..<3 {
+ let url = directory.appendingPathComponent("staged-\(index).png")
+ try Self.writeSolidImage(
+ width: Self.plannedWidth, height: Self.plannedHeight, to: url)
+ imageFiles[UUID()] = url
+ }
+
+ // Rewritten from inside the first encode, which is the only point that
+ // sits between the counts and the rest of the encodes. It stands in for
+ // a staged file replaced while the request was in flight.
+ var rewritten = false
+ let encoded = try ServerRequestImages.encodeAll(
+ imageFiles,
+ with: preprocessor,
+ encode: { image -> EncodedImage in
+ if !rewritten {
+ rewritten = true
+ for url in imageFiles.values {
+ try Self.writeSolidImage(
+ width: Self.rewrittenWidth,
+ height: Self.rewrittenHeight,
+ to: url)
+ }
+ }
+ let tokens = try ServerRequestImages.encode(
+ image,
+ fromPlan: { $0.geometry.softTokenCount },
+ byReopening: {
+ try preprocessor.plan(fileURL: $0).geometry.softTokenCount
+ })
+ return EncodedImage(planned: image.softTokenCount, encoded: tokens)
+ })
+
+ #expect(encoded.count == imageFiles.count)
+ let plannedCounts = Set(encoded.values.map(\.planned))
+ let reread = try ServerRequestImages.plans(
+ for: Array(imageFiles.values), with: preprocessor)
+ let rereadCounts = Set(reread.map(\.softTokenCount))
+ try #require(
+ plannedCounts.isDisjoint(with: rereadCounts),
+ "the rewrite has to move the projected count or a second read is invisible")
+ for (id, image) in encoded {
+ #expect(image.encoded == image.planned,
+ "image \(id) was read again at encode time: its span was laid out for \(image.planned) tokens and the encode read \(image.encoded)")
+ }
+ }
+
+ /// The bound on open descriptors is the one place a second read is
+ /// intended, and it applies from the image past it onwards.
+ @Test func onlyTheImagesPastTheOpenPlanBoundAreReadTwice() throws {
+ let device = try #require(MTLCreateSystemDefaultDevice())
+ let preprocessor = Gemma4ImagePreprocessor(device: device)
+ let directory = try Self.makeStagingDirectory()
+ defer { try? FileManager.default.removeItem(at: directory) }
+
+ var urls: [URL] = []
+ for index in 0..<2 {
+ let url = directory.appendingPathComponent("staged-\(index).png")
+ try Self.writeSolidImage(
+ width: Self.plannedWidth, height: Self.plannedHeight, to: url)
+ urls.append(url)
+ }
+ let planned = try ServerRequestImages.plans(
+ for: urls, with: preprocessor, maximumOpenPlans: 1)
+ for url in urls {
+ try Self.writeSolidImage(
+ width: Self.rewrittenWidth, height: Self.rewrittenHeight, to: url)
+ }
+ let encoded = try planned.map { image in
+ try ServerRequestImages.encode(
+ image,
+ fromPlan: { $0.geometry.softTokenCount },
+ byReopening: {
+ try preprocessor.plan(fileURL: $0).geometry.softTokenCount
+ })
+ }
+
+ #expect(encoded[0] == planned[0].softTokenCount,
+ "the image inside the bound kept its plan, so its encode reads \(planned[0].softTokenCount) tokens rather than \(encoded[0])")
+ #expect(encoded[1] != planned[1].softTokenCount,
+ "the image past the bound gave its descriptor up, so its encode has to reopen the file rather than report \(encoded[1])")
+ }
+
+ /// An unreadable image is the request's problem whichever position it sits
+ /// in, and the tower is the expensive part: planning every image first
+ /// refuses the request before any of the others is encoded.
+ @Test func anUnreadableImageIsRefusedBeforeAnyOtherImageIsEncoded() throws {
+ let device = try #require(MTLCreateSystemDefaultDevice())
+ let preprocessor = Gemma4ImagePreprocessor(device: device)
+ let directory = try Self.makeStagingDirectory()
+ defer { try? FileManager.default.removeItem(at: directory) }
+
+ var imageFiles: [UUID: URL] = [:]
+ for index in 0..<2 {
+ let url = directory.appendingPathComponent("staged-\(index).png")
+ try Self.writeSolidImage(
+ width: Self.plannedWidth, height: Self.plannedHeight, to: url)
+ imageFiles[UUID()] = url
+ }
+ let broken = directory.appendingPathComponent("staged-broken.png")
+ try Data("this is not an image, whatever the extension claims".utf8)
+ .write(to: broken)
+ imageFiles[UUID()] = broken
+
+ var encodes = 0
+ var failure: (any Error)?
+ do {
+ _ = try ServerRequestImages.encodeAll(
+ imageFiles,
+ with: preprocessor,
+ encode: { image -> Int in
+ encodes += 1
+ return image.softTokenCount
+ })
+ } catch {
+ failure = error
+ }
+
+ #expect(failure != nil, "an image that cannot be read has to fail the request")
+ #expect(encodes == 0,
+ "the request was refused only after \(encodes) of its images had been encoded")
+ }
+
+ private static func makeStagingDirectory() throws -> URL {
+ let directory = FileManager.default.temporaryDirectory
+ .appendingPathComponent("server-request-images-\(UUID().uuidString)")
+ try FileManager.default.createDirectory(
+ at: directory, withIntermediateDirectories: true)
+ return directory
+ }
+
+ /// A solid PNG of the given shape, replacing whatever is at the URL. Only
+ /// the dimensions matter here: the projected token count follows from them
+ /// alone, and these are small enough that nothing decodes a real surface.
+ private static func writeSolidImage(width: Int, height: Int, to url: URL) throws {
+ let colorSpace = try #require(CGColorSpace(name: CGColorSpace.sRGB))
+ let bitmap = try #require(CGContext(
+ data: nil, width: width, height: height, bitsPerComponent: 8,
+ bytesPerRow: width * 4, space: colorSpace,
+ bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue))
+ bitmap.setFillColor(CGColor(gray: 0.5, alpha: 1))
+ bitmap.fill(CGRect(x: 0, y: 0, width: width, height: height))
+ let image = try #require(bitmap.makeImage())
+ try? FileManager.default.removeItem(at: url)
+ let destination = try #require(CGImageDestinationCreateWithURL(
+ url as CFURL, UTType.png.identifier as CFString, 1, nil))
+ CGImageDestinationAddImage(destination, image, nil)
+ #expect(CGImageDestinationFinalize(destination))
+ }
+}
diff --git a/Tests/TurboFieldfareServer/ServerIngressHardeningTests.swift b/Tests/TurboFieldfareServer/ServerIngressHardeningTests.swift
new file mode 100644
index 00000000..7a997143
--- /dev/null
+++ b/Tests/TurboFieldfareServer/ServerIngressHardeningTests.swift
@@ -0,0 +1,385 @@
+import Darwin
+import Foundation
+import NIOCore
+import Testing
+@testable import TurboFieldfare
+@testable import TurboFieldfareServerCore
+
+/// Ingress-side resource ownership: what a request is allowed to allocate
+/// before it has been accepted, and when those allocations come back.
+///
+/// The unit under test is the connection, not the completion, so the backend
+/// only has to answer.
+private actor EchoBackend: ServerInferenceBackend {
+ func generate(
+ _ request: ValidatedChatRequest,
+ onEvent: @escaping @Sendable (ServerInferenceEvent) -> Void
+ ) async throws -> ServerCompletion {
+ onEvent(.content("ok"))
+ return ServerCompletion(
+ content: "ok", toolCalls: [], finishReason: "stop",
+ usage: OpenAIUsage(promptTokens: 1, completionTokens: 1, totalTokens: 2))
+ }
+}
+
+@Suite struct ServerIngressHardeningTests {
+ /// A staging root of this test's own. The process-wide one is shared with
+ /// every other server in the suite, so counting files under it measures
+ /// whatever else happens to be running.
+ private static func makeRoot() -> URL {
+ FileManager.default.temporaryDirectory
+ .appendingPathComponent("ingress-\(UUID().uuidString)", isDirectory: true)
+ }
+
+ /// Every file staged under this root, however deep. A leaked lease shows up
+ /// here as a directory that outlives its request.
+ private static func stagedFileCount(_ root: URL) -> Int {
+ guard let walker = FileManager.default.enumerator(
+ at: root, includingPropertiesForKeys: [.isRegularFileKey]) else { return 0 }
+ var count = 0
+ for case let url as URL in walker {
+ let regular = (try? url.resourceValues(forKeys: [.isRegularFileKey]))?
+ .isRegularFile ?? false
+ if regular { count += 1 }
+ }
+ return count
+ }
+
+ private static func imageBody(count: Int) -> String {
+ // A one-pixel PNG, valid enough to be staged; the request is rejected
+ // later, which is exactly the case that used to leak.
+ let pixel = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="
+ let parts = (0..<count).map {
+ _ in #"{"type":"image_url","image_url":{"url":"data:image/png;base64,\#(pixel)"}}"#
+ }.joined(separator: ",")
+ return #"{"model":"test-model","messages":[{"role":"user","content":[\#(parts)]}]}"#
+ }
+
+ /// A rejected request must give its staged images back immediately. The
+ /// client is under no obligation to close a keep-alive connection, so
+ /// holding them until `channelInactive` means holding them forever.
+ @Test func rejectedRequestReleasesStagedImagesWithoutClosingTheConnection() async throws {
+ let root = Self.makeRoot()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let server = TurboFieldfareHTTPServer(
+ modelID: "test-model", queueLimit: 1, backend: EchoBackend(),
+ visionCapability: "ready", attachmentRoot: root)
+ let channel = try await server.start(port: 0)
+ let port = try #require(channel.localAddress?.port)
+ let socket = try connectedSocket(port: port)
+ defer { _ = Darwin.close(socket) }
+
+ // Over the per-request image cap, so staging happens and then fails.
+ let body = Self.imageBody(count: ServerAttachmentStore.maximumRequestImages + 4)
+ try writeAll(socket: socket, text: httpRequest(
+ port: port, body: body, connection: "keep-alive"))
+ let response = try readUntil(
+ socket: socket, timeoutMilliseconds: 4_000,
+ condition: { $0.contains("HTTP/1.1 4") })
+ #expect(response.contains("too_many_images"))
+
+ // Connection deliberately still open.
+ #expect(Self.stagedFileCount(root) == 0,
+ "staged images survived the rejection that discarded them")
+ try await server.shutdown()
+ }
+
+ /// A server that cannot serve images must refuse them during the body
+ /// parse — before a byte is decoded to disk — not after the request has
+ /// queued behind a generation.
+ @Test func imagesAreRefusedWithoutStagingWhenVisionIsUnavailable() async throws {
+ let root = Self.makeRoot()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let server = TurboFieldfareHTTPServer(
+ modelID: "test-model", queueLimit: 1, backend: EchoBackend(),
+ visionCapability: "missing", attachmentRoot: root)
+ let channel = try await server.start(port: 0)
+ let port = try #require(channel.localAddress?.port)
+ let socket = try connectedSocket(port: port)
+ defer { _ = Darwin.close(socket) }
+
+ try writeAll(socket: socket, text: httpRequest(
+ port: port, body: Self.imageBody(count: 1), connection: "keep-alive"))
+ let response = try readUntil(
+ socket: socket, timeoutMilliseconds: 4_000,
+ condition: { $0.contains("HTTP/1.1 4") })
+ #expect(response.contains("vision_unavailable"))
+ #expect(Self.stagedFileCount(root) == 0,
+ "an image was staged on a server that cannot serve images")
+ try await server.shutdown()
+ }
+
+ /// Nothing may be written to disk for a request the router will not accept.
+ /// Staging used to run before the method, path and content-type were even
+ /// looked at, so `PUT /health` could fill the attachment directory.
+ @Test func bodiesOnUnroutedRequestsAreNeverStaged() async throws {
+ let root = Self.makeRoot()
+ defer { try? FileManager.default.removeItem(at: root) }
+ let server = TurboFieldfareHTTPServer(
+ modelID: "test-model", queueLimit: 1, backend: EchoBackend(),
+ attachmentRoot: root)
+ let channel = try await server.start(port: 0)
+ let port = try #require(channel.localAddress?.port)
+ let body = Self.imageBody(count: 3)
+
+ func send(_ head: String, expecting status: String) throws {
+ let socket = try connectedSocket(port: port)
+ defer { _ = Darwin.close(socket) }
+ try writeAll(socket: socket, text: head
+ + "Host: 127.0.0.1:\(port)\r\n"
+ + "Content-Length: \(body.utf8.count)\r\n"
+ + "Connection: close\r\n\r\n" + body)
+ let response = try readUntil(
+ socket: socket, timeoutMilliseconds: 4_000,
+ condition: { $0.contains("HTTP/1.1 ") })
+ #expect(response.contains(status), "got \(response.prefix(64))")
+ #expect(Self.stagedFileCount(root) == 0,
+ "a body was staged before its request was routed")
+ }
+
+ try send("PUT /health HTTP/1.1\r\nContent-Type: application/json\r\n",
+ expecting: "405")
+ try send("POST /v1/nope HTTP/1.1\r\nContent-Type: application/json\r\n",
+ expecting: "404")
+ try send("POST /v1/chat/completions HTTP/1.1\r\nContent-Type: text/plain\r\n",
+ expecting: "415")
+ try await server.shutdown()
+ }
+
+ /// A body on an unrouted request is discarded rather than parsed, so the
+ /// parser's size cap no longer applies to it. It still has to be bounded.
+ @Test func discardedBodiesAreStillBounded() async throws {
+ let server = TurboFieldfareHTTPServer(
+ modelID: "test-model", queueLimit: 1, backend: EchoBackend())
+ let channel = try await server.start(port: 0)
+ let port = try #require(channel.localAddress?.port)
+ let socket = try connectedSocket(port: port)
+ defer { _ = Darwin.close(socket) }
+
+ let chunk = String(repeating: "x", count: 1 << 20)
+ let total = StreamingChatRequestBody.maximumWireBytes + (4 << 20)
+ try writeAll(socket: socket, text: "POST /v1/nope HTTP/1.1\r\n"
+ + "Host: 127.0.0.1:\(port)\r\n"
+ + "Content-Type: application/json\r\n"
+ + "Content-Length: \(total)\r\n"
+ + "Connection: close\r\n\r\n")
+ var sent = 0
+ var response = ""
+ while sent < total {
+ do { try writeAll(socket: socket, text: chunk) } catch { break }
+ sent += chunk.utf8.count
+ // The server answers as soon as the cap is passed and then closes.
+ if let peek = try? readAvailable(socket: socket, timeoutMilliseconds: 0),
+ peek.contains("HTTP/1.1 ") {
+ response = peek
+ break
+ }
+ }
+ if !response.contains("HTTP/1.1 ") {
+ response = try readUntil(
+ socket: socket, timeoutMilliseconds: 4_000,
+ condition: { $0.contains("HTTP/1.1 ") })
+ }
+ #expect(response.contains("413") || response.contains("request_too_large"),
+ "unbounded discarded body: \(response.prefix(64))")
+ try await server.shutdown()
+ }
+
+ /// An idle keep-alive connection holds a slot against the connection cap
+ /// forever unless the server closes it.
+ @Test func idleConnectionsAreClosed() async throws {
+ let server = TurboFieldfareHTTPServer(
+ modelID: "test-model", queueLimit: 1, backend: EchoBackend(),
+ idleTimeout: .milliseconds(200))
+ let channel = try await server.start(port: 0)
+ let port = try #require(channel.localAddress?.port)
+ let socket = try connectedSocket(port: port)
+ defer { _ = Darwin.close(socket) }
+
+ // One completed request, then silence.
+ try writeAll(socket: socket, text: httpRequest(
+ port: port, body: #"{"model":"test-model","messages":[{"role":"user","content":"hi"}]}"#,
+ connection: "keep-alive"))
+ _ = try readUntil(socket: socket, timeoutMilliseconds: 4_000,
+ condition: { $0.contains("\"content\":\"ok\"") })
+
+ // recv returning 0 is the peer's FIN.
+ var descriptor = pollfd(fd: socket, events: Int16(POLLIN), revents: 0)
+ var closed = false
+ let deadline = Date().addingTimeInterval(4)
+ while Date() < deadline {
+ guard Darwin.poll(&descriptor, 1, 100) > 0 else { continue }
+ var buffer = [UInt8](repeating: 0, count: 1_024)
+ if Darwin.recv(socket, &buffer, buffer.count, 0) == 0 { closed = true; break }
+ }
+ #expect(closed, "idle connection was never closed")
+ try await server.shutdown()
+ }
+
+ /// A request whose parse already failed must not become an unbounded
+ /// drain: past the wire cap the server answers and closes, because a
+ /// chunked stream may never send the .end that would otherwise produce
+ /// the response, and every read resets the idle timer.
+ @Test func bodiesPastTheWireCapAreAnsweredAndClosed() async throws {
+ let server = TurboFieldfareHTTPServer(
+ modelID: "test-model", queueLimit: 1, backend: EchoBackend())
+ let channel = try await server.start(port: 0)
+ let port = try #require(channel.localAddress?.port)
+ let socket = try connectedSocket(port: port)
+ defer { _ = Darwin.close(socket) }
+
+ let chunk = String(repeating: "x", count: 1 << 20)
+ let total = StreamingChatRequestBody.maximumWireBytes + (4 << 20)
+ try writeAll(socket: socket, text: "POST /v1/chat/completions HTTP/1.1\r\n"
+ + "Host: 127.0.0.1:\(port)\r\n"
+ + "Content-Type: application/json\r\n"
+ + "Content-Length: \(total)\r\n\r\n")
+ var sent = 0
+ var response = ""
+ while sent < total {
+ do { try writeAll(socket: socket, text: chunk) } catch { break }
+ sent += chunk.utf8.count
+ if let peek = try? readAvailable(socket: socket, timeoutMilliseconds: 0),
+ peek.contains("HTTP/1.1 ") {
+ response = peek
+ break
+ }
+ }
+ if !response.contains("HTTP/1.1 ") {
+ response = try readUntil(
+ socket: socket, timeoutMilliseconds: 4_000,
+ condition: { $0.contains("HTTP/1.1 ") })
+ }
+ #expect(response.contains("413") || response.contains("request_too_large"),
+ "unbounded latched body: \(response.prefix(64))")
+
+ var descriptor = pollfd(fd: socket, events: Int16(POLLIN), revents: 0)
+ var closed = false
+ let deadline = Date().addingTimeInterval(4)
+ while Date() < deadline {
+ guard Darwin.poll(&descriptor, 1, 100) > 0 else { continue }
+ var buffer = [UInt8](repeating: 0, count: 4_096)
+ if Darwin.recv(socket, &buffer, buffer.count, 0) == 0 { closed = true; break }
+ }
+ #expect(closed, "a connection past the wire cap stayed open")
+ try await server.shutdown()
+ }
+
+ /// A client that sends a request head and goes silent is a stalled upload,
+ /// not a request in flight: it must not hold a slot against the connection
+ /// cap past the read timeout. An active uploader is safe — every body
+ /// chunk it sends resets the timer.
+ @Test func stalledUploadsAreReapedByTheIdleTimeout() async throws {
+ let server = TurboFieldfareHTTPServer(
+ modelID: "test-model", queueLimit: 1, backend: EchoBackend(),
+ idleTimeout: .milliseconds(200))
+ let channel = try await server.start(port: 0)
+ let port = try #require(channel.localAddress?.port)
+ let socket = try connectedSocket(port: port)
+ defer { _ = Darwin.close(socket) }
+
+ // A head promising a body that never arrives.
+ try writeAll(socket: socket, text: "POST /v1/chat/completions HTTP/1.1\r\n"
+ + "Host: 127.0.0.1:\(port)\r\n"
+ + "Content-Type: application/json\r\n"
+ + "Content-Length: 1024\r\n\r\n{\"model\":")
+
+ var descriptor = pollfd(fd: socket, events: Int16(POLLIN), revents: 0)
+ var closed = false
+ let deadline = Date().addingTimeInterval(4)
+ while Date() < deadline {
+ guard Darwin.poll(&descriptor, 1, 100) > 0 else { continue }
+ var buffer = [UInt8](repeating: 0, count: 1_024)
+ if Darwin.recv(socket, &buffer, buffer.count, 0) == 0 { closed = true; break }
+ }
+ #expect(closed, "a stalled upload was never reaped")
+ try await server.shutdown()
+ }
+
+ /// Accepted sockets were unbounded: each costs a descriptor and can pin a
+ /// staging directory, so the count has to be capped.
+ @Test func connectionsBeyondTheCapAreClosed() async throws {
+ let server = TurboFieldfareHTTPServer(
+ modelID: "test-model", queueLimit: 1, backend: EchoBackend())
+ let channel = try await server.start(port: 0)
+ let port = try #require(channel.localAddress?.port)
+ let cap = TurboFieldfareHTTPServer.maximumConnections
+ var sockets: [Int32] = []
+ defer { sockets.forEach { _ = Darwin.close($0) } }
+ for _ in 0..<cap {
+ sockets.append(try connectedSocket(port: port))
+ }
+ // The accept loop runs on the event loop; wait for it to catch up.
+ let deadline = Date().addingTimeInterval(4)
+ while await server.acceptedConnectionCount < cap, Date() < deadline {
+ try await Task.sleep(nanoseconds: 20_000_000)
+ }
+ #expect(await server.acceptedConnectionCount == cap)
+
+ let overflow = try connectedSocket(port: port)
+ sockets.append(overflow)
+ // A refused connection is accepted by the kernel and then closed, so it
+ // reads EOF rather than failing to connect.
+ var descriptor = pollfd(fd: overflow, events: Int16(POLLIN), revents: 0)
+ var closed = false
+ let overflowDeadline = Date().addingTimeInterval(4)
+ while Date() < overflowDeadline {
+ guard Darwin.poll(&descriptor, 1, 100) > 0 else { continue }
+ var buffer = [UInt8](repeating: 0, count: 64)
+ if Darwin.recv(overflow, &buffer, buffer.count, 0) == 0 { closed = true; break }
+ }
+ #expect(closed, "connection past the cap stayed open")
+ #expect(await server.acceptedConnectionCount == cap)
+ try await server.shutdown()
+ }
+}
+
+/// The sweep is what reclaims staging directories left by a process that died
+/// before its leases could release them.
+@Suite struct ServerAttachmentSweepTests {
+ @Test func sweepReclaimsDeadProcessesAndSparesLiveOnes() throws {
+ let manager = FileManager.default
+ // An isolated root: a server starting in a parallel test sweeps the
+ // real one, which would race this test's fixtures.
+ let root = manager.temporaryDirectory
+ .appendingPathComponent("sweep-\(UUID().uuidString)", isDirectory: true)
+ defer { try? manager.removeItem(at: root) }
+ try manager.createDirectory(at: root, withIntermediateDirectories: true)
+
+ // A pid that cannot be running: pid_t values are positive and this one
+ // is past the system maximum.
+ let dead = root.appendingPathComponent("pid-4194300", isDirectory: true)
+ let deadFile = dead.appendingPathComponent("staged.bin")
+ try manager.createDirectory(at: dead, withIntermediateDirectories: true)
+ try Data([0x1]).write(to: deadFile)
+
+ // A directory from an older layout, owned by no process at all.
+ let legacy = root.appendingPathComponent(UUID().uuidString, isDirectory: true)
+ try manager.createDirectory(at: legacy, withIntermediateDirectories: true)
+
+ // This process is alive, so its own directory must survive.
+ let live = try ServerAttachmentDirectory.makeLease(in: root)
+ let liveFile = live.directoryURL.appendingPathComponent("staged.bin")
+ try Data([0x2]).write(to: liveFile)
+
+ let reclaimed = ServerAttachmentDirectory.sweepAbandoned(in: root)
+ #expect(reclaimed.contains("pid-4194300"))
+ #expect(reclaimed.contains(legacy.lastPathComponent))
+ #expect(!manager.fileExists(atPath: dead.path))
+ #expect(!manager.fileExists(atPath: legacy.path))
+ #expect(manager.fileExists(atPath: liveFile.path),
+ "the sweep deleted a live process's staged images")
+
+ withExtendedLifetime(live) {}
+ }
+
+ @Test func leasesAreScopedUnderThisProcess() throws {
+ let lease = try ServerAttachmentDirectory.makeLease()
+ defer { try? FileManager.default.removeItem(at: lease.directoryURL) }
+ #expect(lease.directoryURL.deletingLastPathComponent().lastPathComponent
+ == "pid-\(getpid())")
+ #expect(lease.directoryURL.deletingLastPathComponent()
+ .deletingLastPathComponent().lastPathComponent
+ == ServerAttachmentDirectory.rootName)
+ }
+}
diff --git a/Tests/TurboFieldfareServer/ServerLogTests.swift b/Tests/TurboFieldfareServer/ServerLogTests.swift
new file mode 100644
index 00000000..6e1927e9
--- /dev/null
+++ b/Tests/TurboFieldfareServer/ServerLogTests.swift
@@ -0,0 +1,22 @@
+import Testing
+@testable import TurboFieldfareServerCore
+
+/// A cancelled request used to be excluded from logging entirely, on the
+/// reasoning that a client hanging up is not a server fault. That is true, and it
+/// left the request's last line as `generating` forever: reading the log, a
+/// running request, an abandoned one and a crashed one were indistinguishable.
+@Suite struct ServerLogTests {
+ @Test func aCancelledRequestReadsAsCancelledRatherThanFailed() {
+ let line = ServerLog.cancelledMessage(id: "chatcmpl-abc",
+ phase: "generating",
+ duration: .milliseconds(5369))
+
+ #expect(line.contains("chatcmpl-abc"))
+ #expect(line.contains("cancelled by client"))
+ #expect(line.contains("phase=generating"))
+ #expect(line.contains("5.369s"))
+ // Distinct from a failure, so an abandoned client does not read as a
+ // server fault in the log or in anything counting error lines.
+ #expect(!line.contains("failed"))
+ }
+}
diff --git a/Tests/TurboFieldfareServer/ServerPromptCacheTests.swift b/Tests/TurboFieldfareServer/ServerPromptCacheTests.swift
index caddd15c..84d62221 100644
--- a/Tests/TurboFieldfareServer/ServerPromptCacheTests.swift
+++ b/Tests/TurboFieldfareServer/ServerPromptCacheTests.swift
@@ -118,6 +118,137 @@ struct ServerPromptCacheTests {
#expect(!rendered.prefix(kvBacked.count).elementsEqual(kvBacked))
}
+ /// A model that repeats a tool call verbatim must keep its cache.
+ ///
+ /// The repeat renders to a token sequence the history already contains, so
+ /// the old unique-match rule refused the bridge and the conversation
+ /// stayed uncached from the first verbatim repeat on; the boundary is
+ /// resolved by position instead. A bridge that cannot render is still a
+ /// named condition rather than a swallowed one — the divergent-history
+ /// shape at the end still refuses — but with message-equal leading history
+ /// the pinned render is deterministic, so `.bridgeRenderFailed` inside
+ /// `match` is defense in depth rather than a reachable outcome.
+ @Test func aRepeatedToolCallResolvesByPositionAndHits() async throws {
+ let tokenizer = try await GFTokenizer.load()
+ let call = GFTokenizer.HistoricalToolCall(
+ id: "call_repeat", name: "read", arguments: .object(["path": .string("a.txt")]))
+ let tools = [GFTokenizer.FunctionDefinition(
+ name: "read",
+ description: "Read a file.",
+ parameters: .object(["type": .string("object")]))]
+ let earlier: [GFTokenizer.Message] = [
+ GFTokenizer.Message(role: .user, content: "read a.txt"),
+ GFTokenizer.Message(role: .assistant, content: nil, toolCalls: [call]),
+ GFTokenizer.Message(role: .tool, content: "contents", toolCallID: call.id),
+ GFTokenizer.Message(role: .user, content: "read it again"),
+ ]
+ let cached = request(messages: earlier, tools: tools)
+ let assistant = GFTokenizer.Message(
+ role: .assistant, content: nil, toolCalls: [call])
+ let prefix = try tokenizer.encodeToolChat(
+ messages: earlier + [assistant], tools: tools)
+ // The KV holds what the model generated, not a fresh render of it, so
+ // the cheap prefix path cannot match and the bridge is what decides.
+ let initialPrompt = try tokenizer.encodeToolChat(
+ messages: earlier, tools: tools)
+ let callStart = try #require(prefix.lastIndex(of: tokenizer.toolCallStartID))
+ let callEnd = try #require(prefix.lastIndex(of: tokenizer.toolCallEndID))
+ let kvBacked = initialPrompt + Array(prefix[callStart...callEnd])
+ let parsed = ParsedToolCall(
+ id: call.id, name: call.name, arguments: call.arguments,
+ argumentsJSON: try call.arguments.encoded())
+ var cache = ServerPromptCache()
+ cache.publish(
+ domain: domain,
+ request: cached,
+ content: "",
+ calls: [parsed],
+ result: rawResult(
+ prompt: initialPrompt,
+ kvBacked: kvBacked,
+ boundary: tokenizer.toolResponseID,
+ reason: .toolCalls))
+
+ let continuation = request(
+ messages: earlier + [
+ assistant,
+ GFTokenizer.Message(
+ role: .tool, content: "contents", toolCallID: call.id),
+ ],
+ tools: tools)
+ let bridge = try tokenizer.encodeToolResultContinuation(
+ cachedMessages: earlier,
+ assistant: assistant,
+ incomingMessages: continuation.messages,
+ tools: tools)
+ // The bridge continues from the cached repeat, not its earlier
+ // identical twin. Both twins are followed by a tool response, so the
+ // first-token check alone cannot tell them apart; a twin-anchored
+ // bridge would replay the first response and the repeated call turn.
+ #expect(bridge.first == tokenizer.toolResponseID)
+ #expect(bridge.filter { $0 == tokenizer.toolResponseID }.count == 1)
+ #expect(!bridge.contains(tokenizer.toolCallStartID))
+
+ let match = cache.match(
+ domain: domain,
+ request: continuation,
+ renderedPromptIDs: try tokenizer.encodeToolChat(
+ messages: continuation.messages, tools: tools),
+ tokenizer: tokenizer)
+
+ guard case .hit(let effective, let cached) = match else {
+ Issue.record("expected repeated-call tool-result hit")
+ return
+ }
+ #expect(cached == kvBacked.count)
+ #expect(effective == kvBacked + bridge)
+
+ // A cached history that diverged from the incoming one cannot anchor
+ // the repeated sequence by position, and the ambiguous fallback still
+ // refuses rather than guessing a twin.
+ let diverged = [GFTokenizer.Message(role: .user, content: "read b.txt")]
+ + earlier.dropFirst()
+ #expect(throws: (any Error).self) {
+ try tokenizer.encodeToolResultContinuation(
+ cachedMessages: diverged,
+ assistant: assistant,
+ incomingMessages: continuation.messages,
+ tools: tools)
+ }
+ }
+
+ /// The prompt-cache domain used to cover six configuration fields and
+ /// nothing else, while roughly nineteen `TURBO_FIELDFARE_VISION_*` switches
+ /// select kernels - one of them set to `0` picks a different attention path
+ /// and costs 55% of the encode. A prefix built under one selection could be
+ /// resumed under another with nothing recording the change.
+ @Test func runtimeIdentityCoversTheSwitchesThatSelectKernels() {
+ let runtime = RuntimeConfiguration()
+ let plain = ServerModelSession.runtimeIdentityString(
+ runtime: runtime, environment: [:])
+ let switched = ServerModelSession.runtimeIdentityString(
+ runtime: runtime,
+ environment: ["TURBO_FIELDFARE_VISION_ATTENTION_MPP": "0"])
+ #expect(plain != switched, "a kernel switch did not change cache identity")
+
+ // Unrelated variables stay out of it, or every shell would invalidate.
+ #expect(ServerModelSession.runtimeIdentityString(
+ runtime: runtime, environment: ["PATH": "/usr/bin"]) == plain)
+
+ // Stable for the same input, and order-independent.
+ #expect(ServerModelSession.runtimeIdentityString(
+ runtime: runtime,
+ environment: ["TURBO_FIELDFARE_B": "1", "TURBO_FIELDFARE_A": "1"])
+ == ServerModelSession.runtimeIdentityString(
+ runtime: runtime,
+ environment: ["TURBO_FIELDFARE_A": "1", "TURBO_FIELDFARE_B": "1"]))
+
+ // And the value matters, not just the name.
+ #expect(ServerModelSession.runtimeIdentityString(
+ runtime: runtime, environment: ["TURBO_FIELDFARE_VISION_ATTENTION_MPP": "1"])
+ != switched)
+ }
+
@Test func mismatchedLineageDomainAndUnsafeStopsMiss() async throws {
let tokenizer = try await GFTokenizer.load()
let initial = request(messages: [
@@ -160,11 +291,13 @@ struct ServerPromptCacheTests {
let rendered = tokenizer.encode(
try tokenizer.applyChatTemplate(changed.messages),
addBOS: false)
+ // A changed first message is a diverged history, and the miss now says
+ // so rather than arriving as an anonymous one.
#expect(cache.match(
domain: domain,
request: changed,
renderedPromptIDs: rendered,
- tokenizer: tokenizer) == .miss)
+ tokenizer: tokenizer).missReason == .historyDiverged)
}
@Test func tailCompletedStopStringDoesNotPublishPrefix() async throws {
@@ -195,70 +328,473 @@ struct ServerPromptCacheTests {
#expect(cache.entry == nil)
}
- /// A verbatim-repeated tool call must keep its cache; the unique-match
- /// rule refused this shape and dropped the cache from that turn on.
- @Test func repeatedIdenticalToolCallKeepsTheBoundaryResolvable() async throws {
+ /// Why `ServerModelSession.generate` must never publish a multimodal turn.
+ ///
+ /// This cache identifies a prefix by its flattened message text, and image
+ /// parts contribute nothing to that. An image turn's KV holds rows built
+ /// from projected image features, but its cached `inputMessages` are just
+ /// the text. A later text-only continuation of that conversation — a client
+ /// that resends the history without the `image_url` parts — then matches,
+ /// and resumes from a prefix whose content it never sent.
+ ///
+ /// This publishes an image turn directly, bypassing the guard, to show the
+ /// cache handing that prefix over. It fails the day the cache learns image
+ /// identity, at which point the guard can be relaxed deliberately rather
+ /// than by accident.
+ @Test func anImageBuiltPrefixWouldBeHandedToATextContinuation() async throws {
let tokenizer = try await GFTokenizer.load()
- let tools = [GFTokenizer.FunctionDefinition(
- name: "ls",
- description: "list a directory",
- parameters: .object([
- "type": .string("object"),
- "properties": .object([
- "path": .object(["type": .string("string")]),
- ]),
- ]))]
- let call = { (id: String) in
- GFTokenizer.HistoricalToolCall(
- id: id,
- name: "ls",
- arguments: .object(["path": .string(".")]))
+ var cache = ServerPromptCache()
+ let opening = [GFTokenizer.Message(role: .user, content: "describe this")]
+
+ let imageTurn = ValidatedChatRequest(
+ messages: opening,
+ multimodalMessages: [MultimodalMessage(
+ role: .user,
+ content: [.text("describe this"), .image(id: UUID())])],
+ imageFiles: [UUID(): URL(fileURLWithPath: "/dev/null")],
+ imageIdentities: [["sha-of-the-image"]],
+ tools: [],
+ stream: false,
+ includeUsage: false,
+ generationConfig: GenerationConfig(maxNewTokens: 16, temperature: 0),
+ maximumCompletionTokens: 16)
+ // The condition the session's guard tests.
+ #expect(imageTurn.multimodalMessages != nil)
+
+ let prefix = tokenizer.encode(
+ try tokenizer.applyChatTemplate(opening), addBOS: false)
+ cache.publish(
+ domain: domain,
+ request: imageTurn,
+ content: "a description",
+ calls: [],
+ result: rawResult(prompt: prefix,
+ kvBacked: prefix + tokenizer.encode("a description", addBOS: false),
+ boundary: tokenizer.endOfTurnID,
+ reason: .endOfTurn))
+
+ // The same conversation, continued, with the image part dropped.
+ let continuation = request(messages: opening + [
+ GFTokenizer.Message(role: .assistant, content: "a description"),
+ GFTokenizer.Message(role: .user, content: "and now?"),
+ ])
+ #expect(continuation.multimodalMessages == nil)
+
+ let rendered = tokenizer.encode(
+ try tokenizer.applyChatTemplate(continuation.messages), addBOS: false)
+ let match = cache.match(
+ domain: domain,
+ request: continuation,
+ renderedPromptIDs: rendered,
+ tokenizer: tokenizer)
+ // Refused by identity now, not by a blanket rule: the entry remembers
+ // which image built it, so a client that drops the image parts cannot
+ // resume onto a KV holding projected features it never sent. This is
+ // what replaced the publish guard in `ServerModelSession.generate`.
+ #expect(match.missReason == .imagesDiverged,
+ "an image-built prefix was handed to a text continuation")
+ }
+
+ /// Image parts contribute nothing to a message's flattened text, so two
+ /// prompts differing only in their image compare equal as messages. The
+ /// cache must separate them on image content hash.
+ @Test func differentImageWithIdenticalTextDoesNotReuseThePrefix() async throws {
+ let tokenizer = try await GFTokenizer.load()
+ let messages = [GFTokenizer.Message(role: .user, content: "describe")]
+ let initial = request(messages: messages, imageIdentities: [["image-a"]])
+ let prompt = tokenizer.encode(
+ try tokenizer.applyChatTemplate(initial.messages), addBOS: false)
+ let kvBacked = prompt + tokenizer.encode("answer", addBOS: false)
+ var cache = ServerPromptCache()
+ cache.publish(
+ domain: domain, request: initial, content: "answer", calls: [],
+ result: rawResult(prompt: prompt, kvBacked: kvBacked,
+ boundary: tokenizer.endOfTurnID, reason: .endOfTurn))
+
+ let follow = messages + [
+ GFTokenizer.Message(role: .assistant, content: "answer"),
+ GFTokenizer.Message(role: .user, content: "and now"),
+ ]
+ let sameImage = cache.match(
+ domain: domain,
+ request: request(messages: follow,
+ imageIdentities: [["image-a"], [], []]),
+ renderedPromptIDs: nil, tokenizer: tokenizer)
+ guard case .hit = sameImage else {
+ Issue.record("the same image must continue from the cached prefix")
+ return
}
- let first = GFTokenizer.Message(
- role: .assistant, content: nil, toolCalls: [call("call_1")])
- let firstResult = GFTokenizer.Message(
- role: .tool, content: "pkg/", toolCallID: "call_1", name: "ls")
- // Byte-identical to the first call; only the call id differs.
- let repeated = GFTokenizer.Message(
- role: .assistant, content: nil, toolCalls: [call("call_2")])
- let repeatedResult = GFTokenizer.Message(
- role: .tool, content: "pkg/", toolCallID: "call_2", name: "ls")
- let cachedMessages = [
- GFTokenizer.Message(role: .user, content: "list the tree"),
- first,
- firstResult,
+
+ let otherImage = cache.match(
+ domain: domain,
+ request: request(messages: follow,
+ imageIdentities: [["image-b"], [], []]),
+ renderedPromptIDs: nil, tokenizer: tokenizer)
+ #expect(otherImage.missReason == .imagesDiverged)
+
+ let noImage = cache.match(
+ domain: domain,
+ request: request(messages: follow, imageIdentities: [[], [], []]),
+ renderedPromptIDs: nil, tokenizer: tokenizer)
+ #expect(noImage.missReason == .imagesDiverged)
+ }
+
+ /// A continuation carrying its own image cannot use the text bridge, but the
+ /// cached prefix is still valid, so it resumes after a render instead of
+ /// being discarded.
+ @Test func continuationCarryingItsOwnImageResumesAfterRender() async throws {
+ let tokenizer = try await GFTokenizer.load()
+ let messages = [GFTokenizer.Message(role: .user, content: "describe")]
+ let initial = request(messages: messages, imageIdentities: [["image-a"]])
+ let prompt = tokenizer.encode(
+ try tokenizer.applyChatTemplate(initial.messages), addBOS: false)
+ let kvBacked = prompt + tokenizer.encode("answer", addBOS: false)
+ var cache = ServerPromptCache()
+ cache.publish(
+ domain: domain, request: initial, content: "answer", calls: [],
+ result: rawResult(prompt: prompt, kvBacked: kvBacked,
+ boundary: tokenizer.endOfTurnID, reason: .endOfTurn))
+
+ let follow = messages + [
+ GFTokenizer.Message(role: .assistant, content: "answer"),
+ GFTokenizer.Message(role: .user, content: "and this one"),
]
+ let match = cache.match(
+ domain: domain,
+ request: request(messages: follow,
+ imageIdentities: [["image-a"], [], ["image-b"]]),
+ renderedPromptIDs: nil, tokenizer: tokenizer)
+ // The history and its images match, so this resumes via a render
+ // rather than throwing the cached prefix away.
+ #expect(match == .renderThenResume(cachedPromptTokens: kvBacked.count))
+ }
- let bridge = try tokenizer.encodeToolResultContinuation(
- cachedMessages: cachedMessages,
- assistant: repeated,
- incomingMessages: cachedMessages + [repeated, repeatedResult],
- tools: tools)
+ // MARK: - Image identity revalidation
- // Both twins are followed by a response; only the counts tell a
- // twin-anchored bridge apart.
- #expect(bridge.first == tokenizer.toolResponseID)
- #expect(bridge.filter { $0 == tokenizer.toolResponseID }.count == 1)
- #expect(!bridge.contains(tokenizer.toolCallStartID))
+ /// Publishing after each turn must keep an image conversation reusable
+ /// indefinitely, not only for the first follow-up.
+ @Test func imageConversationKeepsReusingAcrossManyTurns() async throws {
+ let tokenizer = try await GFTokenizer.load()
+ var messages = [GFTokenizer.Message(role: .user, content: "describe")]
+ var identities: [[String]] = [["image-a"]]
+ var cache = ServerPromptCache()
- // A diverged cached history cannot anchor by position and still refuses.
- let diverged = [GFTokenizer.Message(role: .user, content: "list the other tree")]
- + cachedMessages.dropFirst()
- #expect(throws: (any Error).self) {
- try tokenizer.encodeToolResultContinuation(
- cachedMessages: diverged,
- assistant: repeated,
- incomingMessages: cachedMessages + [repeated, repeatedResult],
- tools: tools)
+ var prompt = tokenizer.encode(
+ try tokenizer.applyChatTemplate(messages), addBOS: false)
+ var kvBacked = prompt + tokenizer.encode("answer 0", addBOS: false)
+ cache.publish(
+ domain: domain,
+ request: request(messages: messages, imageIdentities: identities),
+ content: "answer 0", calls: [],
+ result: rawResult(prompt: prompt, kvBacked: kvBacked,
+ boundary: tokenizer.endOfTurnID, reason: .endOfTurn))
+
+ for turn in 1...5 {
+ messages.append(GFTokenizer.Message(
+ role: .assistant, content: "answer \(turn - 1)"))
+ messages.append(GFTokenizer.Message(
+ role: .user, content: "follow up \(turn)"))
+ identities.append([])
+ identities.append([])
+ let follow = request(messages: messages, imageIdentities: identities)
+ let match = cache.match(
+ domain: domain, request: follow,
+ renderedPromptIDs: nil, tokenizer: tokenizer)
+ guard case .hit(let effective, let cached) = match else {
+ Issue.record("turn \(turn) lost the cached image prefix")
+ return
+ }
+ #expect(cached == kvBacked.count)
+ prompt = effective
+ kvBacked = effective + tokenizer.encode("answer \(turn)", addBOS: false)
+ cache.publish(
+ domain: domain, request: follow,
+ content: "answer \(turn)", calls: [],
+ result: rawResult(prompt: prompt, kvBacked: kvBacked,
+ boundary: tokenizer.endOfTurnID,
+ reason: .endOfTurn))
}
}
+ /// Identity must distinguish a message's images by content, by count, and
+ /// by order within the message.
+ @Test func multipleImagesAreDistinguishedByContentCountAndOrder() async throws {
+ let tokenizer = try await GFTokenizer.load()
+ let messages = [GFTokenizer.Message(role: .user, content: "compare")]
+ let all = ["img-1", "img-2", "img-3", "img-4"]
+ let initial = request(messages: messages, imageIdentities: [all])
+ let prompt = tokenizer.encode(
+ try tokenizer.applyChatTemplate(messages), addBOS: false)
+ let kvBacked = prompt + tokenizer.encode("answer", addBOS: false)
+ var cache = ServerPromptCache()
+ cache.publish(
+ domain: domain, request: initial, content: "answer", calls: [],
+ result: rawResult(prompt: prompt, kvBacked: kvBacked,
+ boundary: tokenizer.endOfTurnID, reason: .endOfTurn))
+
+ let follow = messages + [
+ GFTokenizer.Message(role: .assistant, content: "answer"),
+ GFTokenizer.Message(role: .user, content: "again"),
+ ]
+ func match(_ leading: [String]) -> ServerPromptCacheMatch {
+ cache.match(
+ domain: domain,
+ request: request(messages: follow,
+ imageIdentities: [leading, [], []]),
+ renderedPromptIDs: nil, tokenizer: tokenizer)
+ }
+ guard case .hit = match(all) else {
+ Issue.record("identical four-image prefix must reuse")
+ return
+ }
+ #expect(match(["img-1", "img-2", "img-4", "img-3"]).missReason == .imagesDiverged)
+ #expect(match(["img-1", "img-2", "img-3"]).missReason == .imagesDiverged)
+ #expect(match(all + ["img-5"]).missReason == .imagesDiverged)
+ #expect(match(["img-1", "img-9", "img-3", "img-4"]).missReason == .imagesDiverged)
+ }
+
+ /// The same image moved to a different message is a different prompt, even
+ /// though the flattened text and the multiset of images are unchanged.
+ @Test func movingAnImageBetweenMessagesMisses() async throws {
+ let tokenizer = try await GFTokenizer.load()
+ let messages = [
+ GFTokenizer.Message(role: .user, content: "one"),
+ GFTokenizer.Message(role: .assistant, content: "ok"),
+ GFTokenizer.Message(role: .user, content: "two"),
+ ]
+ let initial = request(messages: messages,
+ imageIdentities: [["image-a"], [], []])
+ let prompt = tokenizer.encode(
+ try tokenizer.applyChatTemplate(messages), addBOS: false)
+ let kvBacked = prompt + tokenizer.encode("answer", addBOS: false)
+ var cache = ServerPromptCache()
+ cache.publish(
+ domain: domain, request: initial, content: "answer", calls: [],
+ result: rawResult(prompt: prompt, kvBacked: kvBacked,
+ boundary: tokenizer.endOfTurnID, reason: .endOfTurn))
+
+ let follow = messages + [
+ GFTokenizer.Message(role: .assistant, content: "answer"),
+ GFTokenizer.Message(role: .user, content: "three"),
+ ]
+ let moved = cache.match(
+ domain: domain,
+ request: request(messages: follow,
+ imageIdentities: [[], [], ["image-a"], [], []]),
+ renderedPromptIDs: nil, tokenizer: tokenizer)
+ #expect(moved.missReason == .imagesDiverged)
+ }
+
+ /// A multimodal request whose identity array does not line up with its
+ /// messages must neither publish nor match, since it cannot be told apart
+ /// from a request carrying a different image.
+ @Test func malformedImageIdentityIsFailClosed() async throws {
+ let tokenizer = try await GFTokenizer.load()
+ let messages = [GFTokenizer.Message(role: .user, content: "describe")]
+ let prompt = tokenizer.encode(
+ try tokenizer.applyChatTemplate(messages), addBOS: false)
+ let kvBacked = prompt + tokenizer.encode("answer", addBOS: false)
+ let malformed = ValidatedChatRequest(
+ messages: messages,
+ multimodalMessages: [MultimodalMessage(
+ role: .user, content: [.image(id: UUID()), .text("describe")])],
+ imageFiles: [UUID(): URL(fileURLWithPath: "/dev/null")],
+ imageIdentities: [],
+ tools: [],
+ stream: false,
+ includeUsage: false,
+ generationConfig: GenerationConfig(maxNewTokens: 16, temperature: 0),
+ maximumCompletionTokens: 16)
+
+ var cache = ServerPromptCache()
+ cache.publish(
+ domain: domain, request: malformed, content: "answer", calls: [],
+ result: rawResult(prompt: prompt, kvBacked: kvBacked,
+ boundary: tokenizer.endOfTurnID, reason: .endOfTurn))
+ #expect(cache.entry == nil)
+
+ cache.publish(
+ domain: domain,
+ request: request(messages: messages, imageIdentities: [["image-a"]]),
+ content: "answer", calls: [],
+ result: rawResult(prompt: prompt, kvBacked: kvBacked,
+ boundary: tokenizer.endOfTurnID, reason: .endOfTurn))
+ let follow = messages + [
+ GFTokenizer.Message(role: .assistant, content: "answer"),
+ GFTokenizer.Message(role: .user, content: "again"),
+ ]
+ let malformedFollow = ValidatedChatRequest(
+ messages: follow,
+ multimodalMessages: [MultimodalMessage(
+ role: .user, content: [.image(id: UUID())])],
+ imageFiles: [UUID(): URL(fileURLWithPath: "/dev/null")],
+ imageIdentities: [],
+ tools: [],
+ stream: false,
+ includeUsage: false,
+ generationConfig: GenerationConfig(maxNewTokens: 16, temperature: 0),
+ maximumCompletionTokens: 16)
+ #expect(cache.match(domain: domain, request: malformedFollow,
+ renderedPromptIDs: nil,
+ tokenizer: tokenizer).missReason
+ == .missingImageIdentity)
+ }
+
+ /// A text-only conversation must keep hitting after the image work; the
+ /// identity comparison has to be inert when no image is present.
+ @Test func textOnlyConversationIsUnaffectedByImageIdentity() async throws {
+ let tokenizer = try await GFTokenizer.load()
+ let messages = [GFTokenizer.Message(role: .user, content: "first")]
+ let initial = request(messages: messages)
+ let prompt = tokenizer.encode(
+ try tokenizer.applyChatTemplate(messages), addBOS: false)
+ let kvBacked = prompt + tokenizer.encode("answer", addBOS: false)
+ var cache = ServerPromptCache()
+ cache.publish(
+ domain: domain, request: initial, content: "answer", calls: [],
+ result: rawResult(prompt: prompt, kvBacked: kvBacked,
+ boundary: tokenizer.endOfTurnID, reason: .endOfTurn))
+ let follow = request(messages: messages + [
+ GFTokenizer.Message(role: .assistant, content: "answer"),
+ GFTokenizer.Message(role: .user, content: "second"),
+ ])
+ guard case .hit = cache.match(
+ domain: domain, request: follow,
+ renderedPromptIDs: nil, tokenizer: tokenizer) else {
+ Issue.record("text-only continuation must still reuse the prefix")
+ return
+ }
+ }
+
+ /// Nothing privileges the first turn. An image introduced at turn three is
+ /// prefilled once as a miss, joins the cached prefix, and is reused by every
+ /// later text turn exactly like a turn-one image.
+ @Test func imageIntroducedAtALaterTurnJoinsTheCachedPrefix() async throws {
+ let tokenizer = try await GFTokenizer.load()
+ var cache = ServerPromptCache()
+ var messages = [GFTokenizer.Message(role: .user, content: "turn 1")]
+ var identities: [[String]] = [[]]
+
+ func publish(_ request: ValidatedChatRequest,
+ _ content: String) -> [Int32] {
+ let prompt = (try? tokenizer.applyChatTemplate(request.messages))
+ .map { tokenizer.encode($0, addBOS: false) } ?? []
+ let kvBacked = prompt + tokenizer.encode(content, addBOS: false)
+ cache.publish(
+ domain: domain, request: request, content: content, calls: [],
+ result: rawResult(prompt: prompt, kvBacked: kvBacked,
+ boundary: tokenizer.endOfTurnID,
+ reason: .endOfTurn))
+ return kvBacked
+ }
+
+ // Turns 1 and 2 are text only.
+ _ = publish(request(messages: messages, imageIdentities: identities),
+ "answer 1")
+ messages += [
+ GFTokenizer.Message(role: .assistant, content: "answer 1"),
+ GFTokenizer.Message(role: .user, content: "turn 2"),
+ ]
+ identities += [[], []]
+ _ = publish(request(messages: messages, imageIdentities: identities),
+ "answer 2")
+
+ // Turn 3 introduces an image. The text bridge cannot render it, so this
+ // resumes after a render rather than discarding the prefix.
+ messages += [
+ GFTokenizer.Message(role: .assistant, content: "answer 2"),
+ GFTokenizer.Message(role: .user, content: "look at this"),
+ ]
+ identities += [[], ["image-late"]]
+ let introducing = request(messages: messages, imageIdentities: identities)
+ guard case .renderThenResume = cache.match(
+ domain: domain, request: introducing,
+ renderedPromptIDs: nil, tokenizer: tokenizer) else {
+ Issue.record("introducing an image should resume after a render")
+ return
+ }
+ let kvWithImage = publish(introducing, "answer 3")
+
+ // Turn 4 onward reuses the prefix that now contains the late image.
+ for turn in 4...6 {
+ messages += [
+ GFTokenizer.Message(role: .assistant,
+ content: "answer \(turn - 1)"),
+ GFTokenizer.Message(role: .user, content: "turn \(turn)"),
+ ]
+ identities += [[], []]
+ let follow = request(messages: messages, imageIdentities: identities)
+ guard case .hit(let effective, let cached) = cache.match(
+ domain: domain, request: follow,
+ renderedPromptIDs: nil, tokenizer: tokenizer) else {
+ Issue.record("turn \(turn) lost the late image prefix")
+ return
+ }
+ if turn == 4 { #expect(cached == kvWithImage.count) }
+ let kvBacked = effective + tokenizer.encode("answer \(turn)",
+ addBOS: false)
+ cache.publish(
+ domain: domain, request: follow, content: "answer \(turn)",
+ calls: [],
+ result: rawResult(prompt: effective, kvBacked: kvBacked,
+ boundary: tokenizer.endOfTurnID,
+ reason: .endOfTurn))
+ }
+
+ // And the late image is still identity-checked, not merely carried.
+ messages += [
+ GFTokenizer.Message(role: .assistant, content: "answer 6"),
+ GFTokenizer.Message(role: .user, content: "turn 7"),
+ ]
+ var swapped = identities + [[], []]
+ swapped[5] = ["image-other"]
+ #expect(cache.match(
+ domain: domain,
+ request: request(messages: messages, imageIdentities: swapped),
+ renderedPromptIDs: nil,
+ tokenizer: tokenizer).missReason == .imagesDiverged)
+ }
+
+ /// The rendered-prefix fast path must not be usable for an image request:
+ /// placeholder tokens are identical whatever image they stand for, so
+ /// rendered ids cannot tell two images apart. Previously this was safe only
+ /// because the caller passed nil for multimodal requests.
+ @Test func renderedPrefixFastPathRefusesImageRequests() async throws {
+ let tokenizer = try await GFTokenizer.load()
+ let messages = [GFTokenizer.Message(role: .user, content: "describe")]
+ let initial = request(messages: messages, imageIdentities: [["image-a"]])
+ let prompt = tokenizer.encode(
+ try tokenizer.applyChatTemplate(messages), addBOS: false)
+ let kvBacked = prompt + tokenizer.encode("answer", addBOS: false)
+ var cache = ServerPromptCache()
+ cache.publish(
+ domain: domain, request: initial, content: "answer", calls: [],
+ result: rawResult(prompt: prompt, kvBacked: kvBacked,
+ boundary: tokenizer.endOfTurnID, reason: .endOfTurn))
+
+ // Same rendered ids, different image: the fast path would hit on tokens
+ // alone, so it must be refused.
+ let follow = messages + [
+ GFTokenizer.Message(role: .assistant, content: "answer"),
+ GFTokenizer.Message(role: .user, content: "again"),
+ ]
+ let rendered = kvBacked + tokenizer.encodeTextContinuation(userContent: "again")
+ let other = cache.match(
+ domain: domain,
+ request: request(messages: follow,
+ imageIdentities: [["image-b"], [], []]),
+ renderedPromptIDs: rendered, tokenizer: tokenizer)
+ #expect(other.missReason == .imagesDiverged)
+ }
+
private func request(
messages: [GFTokenizer.Message],
- tools: [GFTokenizer.FunctionDefinition] = []
+ tools: [GFTokenizer.FunctionDefinition] = [],
+ imageIdentities: [[String]] = []
) -> ValidatedChatRequest {
ValidatedChatRequest(
messages: messages,
+ imageIdentities: imageIdentities,
tools: tools,
stream: false,
includeUsage: false,
diff --git a/Tests/TurboFieldfareServer/StreamingChatRequestBodyTests.swift b/Tests/TurboFieldfareServer/StreamingChatRequestBodyTests.swift
new file mode 100644
index 00000000..81ede49a
--- /dev/null
+++ b/Tests/TurboFieldfareServer/StreamingChatRequestBodyTests.swift
@@ -0,0 +1,119 @@
+import Foundation
+import NIOCore
+import Testing
+@testable import TurboFieldfareServerCore
+
+@Suite struct StreamingChatRequestBodyTests {
+ @Test func extractsImageBase64AcrossArbitraryChunks() throws {
+ let source = Data(#"{"model":"m","messages":[{"role":"user","content":[{"type":"image_url","image_url":{"url":"data:image/png;base64,YWJj","detail":"auto"}},{"type":"text","text":"describe"}]}]}"#.utf8)
+ let parser = StreamingChatRequestBody()
+ var offset = 0
+ for size in [1, 2, 3, 5, 8, 13, 21] {
+ while offset < source.count {
+ let end = min(source.count, offset + size)
+ var buffer = ByteBuffer(bytes: source[offset..<end])
+ try parser.feed(&buffer)
+ offset = end
+ if end == source.count { break }
+ }
+ if offset == source.count { break }
+ }
+ let parsed = try parser.finish()
+ #expect(!String(decoding: parsed.json, as: UTF8.self).contains("YWJj"))
+ let staged = try #require(parsed.stagedImages.values.first)
+ #expect(try Data(contentsOf: staged.fileURL) == Data("abc".utf8))
+
+ let request = try JSONDecoder().decode(OpenAIChatRequest.self, from: parsed.json)
+ let validated = try OpenAIRequestValidator.validate(
+ request,
+ modelID: "m",
+ preStagedImages: parsed.stagedImages,
+ attachmentLease: parsed.lease)
+ #expect(validated.multimodalMessages?.count == 1)
+ #expect(validated.imageFiles.count == 1)
+ }
+
+ /// A spec-valid serializer may escape the solidus (PHP's json_encode does
+ /// by default) or write payload characters as \u escapes; both must stage
+ /// the same bytes as the unescaped form.
+ @Test func decodesJSONEscapesInsideImageDataURLs() throws {
+ let source = Data(#"{"model":"m","messages":[{"role":"user","content":[{"type":"image_url","image_url":{"url":"data:image\/png;base64,YWJj"}}]}]}"#.utf8)
+ let parser = StreamingChatRequestBody()
+ var buffer = ByteBuffer(bytes: source)
+ try parser.feed(&buffer)
+ let parsed = try parser.finish()
+ let staged = try #require(parsed.stagedImages.values.first)
+ #expect(try Data(contentsOf: staged.fileURL) == Data("abc".utf8))
+
+ let unicodeJSON = #"{"model":"m","messages":[{"role":"user","content":"#
+ + #"[{"type":"image_url","image_url":{"url":"data:image/png;base64,\u0059WJj"}}]}]}"#
+ let unicodeSource = Data(unicodeJSON.utf8)
+ let unicodeParser = StreamingChatRequestBody()
+ var unicodeBuffer = ByteBuffer(bytes: unicodeSource)
+ try unicodeParser.feed(&unicodeBuffer)
+ let unicodeParsed = try unicodeParser.finish()
+ let unicodeStaged = try #require(unicodeParsed.stagedImages.values.first)
+ #expect(try Data(contentsOf: unicodeStaged.fileURL) == Data("abc".utf8))
+ }
+
+ /// Padding must terminate the payload, and the answer must not depend on
+ /// how the wire happened to chunk the bytes: mid-stream padding is always
+ /// rejected, terminal padding always accepted.
+ @Test func base64PaddingHandlingIsChunkingIndependent() throws {
+ func parse(_ payload: String, chunk: Int) throws -> ParsedChatRequestBody {
+ let source = Data(#"{"model":"m","messages":[{"role":"user","content":[{"type":"image_url","image_url":{"url":"data:image/png;base64,\#(payload)"}}]}]}"#.utf8)
+ let parser = StreamingChatRequestBody()
+ var offset = 0
+ while offset < source.count {
+ let end = min(source.count, offset + chunk)
+ var buffer = ByteBuffer(bytes: source[offset..<end])
+ try parser.feed(&buffer)
+ offset = end
+ }
+ return try parser.finish()
+ }
+ for chunk in [1, 3, 7, 64, 4_096] {
+ #expect(throws: ServerRequestError.self, "chunk \(chunk)") {
+ _ = try parse("AA==AAAA", chunk: chunk)
+ }
+ let parsed = try parse("QUJDRA==", chunk: chunk)
+ let staged = try #require(parsed.stagedImages.values.first)
+ #expect(try Data(contentsOf: staged.fileURL) == Data("ABCD".utf8))
+ }
+ }
+
+ /// A non-data URL with escapes is not staged and must pass through with
+ /// its original bytes, not the decoded ones.
+ @Test func escapedNonDataURLsPassThroughVerbatim() throws {
+ let source = Data(#"{"model":"m","messages":[{"role":"user","content":[{"type":"image_url","image_url":{"url":"https:\/\/example.com\/a.png"}}]}]}"#.utf8)
+ let parser = StreamingChatRequestBody()
+ var buffer = ByteBuffer(bytes: source)
+ try parser.feed(&buffer)
+ let parsed = try parser.finish()
+ #expect(parsed.json == source)
+ #expect(parsed.stagedImages.isEmpty)
+ }
+
+ /// An image_url-shaped object outside messages[].content[] — here inside a
+ /// tool schema — is someone else's data and must not be staged, rewritten,
+ /// or rejected.
+ @Test func imageURLShapesOutsideMessageContentAreUntouched() throws {
+ let source = Data(#"{"model":"m","messages":[{"role":"user","content":"hi"}],"tools":[{"type":"function","function":{"name":"f","parameters":{"type":"object","example":{"image_url":{"url":"data:image/png;base64,YWJj"}}}}}]}"#.utf8)
+ let parser = StreamingChatRequestBody()
+ var buffer = ByteBuffer(bytes: source)
+ try parser.feed(&buffer)
+ let parsed = try parser.finish()
+ #expect(parsed.json == source)
+ #expect(parsed.stagedImages.isEmpty)
+ }
+
+ @Test func leavesDataURLTextUntouched() throws {
+ let source = Data(#"{"model":"m","messages":[{"role":"user","content":"data:image/png;base64,YWJj"}]}"#.utf8)
+ let parser = StreamingChatRequestBody()
+ var buffer = ByteBuffer(bytes: source)
+ try parser.feed(&buffer)
+ let parsed = try parser.finish()
+ #expect(parsed.json == source)
+ #expect(parsed.stagedImages.isEmpty)
+ }
+}
diff --git a/docs/OPENAI_SERVER.md b/docs/OPENAI_SERVER.md
index 212a2106..8728460a 100644
--- a/docs/OPENAI_SERVER.md
+++ b/docs/OPENAI_SERVER.md
@@ -106,6 +106,11 @@ OpenCode:
"models": {
"gemma-4-26b-a4b-it": {
"name": "Gemma 4 26B-A4B IT",
+ "attachment": true,
+ "modalities": {
+ "input": ["text", "image"],
+ "output": ["text"]
+ },
"limit": {
"context": 16384,
"output": 4096
@@ -119,6 +124,13 @@ OpenCode:
Select `turbofieldfare/gemma-4-26b-a4b-it` in OpenCode.
+`attachment` and `modalities` are what make images work. OpenCode decides whether
+a model accepts images from this configuration, not from the `capabilities` field
+`/v1/models` returns, so without them it refuses an image with "this model does
+not support image input" before sending anything. Images then reach the server
+through OpenCode's `read` tool, which returns image files as attachments; ask it
+to read the file explicitly.
+
Pi uses its `openai-completions` adapter:
```json
@@ -137,6 +149,7 @@ Pi uses its `openai-completions` adapter:
"id": "gemma-4-26b-a4b-it",
"name": "Gemma 4 26B-A4B IT",
"reasoning": false,
+ "input": ["text", "image"],
"contextWindow": 16384,
"maxTokens": 4096
}]
@@ -147,6 +160,12 @@ Pi uses its `openai-completions` adapter:
Keep the client context setting at or below the server's `--max-context`.
+Pi's `input` field declares image support the same way OpenCode's `modalities`
+does. With it, `pi -p @photo.png "What is in this image?"` sends the image as a
+base64 data URL in an `image_url` part, which is the shape this server accepts;
+its RPC interface takes an explicit `images` array and produces the same
+request.
+
## Prompt reuse
Single-prefix KV reuse is on by default. Send the complete message history with
@@ -204,7 +223,7 @@ Supported options include `temperature`, `top_p`, `top_k`,
`max_completion_tokens`, and function-tool fields.
The server supports one model and one choice. It does not support the Responses
-API, legacy Completions, embeddings, multimodal input, structured output,
+API, legacy Completions, embeddings, structured output,
batching, log probabilities, or remote model switching.
Context length can be 4K, 8K, 16K, 32K, or 64K. The default is 16K. Larger FP16
@@ -214,3 +233,23 @@ watch memory pressure.
For long requests, stderr reports the request lifecycle as prepared, queued,
generating, completed, or failed. It includes token counts and timing, but not
prompt text, tool arguments, headers, or request bodies.
+
+## Images
+
+`messages[].content` accepts `image_url` parts in user messages. An
+`image_url` on any other role returns HTTP 400. The URL must be a data URL,
+and `detail` must be absent or set to `auto`.
+
+Image bytes go to disk as the request body arrives, so a large upload does not
+sit in memory. Before any pixel is decoded, the server works out how many
+tokens the images will occupy and rejects the request if they do not fit the
+context. Bodies and images over their limits return HTTP 413.
+
+`GET /v1/models` reports `capabilities` as `["text", "image"]` when a valid
+companion pack is loaded and `["text"]` otherwise. `GET /health` reports the
+same state under `vision`, as `ready`, `missing`, `invalid`, or `unsupported`.
+`unsupported` means the image tower cannot run on this Mac; it requires M2 or
+newer. Text requests remain available.
+
+Choose the pack and the residency policy with `--vision-pack <dir>` and
+`--vision-residency on-demand|keep-ready`.
diff --git a/docs/OPTIMIZATION_JOURNEY.md b/docs/OPTIMIZATION_JOURNEY.md
index 1fdc81f0..29626a4c 100644
--- a/docs/OPTIMIZATION_JOURNEY.md
+++ b/docs/OPTIMIZATION_JOURNEY.md
@@ -1,7 +1,7 @@
# Optimizing a 14.3 GB model for an 8 GB machine
TurboFieldfare runs Gemma 4 26B-A4B on an 8 GB Apple Silicon machine. Its
-text-only installation, without the vision tower, is about 14.3 GB. The model
+text installation, without the optional image pack, is about 14.3 GB. The model
was never going to fit politely in memory.
Instead, the runtime keeps 1.35 GB of common model weights available to Metal
diff --git a/docs/RUNTIME_CONTROLS.md b/docs/RUNTIME_CONTROLS.md
index 67d029d4..3e45441f 100644
--- a/docs/RUNTIME_CONTROLS.md
+++ b/docs/RUNTIME_CONTROLS.md
@@ -12,7 +12,7 @@ The Mac app and CLI expose these generation controls:
| Control | Mac values | CLI flag | Default | Effect |
| --- | --- | --- | --- | --- |
| Maximum response | Automatic | `--max-new` | App: remaining context; CLI: 1,024 tokens | The app can use the context space left after formatting the prompt. The CLI uses its explicit or default `--max-new` limit. |
-| Maximum context | 4K, 8K, 16K, 32K, 64K | `--max-context` | 4K | Sets prompt plus response capacity. The app shows the FP16 KV-memory delta. |
+| Maximum context | 4K, 8K, 16K, 32K, 64K | `--max-context` | CLI and app: 8K; server: 16K | Sets prompt plus response capacity, and 8K is what leaves room for an image and its prompt. The app shows the FP16 KV-memory delta. The server defaults higher still because agent clients routinely send prompts near 8K on their own. |
| Temperature | 0...2 in 0.05 steps | `--temperature` | 0.2 | `0` is greedy; positive values sample. |
| Top-K | Off or 1...256 | `--top-k` | 64 | Keeps at most K candidates. CLI `0` turns it off. |
| Top-P | Off or 0.01...1 | `--top-p` | 0.95 | Applies nucleus truncation before Top-K and is effective only while Top-K is enabled. |
@@ -26,7 +26,8 @@ benchmark protocol.
## Runtime settings
The CLI and the [local server](OPENAI_SERVER.md) accept these flags with the
-same names, values, and defaults. The server resolves them before it loads the
+same names and values. Their defaults agree except for `--max-context`, which
+the server defaults to 16,384 rather than 8,192. The server resolves them before it loads the
model, so an unsupported combination fails immediately with the usage text.
| Control | Mac values | CLI and server flag | Production default | Effect |
@@ -34,7 +35,7 @@ model, so an unsupported combination fails immediately with the usage text.
| Expert-cache slots | 8, 16, 24, 32 | `--expert-cache-slots` | 16 | More slots can retain more routed experts and reduce later reads, but values above 16 use more RAM. Chunked prefill requires at least 16 slots. |
| Expert-cache policy | LFU | `--expert-cache-policy lfu\|lru` | LFU | Chooses which expert is evicted when the cache is full. |
| Prompt prefill | On, off | `--prefill on\|off` | On | On processes known prompt tokens through the chunked prefill path. Off disables that path. |
-| Prefill chunk size | 128 | `--prefill-chunk-tokens 32\|64\|128` | 128 | Sets the number of prompt tokens processed by each chunked-prefill step. It has no effect while prefill is off. |
+| Prefill chunk size | 128 | `--prefill-chunk-tokens 32\|64\|128\|256\|auto` | 128 | Sets the number of prompt tokens processed by each chunked-prefill step, and has no effect while prefill is off. Chunks loop outside layers, so each one re-reads that layer's routed experts: fewer, larger chunks read less. `auto` picks the smallest size that covers the prompt. On a 7,019-token prompt, 256 measured 16% faster than 128 with byte-identical output. |
| RDADVISE | Off, Default, Bounded, Adaptive | `--rdadvise off\|default\|bounded\|adaptive` | Off | Applies experimental read advice. Its effect depends on the workload; it may help a short decode and slow a long one. |
In the app, changing context length, expert-cache slots, or RDADVISE requires a
@@ -44,9 +45,27 @@ each request and do not require a reload. Each CLI invocation loads a new model
process, so its selected runtime settings apply immediately. The server fixes
its runtime settings at startup, so changing one means restarting the process.
+## Image controls
+
+Image input needs the companion pack installed beside the text model. Without
+it, these controls have nothing to select.
+
+| Control | Values | Default | Effect |
+| --- | --- | --- | --- |
+| Vision pack | directory | `<model>.vision.gturbo` beside the model | Where the companion pack is read from. If you pass a path that does not exist, the load fails. It does not fall back to serving text with the images missing. |
+| Vision residency | `on-demand`, `keep-ready` | `on-demand` | `on-demand` releases the routed-expert streamers and their slot scratch before encoding, then recreates them for language prefill. `keep-ready` maps the tower during the load and leaves it mapped. Changing this requires a reload. |
+
+The CLI takes `--vision-pack` and `--vision-residency`, plus `--image <path>`,
+which is repeatable, and `--chat-prompt`. The server takes the first two.
+
+A request whose images cannot fit the selected context is refused before any
+pixel is decoded. The rejection reports the token cost, not the number of
+images, because an image's cost scales with its dimensions.
+
## Run an experiment
-1. Start from 4K context, 16 expert-cache slots, prefill on, and RDADVISE off.
+1. Start from the 8K default context, 16 expert-cache slots, prefill on, and
+ RDADVISE off.
2. Keep the prompt and generation controls fixed.
3. Record a baseline after a warmup.
4. Change one runtime control and reload the app model, or start a new CLI run.
diff --git a/docs/SYSTEM_DESIGN.md b/docs/SYSTEM_DESIGN.md
index a8c2e10e..0903b327 100644
--- a/docs/SYSTEM_DESIGN.md
+++ b/docs/SYSTEM_DESIGN.md
@@ -1,7 +1,7 @@
# System design
TurboFieldfare is a Swift and Metal runtime for Gemma 4 26B-A4B on Apple
-Silicon. The text-only installation is about 14.3 GB, but the target machine
+Silicon. The text installation is about 14.3 GB, but the target machine
has 8 GB of memory. The runtime keeps the common weights and working state
available to Metal. It stores routed experts in per-layer files and reads only
the experts chosen for the current token or prefill chunk.
@@ -241,7 +241,7 @@ flowchart LR
## Instruction framing
-The Mac app and CLI `--messages-file` mode use the pinned text-only Gemma 4 chat
+The Mac app and CLI `--messages-file` mode use the pinned Gemma 4 chat
format. The app wraps one user prompt. `--messages-file` accepts user and
assistant messages plus optional leading system guidance. Assistant messages
render with Gemma's `model` role. The separate loopback server uses the pinned
@@ -437,14 +437,16 @@ references lead to the supporting code and tests.
## Scope and limitations
-The current runtime supports text-only generation with the pinned Gemma 4
-26B-A4B instruction checkpoint. The source model supports image input, but
-TurboFieldfare omits its vision tower.
+The current runtime supports text and image input with the pinned Gemma 4
+26B-A4B instruction checkpoint. Image support is optional. The vision tower
+and projector live in a separate companion pack, so an installation without
+that pack has the footprint it had before. The image tower requires M2 or
+newer; text-only inference remains available on M1. See [Images](#images).
-The Mac app offers 4K, 8K, 16K, 32K, and 64K context lengths. Published app
-and CLI acceptance evidence covers up to 4K. Vision input, training,
-fine-tuning, server batching, remote serving, and general model support are
-outside the current scope. The optional HTTP server is loopback-only, owns one
+The Mac app offers 4K, 8K, 16K, 32K, and 64K context lengths. Manual acceptance
+covers the Mac app at 8K and CLI stress at 64K. Audio input, video input,
+training, fine-tuning, server batching, remote serving, and general model
+support are outside the current scope. The optional HTTP server is loopback-only, owns one
warm model, serializes generation, and retains one verified conversational KV
prefix by default. It retains only that prefix. See the
[local server guide](OPENAI_SERVER.md).
@@ -462,3 +464,50 @@ default.
- [The experiments that shaped TurboFieldfare](OPTIMIZATION_JOURNEY.md)
- [Complete experiment inventory](experiments/EXPERIMENT_INVENTORY.md)
- [Implementation references](IMPLEMENTATION_REFERENCES.md)
+
+## Images
+
+Image support ships as a companion pack, `<name>.vision.gturbo`, installed
+beside the text model. The pack's manifest records the SHA-256 of the text
+manifest it was built against, so a pack cannot be used with a model it does
+not match. When the pack is absent or fails verification, the text runtime
+runs unchanged and image input is unavailable.
+
+Preprocessing reads the image header before anything else. Orientation, colour
+space, and pixel dimensions come from metadata, and the number of tokens an
+image will occupy follows from its dimensions. A request whose images cannot
+fit the selected context is rejected at that point, before any pixel is
+decoded.
+
+The tower then runs on bounded scratch. Attention is tiled with an online
+softmax, so the full attention matrix is never allocated. The runtime keeps
+the projected features and releases the rest.
+
+Projected features enter the language model as whole spans of rows. Within the
+25 sliding-window layers, the rows of one image attend to each other in both
+directions. The 5 full-attention layers stay causal, and text rows stay causal
+in every layer. An image span prefills as one chunk, so it is never split
+across a chunk boundary. The chunk scratch and the KV ring are sized for the
+largest pooled span rather than for the text chunk size.
+
+Two residency policies decide what the tower costs while it is idle.
+
+Load on demand is the default. Before encoding, the runtime releases the
+routed-expert streamers and their slot scratch, then recreates them for
+language prefill. This is what stops the tower and the expert cache from being
+resident at the same time on an 8 GB machine.
+
+Keep ready maps the tower during the load and leaves it mapped. It spends
+memory to save latency on repeated image work. Page advice is not a guarantee
+of residency; the operating system can still reclaim those pages.
+
+Large images remain metadata-bounded: at most 50 million source pixels, 32,768
+pixels on either side, and 200,000,000 decoded bytes for one surface. This
+admits an 8-bit 8,000x6,000 camera image while rejecting sources beyond the
+pixel boundary before decode.
+
+In one functional pass on the 8 GB M2, 48 MP JPEG and PNG completed under both
+residency policies at 2,224 to 2,229 MiB peak footprint. Per-row system
+swapouts ranged from 0 to 383 MiB. Five smaller images at a 64K context
+completed at 3,357 MiB footprint with 425 MiB of swapouts. These figures are
+observed costs, not rejection thresholds; on-demand remains the default.