Skip to content

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

Expose CLI runtime controls and harden Metal failures (#100)

Andrey Mikhaylov417f38934c75
diff --git a/README.md b/README.md
index 1326100c..41261e18 100644
--- a/README.md
+++ b/README.md
@@ -228,8 +228,10 @@ generate until the selected context window is full.
Common generation options include `--max-context`, `--temperature`, `--top-k`,
`--top-p`, `--repetition-penalty`, `--seed`, and repeatable `--stop` strings.
-The public CLI uses production runtime defaults. Run the following command for
-the complete option list:
+Runtime options include `--expert-cache-slots`, `--expert-cache-policy`,
+`--prefill`, `--prefill-chunk-tokens`, and `--rdadvise`; omitted options use
+the [production defaults](docs/RUNTIME_CONTROLS.md). Run the following command
+for the complete option list:
```bash
swift run -c release TurboFieldfareCLI --help
diff --git a/Sources/TurboFieldfare/Infrastructure/Metal/MetalContext.swift b/Sources/TurboFieldfare/Infrastructure/Metal/MetalContext.swift
index 450c1513..2151b89e 100644
--- a/Sources/TurboFieldfare/Infrastructure/Metal/MetalContext.swift
+++ b/Sources/TurboFieldfare/Infrastructure/Metal/MetalContext.swift
@@ -19,6 +19,12 @@ enum MetalError: Error, CustomStringConvertible {
}
}
+func checkCommandBufferError(_ error: (any Error)?) throws {
+ if let error {
+ throw error
+ }
+}
+
public struct MetalFunctionConstant: Hashable, Sendable {
public enum Value: Hashable, Sendable {
case bool(Bool)
diff --git a/Sources/TurboFieldfare/Runtime/Configuration/RuntimeConfiguration.swift b/Sources/TurboFieldfare/Runtime/Configuration/RuntimeConfiguration.swift
index d7b0c543..9533cac7 100644
--- a/Sources/TurboFieldfare/Runtime/Configuration/RuntimeConfiguration.swift
+++ b/Sources/TurboFieldfare/Runtime/Configuration/RuntimeConfiguration.swift
@@ -22,6 +22,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 minimumExpertCacheSlotsForChunkedPrefill = 16
public let expertCacheSlots: Int
public let expertCachePolicy: RuntimeExpertCachePolicy
diff --git a/Sources/TurboFieldfare/Runtime/Generation/RawCompletion.swift b/Sources/TurboFieldfare/Runtime/Generation/RawCompletion.swift
index 1086a86c..3bae8cae 100644
--- a/Sources/TurboFieldfare/Runtime/Generation/RawCompletion.swift
+++ b/Sources/TurboFieldfare/Runtime/Generation/RawCompletion.swift
@@ -188,14 +188,14 @@ public func runRawCompletion(producer: any LogitProducer,
case .greedyToken(let token):
tokenID = Int32(bitPattern: token)
case .logitsWritten:
- tokenID = sampleOnce(scratch: scratch, context: context,
- history: history, config: config, position: generated)
+ tokenID = try sampleOnce(scratch: scratch, context: context,
+ history: history, config: config, position: generated)
}
} else if fusedGreedy {
tokenID = Int32(bitPattern: fusedRunner!.lastGreedyToken)
} else {
- tokenID = sampleOnce(scratch: scratch, context: context,
- history: history, config: config, position: generated)
+ tokenID = try sampleOnce(scratch: scratch, context: context,
+ history: history, config: config, position: generated)
}
generated += 1
uncommittedBoundaryTokenIDs = [tokenID]
@@ -245,11 +245,12 @@ public func runRawCompletion(producer: any LogitProducer,
}
private func sampleOnce(scratch: RawCompletionScratch, context: MetalContext,
- history: [Int32], config: GenerationConfig, position: Int) -> Int32 {
+ history: [Int32], config: GenerationConfig, position: Int) throws -> Int32 {
let cb = context.queue.makeCommandBuffer()!
scratch.sampler.sample(commandBuffer: cb, logits: scratch.logits, probs: scratch.probs,
history: history, config: config, position: position,
outToken: scratch.outToken)
cb.commit(); cb.waitUntilCompleted()
+ try checkCommandBufferError(cb.error)
return Int32(bitPattern: scratch.outToken.contents().load(as: UInt32.self))
}
diff --git a/Sources/TurboFieldfare/Runtime/Inference/RealForwardRunner.swift b/Sources/TurboFieldfare/Runtime/Inference/RealForwardRunner.swift
index 4d33a6cd..04b652e8 100644
--- a/Sources/TurboFieldfare/Runtime/Inference/RealForwardRunner.swift
+++ b/Sources/TurboFieldfare/Runtime/Inference/RealForwardRunner.swift
@@ -940,10 +940,7 @@ public final class RealForwardRunner: ChunkedPrefillRunner, ContextWindowReporti
hiddenStrideElements: UInt32(D))
cb.commit()
- waitForCompletion(cb)
- if let error = cb.error {
- throw error
- }
+ try waitForCompletion(cb)
let routeCount = t * cfg.topKExperts
let idPtr = scratch.routeIDs.contents()
@@ -1008,10 +1005,7 @@ public final class RealForwardRunner: ChunkedPrefillRunner, ContextWindowReporti
d: UInt32(D),
eps: eps)
sharedCB.commit()
- waitForCompletion(sharedCB)
- if let error = sharedCB.error {
- throw error
- }
+ try waitForCompletion(sharedCB)
let metadata = try prefillGroupedMoE.makeStreamedMetadataBuffers(
device: ctx.device,
@@ -1028,11 +1022,8 @@ public final class RealForwardRunner: ChunkedPrefillRunner, ContextWindowReporti
func drainOldestPendingTile() throws {
guard !pendingTiles.isEmpty else { return }
let pending = pendingTiles.removeFirst()
- withExtendedLifetime((pending.fetch, pending.argumentBuffer)) {
- waitForCompletion(pending.commandBuffer)
- }
- if let error = pending.commandBuffer.error {
- throw error
+ try withExtendedLifetime((pending.fetch, pending.argumentBuffer)) {
+ try waitForCompletion(pending.commandBuffer)
}
if !pending.fetch.plannedMissSlots.isEmpty {
try tileLifetime.complete(tileIndex: pending.tileIndex)
@@ -1182,11 +1173,8 @@ public final class RealForwardRunner: ChunkedPrefillRunner, ContextWindowReporti
eps: eps,
layerScalar: Quantization.bf16ToFloat(scalarBits))
tailCB.commit()
- withExtendedLifetime(metadata) {
- waitForCompletion(tailCB)
- }
- if let error = tailCB.error {
- throw error
+ try withExtendedLifetime(metadata) {
+ try waitForCompletion(tailCB)
}
if L + 1 < cfg.numLayers {
guard let nextCB = ctx.queue.makeCommandBuffer() else {
@@ -1239,10 +1227,7 @@ public final class RealForwardRunner: ChunkedPrefillRunner, ContextWindowReporti
rmsEps: eps)
}
finalCB.commit()
- waitForCompletion(finalCB)
- if let error = finalCB.error {
- throw error
- }
+ try waitForCompletion(finalCB)
if outputMode == .greedyIfAvailable, useFusedGreedyHead {
lastGreedyToken = greedyTokenBuf.contents().load(as: UInt32.self)
}
@@ -1279,30 +1264,23 @@ public final class RealForwardRunner: ChunkedPrefillRunner, ContextWindowReporti
var pendingRoutedCommand: PendingRoutedCommand?
func finishPendingRoutedCommand(_ pending: PendingRoutedCommand,
- waitIfNeeded: Bool) {
+ waitIfNeeded: Bool) throws {
if waitIfNeeded {
- func wait(_ cb: MTLCommandBuffer) {
- waitForCompletion(cb)
- }
if let sharedCB = pending.sharedCB {
- wait(sharedCB)
+ waitUntilCompleted(sharedCB)
}
if let phase1HitCB = pending.phase1HitCB {
- wait(phase1HitCB)
+ waitUntilCompleted(phase1HitCB)
}
- wait(pending.cb)
- } else if let err = pending.cb.error {
- print("CB error: \(err)")
+ waitUntilCompleted(pending.cb)
}
if let sharedCB = pending.sharedCB {
- if let err = sharedCB.error {
- print("CB error: \(err)")
- }
+ try checkCommandBufferError(sharedCB.error)
}
- if let phase1HitCB = pending.phase1HitCB,
- let err = phase1HitCB.error {
- print("CB error: \(err)")
+ if let phase1HitCB = pending.phase1HitCB {
+ try checkCommandBufferError(phase1HitCB.error)
}
+ try checkCommandBufferError(pending.cb.error)
totalCb2Nanos &+= pending.encodeAndCommitNanos
}
@@ -1314,7 +1292,7 @@ public final class RealForwardRunner: ChunkedPrefillRunner, ContextWindowReporti
// Embed lookup + sqrt(H) fused.
let emb = model.embedding
do {
- runSync { cb in
+ try runSync { cb in
embedInt4.encode(commandBuffer: cb,
table: emb.buffer, tableOffset: Int(emb.offset),
scales: emb.buffer, scalesOffset: Int(emb.scaleOffset),
@@ -1491,12 +1469,13 @@ public final class RealForwardRunner: ChunkedPrefillRunner, ContextWindowReporti
gRouter(cb)
cb.commit()
let tWait = clock_gettime_nsec_np(CLOCK_UPTIME_RAW)
- waitForCompletion(cb)
+ waitUntilCompleted(cb)
let waitNanos = clock_gettime_nsec_np(CLOCK_UPTIME_RAW) - tWait
if let pending = pendingRoutedCommand {
- finishPendingRoutedCommand(pending, waitIfNeeded: false)
+ try finishPendingRoutedCommand(pending, waitIfNeeded: false)
pendingRoutedCommand = nil
}
+ try checkCommandBufferError(cb.error)
totalCb1Nanos &+= clock_gettime_nsec_np(CLOCK_UPTIME_RAW) - tCb1Start - waitNanos
// CPU readback to fetch routed-expert blobs from disk.
@@ -1714,7 +1693,7 @@ public final class RealForwardRunner: ChunkedPrefillRunner, ContextWindowReporti
continue
}
if let pending = pendingRoutedCommand {
- finishPendingRoutedCommand(pending, waitIfNeeded: true)
+ try finishPendingRoutedCommand(pending, waitIfNeeded: true)
pendingRoutedCommand = nil
}
@@ -1750,11 +1729,11 @@ public final class RealForwardRunner: ChunkedPrefillRunner, ContextWindowReporti
let useFusedHeadForThisToken = useFusedGreedyHead && outputMode == .greedyIfAvailable
let tHead = clock_gettime_nsec_np(CLOCK_UPTIME_RAW)
if useFusedHeadForThisToken {
- runSync(gFusionHead)
+ try runSync(gFusionHead)
totalHeadFusedNanos &+= clock_gettime_nsec_np(CLOCK_UPTIME_RAW) - tHead
lastGreedyToken = greedyTokenBuf.contents().load(as: UInt32.self)
} else {
- runSync { cb in
+ try runSync { cb in
gFinalNorm(cb)
gLmHead(cb)
}
@@ -1765,21 +1744,20 @@ public final class RealForwardRunner: ChunkedPrefillRunner, ContextWindowReporti
kv?.advance()
}
- private func runSync(_ body: (MTLCommandBuffer) -> Void) {
+ private func runSync(_ body: (MTLCommandBuffer) -> Void) throws {
let cb = ctx.queue.makeCommandBuffer()!
body(cb)
cb.commit()
- cb.waitUntilCompleted()
- if let err = cb.error {
- print("CB error: \(err)")
- }
+ try waitForCompletion(cb)
}
- private nonisolated func waitForCompletion(_ cb: MTLCommandBuffer) {
+ private nonisolated func waitForCompletion(_ cb: MTLCommandBuffer) throws {
+ waitUntilCompleted(cb)
+ try checkCommandBufferError(cb.error)
+ }
+
+ private nonisolated func waitUntilCompleted(_ cb: MTLCommandBuffer) {
cb.waitUntilCompleted()
- if let err = cb.error {
- print("CB error: \(err)")
- }
}
}
diff --git a/Sources/TurboFieldfareCLI/Args.swift b/Sources/TurboFieldfareCLI/Args.swift
index 6fb33094..0f20db8a 100644
--- a/Sources/TurboFieldfareCLI/Args.swift
+++ b/Sources/TurboFieldfareCLI/Args.swift
@@ -1,3 +1,5 @@
+import TurboFieldfare
+
public struct Args: Equatable, Sendable {
public var model: String
public var prompt: String?
@@ -11,6 +13,11 @@ public struct Args: Equatable, Sendable {
public var seed: UInt64?
public var stops: [String]
public var quiet: Bool
+ public var expertCacheSlots: Int
+ public var expertCachePolicy: RuntimeExpertCachePolicy
+ public var prefillPolicy: RuntimePrefillPolicy
+ public var prefillChunkTokens: Int
+ public var rdadvisePolicy: RDAdvicePolicyMode
public init(model: String,
prompt: String? = nil,
@@ -23,7 +30,12 @@ public struct Args: Equatable, Sendable {
repetitionPenalty: Float = 1.0,
seed: UInt64? = nil,
stops: [String] = [],
- quiet: Bool = false) {
+ quiet: Bool = false,
+ expertCacheSlots: Int = RuntimeConfiguration.production.expertCacheSlots,
+ expertCachePolicy: RuntimeExpertCachePolicy = RuntimeConfiguration.production.expertCachePolicy,
+ prefillPolicy: RuntimePrefillPolicy = RuntimeConfiguration.production.prefillPolicy,
+ prefillChunkTokens: Int = RuntimeConfiguration.production.prefillChunkTokens,
+ rdadvisePolicy: RDAdvicePolicyMode = RuntimeConfiguration.production.rdadvisePolicy) {
self.model = model
self.prompt = prompt
self.messagesFile = messagesFile
@@ -36,6 +48,11 @@ public struct Args: Equatable, Sendable {
self.seed = seed
self.stops = stops
self.quiet = quiet
+ self.expertCacheSlots = expertCacheSlots
+ self.expertCachePolicy = expertCachePolicy
+ self.prefillPolicy = prefillPolicy
+ self.prefillChunkTokens = prefillChunkTokens
+ self.rdadvisePolicy = rdadvisePolicy
}
}
@@ -73,18 +90,50 @@ extension Args {
--messages-file <path> JSON chat messages with role and content fields.
options:
- --max-new <int> Generated-token limit (default 1024).
- --max-context <int> Context limit in tokens (default 4096).
- --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).
- --repetition-penalty <f> Repetition penalty (default 1.0).
- --seed <uint64> Deterministic sampling seed (default off).
- --stop <string> Stop substring (repeatable).
- --quiet Suppress the timing footer.
- --help Show this message.
+ --max-new <int> Generated-token limit (default 1024).
+ --max-context <int> Context limit in tokens (default 4096).
+ --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).
+ --repetition-penalty <f> Repetition penalty (default 1.0).
+ --seed <uint64> Deterministic sampling seed (default off).
+ --stop <string> Stop substring (repeatable).
+ --quiet Suppress the timing footer.
+ --expert-cache-slots <n> Expert-cache slots: 8, 16, 24, or 32 (default 16).
+ --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).
+ --rdadvise <s> Read-advice policy: off, default, bounded, or adaptive (default off).
+ --help Show this message.
"""
+ public func resolvedRuntimeConfiguration(
+ forceLogitsHead: Bool) throws -> RuntimeConfiguration {
+ guard RuntimeConfiguration.allowedExpertCacheSlots.contains(expertCacheSlots) else {
+ throw ArgsError.invalidValue(
+ flag: "--expert-cache-slots", value: "\(expertCacheSlots)")
+ }
+ guard RuntimeConfiguration.allowedPrefillChunkTokens.contains(prefillChunkTokens) else {
+ throw ArgsError.invalidValue(
+ flag: "--prefill-chunk-tokens", value: "\(prefillChunkTokens)")
+ }
+ let chunkedPrefillSupported = expertCacheSlots >=
+ RuntimeConfiguration.minimumExpertCacheSlotsForChunkedPrefill
+ guard prefillPolicy == .off || chunkedPrefillSupported else {
+ throw ArgsError.invalidValue(
+ flag: "--expert-cache-slots",
+ value: "\(expertCacheSlots) requires --prefill off")
+ }
+ return RuntimeConfiguration(
+ expertCacheSlots: expertCacheSlots,
+ expertCachePolicy: expertCachePolicy,
+ rdadvisePolicy: rdadvisePolicy,
+ prefillEnabled: prefillPolicy == .chunked,
+ prefillChunkTokens: prefillChunkTokens,
+ forceLogitsHead: forceLogitsHead)
+ }
+
public static func parse(_ argv: [String]) throws -> Args {
var model: String?
var prompt: String?
@@ -98,6 +147,12 @@ extension Args {
var seed: UInt64?
var stops: [String] = []
var quiet = false
+ let runtimeDefaults = RuntimeConfiguration.production
+ var expertCacheSlots = runtimeDefaults.expertCacheSlots
+ var expertCachePolicy = runtimeDefaults.expertCachePolicy
+ var prefillPolicy = runtimeDefaults.prefillPolicy
+ var prefillChunkTokens = runtimeDefaults.prefillChunkTokens
+ var rdadvisePolicy = runtimeDefaults.rdadvisePolicy
var index = 0
while index < argv.count {
@@ -158,6 +213,39 @@ extension Args {
seed = parsed
case "--stop":
stops.append(try takeValue(argv, &index, flag: flag))
+ case "--expert-cache-slots":
+ let value = try takeValue(argv, &index, flag: flag)
+ guard let parsed = Int(value),
+ RuntimeConfiguration.allowedExpertCacheSlots.contains(parsed) else {
+ throw ArgsError.invalidValue(flag: flag, value: value)
+ }
+ expertCacheSlots = parsed
+ case "--expert-cache-policy":
+ let value = try takeValue(argv, &index, flag: flag)
+ guard let parsed = RuntimeExpertCachePolicy(rawValue: value) else {
+ throw ArgsError.invalidValue(flag: flag, value: value)
+ }
+ expertCachePolicy = parsed
+ case "--prefill":
+ let value = try takeValue(argv, &index, flag: flag)
+ switch value {
+ case "on": prefillPolicy = .chunked
+ case "off": prefillPolicy = .off
+ default: throw ArgsError.invalidValue(flag: flag, value: value)
+ }
+ case "--prefill-chunk-tokens":
+ let value = try takeValue(argv, &index, flag: flag)
+ guard let parsed = Int(value),
+ RuntimeConfiguration.allowedPrefillChunkTokens.contains(parsed) else {
+ throw ArgsError.invalidValue(flag: flag, value: value)
+ }
+ prefillChunkTokens = parsed
+ case "--rdadvise":
+ let value = try takeValue(argv, &index, flag: flag)
+ guard let parsed = RDAdvicePolicyMode(rawValue: value) else {
+ throw ArgsError.invalidValue(flag: flag, value: value)
+ }
+ rdadvisePolicy = parsed
default:
throw ArgsError.unknownFlag(flag)
}
@@ -173,18 +261,25 @@ extension Args {
flag: "--top-p",
value: "\(topP) requires --top-k between 1 and 256")
}
- return Args(model: model,
- prompt: prompt,
- messagesFile: messagesFile,
- maxNew: maxNew,
- maxContext: maxContext,
- temperature: temperature,
- topK: topK,
- topP: topP,
- repetitionPenalty: repetitionPenalty,
- seed: seed,
- stops: stops,
- quiet: quiet)
+ let arguments = Args(model: model,
+ prompt: prompt,
+ messagesFile: messagesFile,
+ maxNew: maxNew,
+ maxContext: maxContext,
+ temperature: temperature,
+ topK: topK,
+ topP: topP,
+ repetitionPenalty: repetitionPenalty,
+ seed: seed,
+ stops: stops,
+ quiet: quiet,
+ expertCacheSlots: expertCacheSlots,
+ expertCachePolicy: expertCachePolicy,
+ prefillPolicy: prefillPolicy,
+ prefillChunkTokens: prefillChunkTokens,
+ rdadvisePolicy: rdadvisePolicy)
+ _ = try arguments.resolvedRuntimeConfiguration(forceLogitsHead: false)
+ return arguments
}
private static func takeValue(_ argv: [String],
diff --git a/Sources/TurboFieldfareCLI/Run.swift b/Sources/TurboFieldfareCLI/Run.swift
index 2a841b83..068a0460 100644
--- a/Sources/TurboFieldfareCLI/Run.swift
+++ b/Sources/TurboFieldfareCLI/Run.swift
@@ -53,7 +53,7 @@ public func run(args: Args,
seed: args.seed,
stopStrings: args.stops,
extraStopTokens: [])
- let runtime = RuntimeConfiguration(
+ let runtime = try args.resolvedRuntimeConfiguration(
forceLogitsHead: !config.isPureGreedy)
guard MTLCreateSystemDefaultDevice() != nil else {
diff --git a/Tests/TurboFieldfare/Core/CLI/CLIArgumentsTests.swift b/Tests/TurboFieldfare/Core/CLI/CLIArgumentsTests.swift
index 4435cba3..08455a82 100644
--- a/Tests/TurboFieldfare/Core/CLI/CLIArgumentsTests.swift
+++ b/Tests/TurboFieldfare/Core/CLI/CLIArgumentsTests.swift
@@ -1,4 +1,5 @@
import Testing
+import TurboFieldfare
@testable import TurboFieldfareCLICore
@Suite struct CLIArgumentsTests {
@@ -16,6 +17,9 @@ import Testing
#expect(arguments.seed == nil)
#expect(arguments.stops.isEmpty)
#expect(!arguments.quiet)
+
+ let runtime = try arguments.resolvedRuntimeConfiguration(forceLogitsHead: false)
+ #expect(runtime == RuntimeConfiguration.production)
}
@Test func generationOptionsParseAndStopsRepeat() throws {
@@ -64,13 +68,127 @@ import Testing
let expected: Set<String> = [
"--model", "--prompt", "--messages-file", "--max-new", "--max-context",
"--temperature", "--top-k", "--top-p", "--repetition-penalty",
- "--seed", "--stop", "--quiet", "--help",
+ "--seed", "--stop", "--quiet", "--expert-cache-slots",
+ "--expert-cache-policy", "--prefill", "--prefill-chunk-tokens",
+ "--rdadvise", "--help",
]
let words = Args.usage.split { $0.isWhitespace || $0 == "(" || $0 == ")" }
let options = Set(words.map(String.init).filter { $0.hasPrefix("--") })
#expect(options == expected)
}
+ @Test func runtimeOptionsReachTypedConfiguration() throws {
+ let arguments = try Args.parse([
+ "--model", "m.gturbo", "--prompt", "hi",
+ "--expert-cache-slots", "24",
+ "--expert-cache-policy", "lru",
+ "--prefill", "off",
+ "--prefill-chunk-tokens", "64",
+ "--rdadvise", "adaptive",
+ ])
+
+ #expect(arguments.expertCacheSlots == 24)
+ #expect(arguments.expertCachePolicy == .lru)
+ #expect(arguments.prefillPolicy == .off)
+ #expect(arguments.prefillChunkTokens == 64)
+ #expect(arguments.rdadvisePolicy == .adaptive)
+
+ let runtime = try arguments.resolvedRuntimeConfiguration(forceLogitsHead: true)
+ #expect(runtime.expertCacheSlots == 24)
+ #expect(runtime.modelExpertCachePolicy == .lru)
+ #expect(runtime.prefillPolicy == .off)
+ #expect(runtime.prefillChunkTokens == 64)
+ #expect(runtime.rdadvisePolicy == .adaptive)
+ #expect(runtime.headPath == .logits)
+ }
+
+ @Test func everySupportedRuntimeOptionParses() throws {
+ for value in RuntimeConfiguration.allowedExpertCacheSlots {
+ let prefill = value < RuntimeConfiguration.minimumExpertCacheSlotsForChunkedPrefill
+ ? "off" : "on"
+ let arguments = try Args.parse([
+ "--model", "m.gturbo", "--prompt", "hi",
+ "--expert-cache-slots", "\(value)",
+ "--prefill", prefill,
+ ])
+ #expect(arguments.expertCacheSlots == value)
+ }
+ for value in RuntimeConfiguration.allowedPrefillChunkTokens {
+ let arguments = try Args.parse([
+ "--model", "m.gturbo", "--prompt", "hi",
+ "--prefill-chunk-tokens", "\(value)",
+ ])
+ #expect(arguments.prefillChunkTokens == value)
+ }
+ for value in ["lfu", "lru"] {
+ let arguments = try Args.parse([
+ "--model", "m.gturbo", "--prompt", "hi",
+ "--expert-cache-policy", value,
+ ])
+ #expect(arguments.expertCachePolicy.rawValue == value)
+ }
+ for value in ["off", "default", "bounded", "adaptive"] {
+ let arguments = try Args.parse([
+ "--model", "m.gturbo", "--prompt", "hi", "--rdadvise", value,
+ ])
+ #expect(arguments.rdadvisePolicy.rawValue == value)
+ }
+ #expect(try Args.parse([
+ "--model", "m.gturbo", "--prompt", "hi", "--prefill", "on",
+ ]).prefillPolicy == .chunked)
+ #expect(try Args.parse([
+ "--model", "m.gturbo", "--prompt", "hi", "--prefill", "off",
+ ]).prefillPolicy == .off)
+ }
+
+ @Test func unsupportedRuntimeOptionValuesAreRejected() {
+ let invalidValues = [
+ ("--expert-cache-slots", "7"),
+ ("--expert-cache-policy", "fifo"),
+ ("--prefill", "yes"),
+ ("--prefill-chunk-tokens", "256"),
+ ("--rdadvise", "automatic"),
+ ]
+ for (flag, value) in invalidValues {
+ #expect(throws: ArgsError.invalidValue(flag: flag, value: value)) {
+ _ = try Args.parse([
+ "--model", "m.gturbo", "--prompt", "hi", flag, value,
+ ])
+ }
+ }
+
+ #expect(throws: ArgsError.invalidValue(
+ flag: "--expert-cache-slots", value: "8 requires --prefill off")) {
+ _ = try Args.parse([
+ "--model", "m.gturbo", "--prompt", "hi",
+ "--expert-cache-slots", "8", "--prefill", "on",
+ ])
+ }
+ }
+
+ @Test func programmaticArgumentsCannotReachRuntimePreconditions() {
+ var arguments = Args(model: "m.gturbo", prompt: "hi")
+ arguments.expertCacheSlots = 7
+ #expect(throws: ArgsError.invalidValue(
+ flag: "--expert-cache-slots", value: "7")) {
+ _ = try arguments.resolvedRuntimeConfiguration(forceLogitsHead: false)
+ }
+
+ arguments.expertCacheSlots = RuntimeConfiguration.production.expertCacheSlots
+ arguments.prefillChunkTokens = 256
+ #expect(throws: ArgsError.invalidValue(
+ flag: "--prefill-chunk-tokens", value: "256")) {
+ _ = try arguments.resolvedRuntimeConfiguration(forceLogitsHead: false)
+ }
+
+ arguments.prefillChunkTokens = RuntimeConfiguration.production.prefillChunkTokens
+ arguments.expertCacheSlots = 8
+ #expect(throws: ArgsError.invalidValue(
+ flag: "--expert-cache-slots", value: "8 requires --prefill off")) {
+ _ = try arguments.resolvedRuntimeConfiguration(forceLogitsHead: false)
+ }
+ }
+
@Test func unsupportedSelectorsAreRejected() {
for flag in ["--runtime-profile", "--experiment-id", "-h"] {
#expect(throws: ArgsError.unknownFlag(flag)) {
diff --git a/Tests/TurboFieldfare/Core/Runtime/Generation/CommandBufferCompletionTests.swift b/Tests/TurboFieldfare/Core/Runtime/Generation/CommandBufferCompletionTests.swift
new file mode 100644
index 00000000..d010592c
--- /dev/null
+++ b/Tests/TurboFieldfare/Core/Runtime/Generation/CommandBufferCompletionTests.swift
@@ -0,0 +1,22 @@
+import Testing
+
+@testable import TurboFieldfare
+
+@Suite struct CommandBufferCompletionTests {
+ private enum SyntheticCommandBufferError: Error, Equatable {
+ case failed
+ }
+
+ @Test func commandBufferErrorsArePropagated() throws {
+ try checkCommandBufferError(nil)
+
+ do {
+ try checkCommandBufferError(SyntheticCommandBufferError.failed)
+ Issue.record("expected command-buffer error")
+ } catch let error as SyntheticCommandBufferError {
+ #expect(error == .failed)
+ } catch {
+ Issue.record("unexpected error: \(error)")
+ }
+ }
+}
diff --git a/Tests/TurboFieldfareApp/Core/State/AppModelTests.swift b/Tests/TurboFieldfareApp/Core/State/AppModelTests.swift
index ac711393..b5a149da 100644
--- a/Tests/TurboFieldfareApp/Core/State/AppModelTests.swift
+++ b/Tests/TurboFieldfareApp/Core/State/AppModelTests.swift
@@ -323,9 +323,12 @@ import Testing
@MainActor
@Test func changingModelPathInvalidatesLoadedStateAndDiagnostics() {
- let model = AppModel(client: MockInferenceClient())
- let oldURL = FileManager.default.temporaryDirectory.appendingPathComponent("old.gturbo")
- let newURL = FileManager.default.temporaryDirectory.appendingPathComponent("new.gturbo")
+ let model = AppModel(client: MockInferenceClient(),
+ installer: MockModelInstallerClient())
+ let testDirectory = FileManager.default.temporaryDirectory
+ .appendingPathComponent("app-model-path-\(UUID().uuidString)", isDirectory: true)
+ let oldURL = testDirectory.appendingPathComponent("old.gturbo")
+ let newURL = testDirectory.appendingPathComponent("new.gturbo")
model.modelPathText = oldURL.path
model.loadState = .ready(modelDirectory: oldURL, loadSeconds: 1)
model.diagnostics = AppDiagnostics(
diff --git a/docs/COMMUNITY_BENCHMARKS.md b/docs/COMMUNITY_BENCHMARKS.md
index aba323e6..13b3ba58 100644
--- a/docs/COMMUNITY_BENCHMARKS.md
+++ b/docs/COMMUNITY_BENCHMARKS.md
@@ -174,6 +174,9 @@ all affect decode speed.
| [Marcelo Barros](https://github.com/marcelopbarros) · [issue #67](https://github.com/drumih/turbo-fieldfare/issues/67) | M4 Pro MacBook Pro | 24 GB | Internal SSD | 61 / 516 | 33.379 tok/s | High Power mode |
| [Marcelo Barros](https://github.com/marcelopbarros) · [issue #67](https://github.com/drumih/turbo-fieldfare/issues/67) | M4 Pro MacBook Pro | 24 GB | Internal SSD | 430 / 780 | 30.614 tok/s | High Power mode |
| [Marcelo Barros](https://github.com/marcelopbarros) · [issue #67](https://github.com/drumih/turbo-fieldfare/issues/67) | M4 Pro MacBook Pro | 24 GB | Internal SSD | 3,015 / 617 | 25.230 tok/s | High Power mode |
+| [Matt Skipton](https://github.com/mattskipton) · [issue #97](https://github.com/drumih/turbo-fieldfare/issues/97) | M5 Pro MacBook Pro | 64 GB | Not reported | 61 / 497 | 37.426 tok/s | One submitted run |
+| [Matt Skipton](https://github.com/mattskipton) · [issue #97](https://github.com/drumih/turbo-fieldfare/issues/97) | M5 Pro MacBook Pro | 64 GB | Not reported | 430 / 721 | 34.194 tok/s | One submitted run |
+| [Matt Skipton](https://github.com/mattskipton) · [issue #97](https://github.com/drumih/turbo-fieldfare/issues/97) | M5 Pro MacBook Pro | 64 GB | Not reported | 3,015 / 610 | 31.485 tok/s | One submitted run |
These submissions use the public community prompts and generate until the end
of the model turn. Compare rows only when the prompt and generated-token counts
diff --git a/docs/RUNTIME_CONTROLS.md b/docs/RUNTIME_CONTROLS.md
index 8dc08b4e..45da4b90 100644
--- a/docs/RUNTIME_CONTROLS.md
+++ b/docs/RUNTIME_CONTROLS.md
@@ -1,8 +1,8 @@
# Runtime controls
-The Mac app exposes generation and runtime controls in its fixed right
-settings pane. FP16 is the fixed KV format. Generation settings apply to the
-next request; load-time settings require a reload.
+The Mac app and CLI expose generation and runtime controls. The app keeps them
+in its fixed right settings pane. FP16 is the fixed KV format. Generation
+settings apply to the next request; app load-time settings require a reload.
## Generation controls
@@ -24,23 +24,26 @@ benchmark protocol.
## Runtime settings
-| Control | Values | Production default | Effect |
-| --- | --- | --- | --- |
-| Expert-cache slots | 8, 16, 24, 32 | 16 | More slots can retain more routed experts and reduce later reads, but values above 16 use more RAM. |
-| Prompt prefill | On, off | On | On processes known prompt tokens through the chunked prefill path. Off disables that path. |
-| 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. |
+| Control | Mac values | CLI flag | Production default | Effect |
+| --- | --- | --- | --- | --- |
+| 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. |
+| 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. |
-Changing context length, expert-cache slots, or RDADVISE requires a reload.
-Some sampling changes also require a reload because greedy and sampled
+In the app, changing context length, expert-cache slots, or RDADVISE requires a
+reload. Some sampling changes also require a reload because greedy and sampled
generation use different output-head paths. Prompt-prefill settings apply to
-each request and do not require a reload.
+each request and do not require a reload. Each CLI invocation loads a new model
+process, so its selected runtime settings apply immediately.
## Run an experiment
1. Start from 4K 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 model.
+4. Change one runtime control and reload the app model, or start a new CLI run.
5. Compare prompt prefill, request TTFT, decode rate, peak memory, and I/O per
token over repeated runs.
6. Restore the production defaults when the experiment ends.