Skip to content

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

Add About panel and Finder reveal, server runtime flags, and SwiftNIO 2.101.3 (#124)

Andrey Mikhaylov903c7bfa9bb8
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 52695d15..7686e5b1 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -31,3 +31,7 @@ jobs:
run: Scripts/test.sh
- name: Check Markdown links
run: ruby Scripts/check_markdown_links.rb
+ - name: Check the app version against the latest release
+ env:
+ GITHUB_TOKEN: ${{ github.token }}
+ run: ruby Scripts/check_app_version.rb
diff --git a/Package.resolved b/Package.resolved
index 29567267..5d6cd2ac 100644
--- a/Package.resolved
+++ b/Package.resolved
@@ -1,5 +1,5 @@
{
- "originHash" : "fcd8c6c7b3bdc1b2987889f5525974610779e7fe094361a13b5cd2b27afa046b",
+ "originHash" : "794fbf949f0e97118a7640964bafcb54454e69c994c870b072392cd249f5f136",
"pins" : [
{
"identity" : "eventsource",
@@ -69,8 +69,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-nio.git",
"state" : {
- "revision" : "f71c8d2a5e74a2c6d11a0fbe324774b5d6084237",
- "version" : "2.99.0"
+ "revision" : "0b18836bd8b0162e7e17a995a3fbee20ed8f3b2b",
+ "version" : "2.101.3"
}
},
{
diff --git a/Package.swift b/Package.swift
index 3430eed7..6b8be2b5 100644
--- a/Package.swift
+++ b/Package.swift
@@ -17,7 +17,7 @@ let package = Package(
],
dependencies: [
.package(url: "https://github.com/huggingface/swift-transformers", from: "1.3.0"),
- .package(url: "https://github.com/apple/swift-nio.git", exact: "2.99.0"),
+ .package(url: "https://github.com/apple/swift-nio.git", exact: "2.101.3"),
],
targets: [
.target(
diff --git a/Scripts/check_app_version.rb b/Scripts/check_app_version.rb
new file mode 100755
index 00000000..ada8cc29
--- /dev/null
+++ b/Scripts/check_app_version.rb
@@ -0,0 +1,84 @@
+#!/usr/bin/env ruby
+
+# Verifies that the version the Mac app shows is not behind the newest published
+# GitHub release.
+#
+# Most users build from a clone, where there is no Info.plist, so the compiled
+# constant in AboutPanelPresentation is the version they see. Nothing bumps it
+# automatically, so without this check it silently ages: the About panel would
+# claim an old version on a current checkout.
+#
+# Being ahead of the newest release is allowed. That is the normal state between
+# bumping the constant and publishing the release built from it.
+
+require "json"
+require "net/http"
+require "uri"
+
+ROOT = File.expand_path("..", __dir__)
+SOURCE = File.join(ROOT, "Sources/TurboFieldfareApp/MacPresentation/AboutPanelPresentation.swift")
+RELEASES_URL = "https://api.github.com/repos/drumih/turbo-fieldfare/releases/latest"
+
+def compiled_version
+ source = File.read(SOURCE)
+ match = source[/fallbackShortVersion\s*=\s*"([^"]+)"/, 1]
+ abort "could not find fallbackShortVersion in #{SOURCE}" unless match
+
+ match
+end
+
+def published_version
+ uri = URI(RELEASES_URL)
+ request = Net::HTTP::Get.new(uri)
+ request["Accept"] = "application/vnd.github+json"
+ request["User-Agent"] = "turbofieldfare-version-check"
+ token = ENV["GITHUB_TOKEN"] || ENV["GH_TOKEN"]
+ request["Authorization"] = "Bearer #{token}" if token && !token.empty?
+
+ response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true, open_timeout: 10, read_timeout: 10) do |http|
+ http.request(request)
+ end
+ unless response.is_a?(Net::HTTPSuccess)
+ warn "warning: could not read the latest release (#{response.code}); skipping the comparison"
+ return nil
+ end
+
+ JSON.parse(response.body)["tag_name"].to_s.delete_prefix("v")
+rescue StandardError => error
+ warn "warning: could not reach GitHub (#{error.class}); skipping the comparison"
+ nil
+end
+
+# Compares dotted numeric versions. Returns -1, 0, or 1.
+def compare(left, right)
+ left_parts = left.split(".").map(&:to_i)
+ right_parts = right.split(".").map(&:to_i)
+ length = [left_parts.length, right_parts.length].max
+ length.times do |index|
+ result = (left_parts[index] || 0) <=> (right_parts[index] || 0)
+ return result unless result.zero?
+ end
+ 0
+end
+
+compiled = compiled_version
+published = published_version
+if published.nil?
+ puts "app version #{compiled}; latest release unknown"
+ exit 0
+end
+
+case compare(compiled, published)
+when -1
+ abort <<~MESSAGE
+ app version #{compiled} is behind the latest release #{published}
+
+ Update fallbackShortVersion in
+ Sources/TurboFieldfareApp/MacPresentation/AboutPanelPresentation.swift
+ so a clone build reports the version it actually corresponds to.
+ MESSAGE
+when 0
+ puts "app version #{compiled} matches the latest release"
+else
+ puts "app version #{compiled} is ahead of the latest release #{published}; unreleased build"
+end
diff --git a/Sources/TurboFieldfareApp/Mac/App/MacAppIcon.swift b/Sources/TurboFieldfareApp/Mac/App/MacAppIcon.swift
new file mode 100644
index 00000000..1352bd32
--- /dev/null
+++ b/Sources/TurboFieldfareApp/Mac/App/MacAppIcon.swift
@@ -0,0 +1,13 @@
+import AppKit
+
+// Bundle.module resolves only inside this target, so the icon cannot be loaded
+// from the presentation library.
+enum MacAppIcon {
+ static func load() -> NSImage? {
+ guard let url = Bundle.module.url(
+ forResource: "turbofieldfare-app-icon",
+ withExtension: "png"
+ ) else { return nil }
+ return NSImage(contentsOf: url)
+ }
+}
diff --git a/Sources/TurboFieldfareApp/Mac/App/TurboFieldfareMacApp.swift b/Sources/TurboFieldfareApp/Mac/App/TurboFieldfareMacApp.swift
index 8ac9dd86..d562fe2e 100644
--- a/Sources/TurboFieldfareApp/Mac/App/TurboFieldfareMacApp.swift
+++ b/Sources/TurboFieldfareApp/Mac/App/TurboFieldfareMacApp.swift
@@ -1,5 +1,6 @@
import AppKit
import TurboFieldfareAppCore
+import TurboFieldfareMacPresentation
import SwiftUI
// Run as a regular foreground app even when launched as a bare SwiftPM
@@ -8,10 +9,7 @@ import SwiftUI
private final class ForegroundAppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ notification: Notification) {
NSApp.setActivationPolicy(.regular)
- if let iconURL = Bundle.module.url(
- forResource: "turbofieldfare-app-icon",
- withExtension: "png"
- ), let icon = NSImage(contentsOf: iconURL) {
+ if let icon = MacAppIcon.load() {
NSApp.applicationIconImage = icon
NSApp.dockTile.display()
}
@@ -43,6 +41,14 @@ struct TurboFieldfareMacApp: App {
.defaultSize(width: 1040, height: 720)
.windowResizability(.contentMinSize)
.commands {
+ CommandGroup(replacing: .appInfo) {
+ Button("About TurboFieldfare") {
+ NSApp.orderFrontStandardAboutPanel(
+ options: AboutPanelPresentation.options(
+ infoDictionary: Bundle.main.infoDictionary,
+ icon: MacAppIcon.load()))
+ }
+ }
CommandMenu("Generation") {
Button("Cancel Generation") { model.cancel() }
.keyboardShortcut(".", modifiers: .command)
@@ -57,6 +63,9 @@ struct TurboFieldfareMacApp: App {
.disabled(!model.canReloadModel)
Button("Unload Model", action: model.unloadModel)
.disabled(!model.canUnloadModel)
+ Divider()
+ Button("Reveal Model in Finder", action: revealModel)
+ .disabled(modelRevealTarget == .unavailable)
}
CommandMenu("Settings") {
Picker("Send Message With", selection: newlineShortcutBinding) {
@@ -77,6 +86,23 @@ struct TurboFieldfareMacApp: App {
}
}
+ private var modelRevealTarget: ModelRevealTarget {
+ ModelRevealPolicy.target(
+ forModelPath: model.modelPathText,
+ fileExists: FileManager.default.fileExists(atPath:))
+ }
+
+ private func revealModel() {
+ switch modelRevealTarget {
+ case .selectItem(let url):
+ NSWorkspace.shared.activateFileViewerSelecting([url])
+ case .openContainer(let url):
+ NSWorkspace.shared.open(url)
+ case .unavailable:
+ break
+ }
+ }
+
private var newlineShortcutBinding: Binding<AppNewlineShortcut> {
Binding {
model.newlineShortcut
diff --git a/Sources/TurboFieldfareApp/MacPresentation/AboutPanelPresentation.swift b/Sources/TurboFieldfareApp/MacPresentation/AboutPanelPresentation.swift
new file mode 100644
index 00000000..30a1e4cd
--- /dev/null
+++ b/Sources/TurboFieldfareApp/MacPresentation/AboutPanelPresentation.swift
@@ -0,0 +1,98 @@
+import AppKit
+import Foundation
+
+public struct AboutPanelContent: Equatable, Sendable {
+ public let applicationName: String
+ public let shortVersion: String
+
+ public init(applicationName: String, shortVersion: String) {
+ self.applicationName = applicationName
+ self.shortVersion = shortVersion
+ }
+}
+
+public enum AboutPanelPresentation {
+ public static let applicationName = "TurboFieldfare"
+
+ // 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.2"
+
+ private static let licenseURL = URL(
+ string: "https://github.com/drumih/turbo-fieldfare/blob/main/LICENSE")!
+
+ public static let repositoryURL = URL(string: "https://github.com/drumih/turbo-fieldfare")!
+
+ public static let repositoryLinkText = "github.com/drumih/turbo-fieldfare"
+
+ private static let licenseName = "Apache License 2.0"
+
+ public static func content(infoDictionary: [String: Any]?) -> AboutPanelContent {
+ AboutPanelContent(
+ applicationName: applicationName,
+ shortVersion: shortVersion(infoDictionary: infoDictionary))
+ }
+
+ public static func shortVersion(infoDictionary: [String: Any]?) -> String {
+ let bundleVersion = (infoDictionary?["CFBundleShortVersionString"] as? String)?
+ .trimmingCharacters(in: .whitespacesAndNewlines)
+ guard let bundleVersion, !bundleVersion.isEmpty else { return fallbackShortVersion }
+ return bundleVersion
+ }
+
+ @MainActor
+ public static func options(infoDictionary: [String: Any]?,
+ icon: NSImage?) -> [NSApplication.AboutPanelOptionKey: Any] {
+ let content = content(infoDictionary: infoDictionary)
+ var options: [NSApplication.AboutPanelOptionKey: Any] = [
+ .applicationName: content.applicationName,
+ .applicationVersion: content.shortVersion,
+ .credits: credits(),
+ ]
+ // The documented fallback is NSImage(named: "NSApplicationIcon"), which a
+ // bare executable cannot resolve, so pass the Dock icon explicitly.
+ if let icon { options[.applicationIcon] = icon }
+ return options
+ }
+
+ @MainActor
+ public static func credits() -> NSAttributedString {
+ let paragraph = NSMutableParagraphStyle()
+ paragraph.alignment = .center
+ // "Apache License 2.0" is a link, and letting it wrap mid-phrase reads as
+ // a broken line, so the break is explicit.
+ let licenseLead = "TurboFieldfare is licensed under the"
+ let text = """
+ \(repositoryLinkText)
+ \(licenseLead)
+ \(licenseName).
+ """
+ let credits = NSMutableAttributedString(
+ string: text,
+ attributes: [
+ .font: NSFont.systemFont(ofSize: NSFont.smallSystemFontSize),
+ .foregroundColor: NSColor.secondaryLabelColor,
+ .paragraphStyle: paragraph,
+ ])
+ link(licenseName, to: licenseURL, in: credits, text: text)
+ link(repositoryLinkText, to: repositoryURL, in: credits, text: text)
+ if let range = text.range(of: licenseLead) {
+ let spaced = NSMutableParagraphStyle()
+ spaced.alignment = .center
+ spaced.paragraphSpacingBefore = 8
+ credits.addAttribute(.paragraphStyle,
+ value: spaced,
+ range: NSRange(range, in: text))
+ }
+ return credits
+ }
+
+ private static func link(_ substring: String,
+ to url: URL,
+ in credits: NSMutableAttributedString,
+ text: String) {
+ guard let range = text.range(of: substring) else { return }
+ credits.addAttribute(.link, value: url, range: NSRange(range, in: text))
+ }
+}
diff --git a/Sources/TurboFieldfareApp/MacPresentation/ModelRevealPolicy.swift b/Sources/TurboFieldfareApp/MacPresentation/ModelRevealPolicy.swift
new file mode 100644
index 00000000..31293319
--- /dev/null
+++ b/Sources/TurboFieldfareApp/MacPresentation/ModelRevealPolicy.swift
@@ -0,0 +1,26 @@
+import Foundation
+
+public enum ModelRevealTarget: Equatable, Sendable {
+ case selectItem(URL)
+ case openContainer(URL)
+ case unavailable
+}
+
+public enum ModelRevealPolicy {
+ // The model directory is user-editable and may not exist yet: an install
+ // that never ran, or a hand-typed path. Falling back to the containing
+ // directory still answers "where would the model go", which is the question
+ // the menu item exists to answer.
+ public static func target(forModelPath path: String,
+ fileExists: (String) -> Bool) -> ModelRevealTarget {
+ let trimmed = path.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !trimmed.isEmpty else { return .unavailable }
+ let url = URL(fileURLWithPath: trimmed, isDirectory: true).standardizedFileURL
+ if fileExists(url.path) { return .selectItem(url) }
+ let container = url.deletingLastPathComponent().standardizedFileURL
+ if container.path != url.path, fileExists(container.path) {
+ return .openContainer(container)
+ }
+ return .unavailable
+ }
+}
diff --git a/Sources/TurboFieldfareServer/Command/main.swift b/Sources/TurboFieldfareServer/Command/main.swift
index ba6aae71..f9f4ec60 100644
--- a/Sources/TurboFieldfareServer/Command/main.swift
+++ b/Sources/TurboFieldfareServer/Command/main.swift
@@ -1,10 +1,15 @@
import Darwin
import Foundation
+import TurboFieldfare
import TurboFieldfareServerCore
let arguments: ServerArguments
+let runtimeConfiguration: RuntimeConfiguration
do {
arguments = try ServerArguments.parse(Array(CommandLine.arguments.dropFirst()))
+ // Resolved here so an unusable flag combination exits with usage instead of
+ // failing after the model has started loading.
+ runtimeConfiguration = try arguments.resolvedRuntimeConfiguration()
} catch ServerArgumentError.help {
print(ServerArguments.usage)
exit(0)
@@ -19,7 +24,8 @@ do {
let backend = try await ServerModelSession.load(
modelDirectory: modelURL,
maxContext: arguments.maxContext,
- promptCacheMode: arguments.promptCacheMode)
+ promptCacheMode: arguments.promptCacheMode,
+ runtimeConfiguration: runtimeConfiguration)
let server = TurboFieldfareHTTPServer(
modelID: arguments.modelID,
queueLimit: arguments.queueLimit,
diff --git a/Sources/TurboFieldfareServer/Core/ServerArguments.swift b/Sources/TurboFieldfareServer/Core/ServerArguments.swift
index 632b1a00..574da2bd 100644
--- a/Sources/TurboFieldfareServer/Core/ServerArguments.swift
+++ b/Sources/TurboFieldfareServer/Core/ServerArguments.swift
@@ -1,4 +1,5 @@
import Foundation
+import TurboFieldfare
public struct ServerArguments: Equatable, Sendable {
public let model: String
@@ -7,20 +8,60 @@ public struct ServerArguments: Equatable, Sendable {
public let maxContext: Int
public let queueLimit: Int
public let promptCacheMode: ServerPromptCacheMode
+ public let expertCacheSlots: Int
+ public let expertCachePolicy: RuntimeExpertCachePolicy
+ public let prefillPolicy: RuntimePrefillPolicy
+ public let prefillChunkTokens: Int
+ public let rdadvisePolicy: RDAdvicePolicyMode
public static let usage = """
usage: TurboFieldfareServer --model <completed .gturbo directory> [options]
- --model <dir> Required model directory.
- --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).
- --queue-limit <count> Maximum queued requests (default 4).
+ --model <dir> Required model directory.
+ --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).
+ --queue-limit <count> Maximum queued requests (default 4).
--prompt-cache-mode <off|single-prefix>
- Prompt KV reuse mode (default single-prefix).
- --help Show this help.
+ Prompt KV reuse mode (default single-prefix).
+ --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 help.
"""
+ // Mirrors the CLI's runtime flags so both binaries accept the same options
+ // with the same validation, instead of the server pinning production
+ // defaults. RuntimeConfiguration traps on unsupported values, so every
+ // bound is checked here before the initializer runs.
+ public func resolvedRuntimeConfiguration(
+ forceLogitsHead: Bool = true
+ ) throws -> RuntimeConfiguration {
+ guard RuntimeConfiguration.allowedExpertCacheSlots.contains(expertCacheSlots) else {
+ 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")
+ }
+ guard prefillPolicy == .off
+ || expertCacheSlots >= RuntimeConfiguration.minimumExpertCacheSlotsForChunkedPrefill
+ else {
+ throw ServerArgumentError.invalid(
+ "--expert-cache-slots \(expertCacheSlots) requires --prefill off")
+ }
+ return RuntimeConfiguration(
+ expertCacheSlots: expertCacheSlots,
+ expertCachePolicy: expertCachePolicy,
+ rdadvisePolicy: rdadvisePolicy,
+ prefillEnabled: prefillPolicy == .chunked,
+ prefillChunkTokens: prefillChunkTokens,
+ forceLogitsHead: forceLogitsHead)
+ }
+
public static func parse(_ input: [String]) throws -> ServerArguments {
var model: String?
var port = 8080
@@ -28,6 +69,11 @@ public struct ServerArguments: Equatable, Sendable {
var maxContext = 16_384
var queueLimit = 4
var promptCacheMode: ServerPromptCacheMode = .singlePrefix
+ var expertCacheSlots = 16
+ var expertCachePolicy = RuntimeExpertCachePolicy.lfu
+ var prefillPolicy = RuntimePrefillPolicy.chunked
+ var prefillChunkTokens = 128
+ var rdadvisePolicy = RDAdvicePolicyMode.off
var index = 0
while index < input.count {
let flag = input[index]
@@ -67,6 +113,35 @@ public struct ServerArguments: Equatable, Sendable {
"--prompt-cache-mode must be off or single-prefix")
}
promptCacheMode = parsed
+ case "--expert-cache-slots":
+ guard let parsed = Int(value),
+ RuntimeConfiguration.allowedExpertCacheSlots.contains(parsed) else {
+ throw ServerArgumentError.invalid("--expert-cache-slots must be 8, 16, 24, or 32")
+ }
+ expertCacheSlots = parsed
+ case "--expert-cache-policy":
+ guard let parsed = RuntimeExpertCachePolicy(rawValue: value) else {
+ throw ServerArgumentError.invalid("--expert-cache-policy must be lfu or lru")
+ }
+ expertCachePolicy = parsed
+ case "--prefill":
+ switch value {
+ case "on": prefillPolicy = .chunked
+ case "off": prefillPolicy = .off
+ default: throw ServerArgumentError.invalid("--prefill must be on or off")
+ }
+ case "--prefill-chunk-tokens":
+ guard let parsed = Int(value),
+ RuntimeConfiguration.allowedPrefillChunkTokens.contains(parsed) else {
+ throw ServerArgumentError.invalid("--prefill-chunk-tokens must be 32, 64, or 128")
+ }
+ prefillChunkTokens = parsed
+ case "--rdadvise":
+ guard let parsed = RDAdvicePolicyMode(rawValue: value) else {
+ throw ServerArgumentError.invalid(
+ "--rdadvise must be off, default, bounded, or adaptive")
+ }
+ rdadvisePolicy = parsed
default:
throw ServerArgumentError.invalid("unknown flag: \(flag)")
}
@@ -77,7 +152,12 @@ public struct ServerArguments: Equatable, Sendable {
modelID: modelID,
maxContext: maxContext,
queueLimit: queueLimit,
- promptCacheMode: promptCacheMode)
+ promptCacheMode: promptCacheMode,
+ expertCacheSlots: expertCacheSlots,
+ expertCachePolicy: expertCachePolicy,
+ prefillPolicy: prefillPolicy,
+ prefillChunkTokens: prefillChunkTokens,
+ rdadvisePolicy: rdadvisePolicy)
}
}
diff --git a/Sources/TurboFieldfareServer/Core/ServerInference.swift b/Sources/TurboFieldfareServer/Core/ServerInference.swift
index 6277dc99..b96543ca 100644
--- a/Sources/TurboFieldfareServer/Core/ServerInference.swift
+++ b/Sources/TurboFieldfareServer/Core/ServerInference.swift
@@ -388,7 +388,8 @@ public actor ServerModelSession: ServerInferenceBackend {
public static func load(modelDirectory: URL,
maxContext: Int,
- promptCacheMode: ServerPromptCacheMode = .singlePrefix) async throws -> ServerModelSession {
+ promptCacheMode: ServerPromptCacheMode = .singlePrefix,
+ runtimeConfiguration: RuntimeConfiguration) async throws -> ServerModelSession {
let tokenizerFolder = GFTokenizer.tokenizerFolder(forModelDirectory: modelDirectory)
guard let tokenizerFolder else {
throw GFTokenizerError.missingToolTemplate
@@ -399,7 +400,7 @@ public actor ServerModelSession: ServerInferenceBackend {
}
let tokenizer = try await GFTokenizer.load(from: tokenizerFolder)
let context = try MetalContext()
- let runtime = RuntimeConfiguration(forceLogitsHead: true)
+ let runtime = runtimeConfiguration
let model = try Model.load(
directoryURL: modelDirectory,
device: context.device,
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index b6607a3e..15a89780 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -36,7 +36,7 @@ The following table covers the complete graph reported by
| [swift-jinja](https://github.com/huggingface/swift-jinja) | 2.3.6 | Apache-2.0 |
| [swift-huggingface](https://github.com/huggingface/swift-huggingface) | 0.9.0 | Apache-2.0 |
| [EventSource](https://github.com/mattt/EventSource) | 1.4.1 | MIT |
-| [swift-nio](https://github.com/apple/swift-nio) | 2.99.0 | Apache-2.0; upstream NOTICE applies |
+| [swift-nio](https://github.com/apple/swift-nio) | 2.101.3 | Apache-2.0; upstream NOTICE applies |
| [swift-atomics](https://github.com/apple/swift-atomics) | 1.3.0 | Apache-2.0 with Runtime Library Exception |
| [swift-collections](https://github.com/apple/swift-collections) | 1.5.1 | Apache-2.0 with Runtime Library Exception |
| [swift-system](https://github.com/apple/swift-system) | 1.6.4 | Apache-2.0 with Runtime Library Exception |
diff --git a/Tests/TurboFieldfareApp/MacPresentation/AboutPanelPresentationTests.swift b/Tests/TurboFieldfareApp/MacPresentation/AboutPanelPresentationTests.swift
new file mode 100644
index 00000000..0da051a9
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/AboutPanelPresentationTests.swift
@@ -0,0 +1,65 @@
+import AppKit
+import Foundation
+import Testing
+@testable import TurboFieldfareMacPresentation
+
+@Suite struct AboutPanelPresentationTests {
+ @Test func packagedBundleVersionWins() {
+ let content = AboutPanelPresentation.content(
+ infoDictionary: ["CFBundleShortVersionString": "0.4.2"])
+ #expect(content.shortVersion == "0.4.2")
+ #expect(content.applicationName == "TurboFieldfare")
+ }
+
+ @Test func cloneBuildFallsBackToTheCompiledVersion() {
+ #expect(AboutPanelPresentation.shortVersion(infoDictionary: nil)
+ == AboutPanelPresentation.fallbackShortVersion)
+ #expect(AboutPanelPresentation.shortVersion(infoDictionary: [:])
+ == AboutPanelPresentation.fallbackShortVersion)
+ }
+
+ @Test(arguments: ["", " ", "\n"])
+ func blankBundleVersionFallsBack(value: String) {
+ #expect(AboutPanelPresentation.shortVersion(
+ infoDictionary: ["CFBundleShortVersionString": value])
+ == AboutPanelPresentation.fallbackShortVersion)
+ }
+
+ @Test func nonStringBundleVersionFallsBack() {
+ #expect(AboutPanelPresentation.shortVersion(
+ infoDictionary: ["CFBundleShortVersionString": 42])
+ == AboutPanelPresentation.fallbackShortVersion)
+ }
+
+ @Test func bundleVersionIsTrimmed() {
+ #expect(AboutPanelPresentation.shortVersion(
+ infoDictionary: ["CFBundleShortVersionString": " 1.2.3\n"]) == "1.2.3")
+ }
+
+ @MainActor
+ @Test func optionsCarryNameVersionAndIconWhenAvailable() {
+ let options = AboutPanelPresentation.options(
+ infoDictionary: ["CFBundleShortVersionString": "0.4.2"],
+ icon: nil)
+ #expect(options[.applicationName] as? String == "TurboFieldfare")
+ #expect(options[.applicationVersion] as? String == "0.4.2")
+ #expect(options[.applicationIcon] == nil)
+ #expect(options[.credits] != nil)
+ }
+
+ @MainActor
+ @Test func creditsLinkToTheLicenseAndTheRepository() {
+ let credits = AboutPanelPresentation.credits()
+ let text = credits.string
+ #expect(text.contains("Apache License 2.0"))
+ #expect(text.contains(AboutPanelPresentation.repositoryLinkText))
+
+ var links: [URL] = []
+ credits.enumerateAttribute(.link,
+ in: NSRange(location: 0, length: credits.length)) { value, _, _ in
+ if let url = value as? URL { links.append(url) }
+ }
+ #expect(links.count == 2)
+ #expect(links.contains(AboutPanelPresentation.repositoryURL))
+ }
+}
diff --git a/Tests/TurboFieldfareApp/MacPresentation/ModelRevealPolicyTests.swift b/Tests/TurboFieldfareApp/MacPresentation/ModelRevealPolicyTests.swift
new file mode 100644
index 00000000..e30a4198
--- /dev/null
+++ b/Tests/TurboFieldfareApp/MacPresentation/ModelRevealPolicyTests.swift
@@ -0,0 +1,49 @@
+import Foundation
+import Testing
+@testable import TurboFieldfareMacPresentation
+
+@Suite struct ModelRevealPolicyTests {
+ @Test func installedModelDirectoryIsSelected() {
+ let target = ModelRevealPolicy.target(
+ forModelPath: "/Users/dev/checkout/scratch/gemma4.gturbo",
+ fileExists: { $0 == "/Users/dev/checkout/scratch/gemma4.gturbo" })
+ #expect(target == .selectItem(
+ URL(fileURLWithPath: "/Users/dev/checkout/scratch/gemma4.gturbo",
+ isDirectory: true)))
+ }
+
+ @Test func missingModelFallsBackToItsContainer() {
+ let target = ModelRevealPolicy.target(
+ forModelPath: "/Users/dev/checkout/scratch/gemma4.gturbo",
+ fileExists: { $0 == "/Users/dev/checkout/scratch" })
+ #expect(target == .openContainer(
+ URL(fileURLWithPath: "/Users/dev/checkout/scratch", isDirectory: true)))
+ }
+
+ @Test func missingContainerIsUnavailable() {
+ let target = ModelRevealPolicy.target(
+ forModelPath: "/Users/dev/checkout/scratch/gemma4.gturbo",
+ fileExists: { _ in false })
+ #expect(target == .unavailable)
+ }
+
+ @Test(arguments: ["", " "])
+ func blankPathIsUnavailable(path: String) {
+ #expect(ModelRevealPolicy.target(forModelPath: path,
+ fileExists: { _ in true }) == .unavailable)
+ }
+
+ @Test func pathIsStandardizedBeforeReveal() {
+ let target = ModelRevealPolicy.target(
+ forModelPath: "/Users/dev/checkout/./scratch/../scratch/gemma4.gturbo",
+ fileExists: { $0 == "/Users/dev/checkout/scratch/gemma4.gturbo" })
+ #expect(target == .selectItem(
+ URL(fileURLWithPath: "/Users/dev/checkout/scratch/gemma4.gturbo",
+ isDirectory: true)))
+ }
+
+ @Test func rootPathDoesNotLoopIntoItself() {
+ #expect(ModelRevealPolicy.target(forModelPath: "/",
+ fileExists: { _ in false }) == .unavailable)
+ }
+}
diff --git a/Tests/TurboFieldfareServer/OpenAIValidationTests.swift b/Tests/TurboFieldfareServer/OpenAIValidationTests.swift
index 18a8b254..d2a8b30e 100644
--- a/Tests/TurboFieldfareServer/OpenAIValidationTests.swift
+++ b/Tests/TurboFieldfareServer/OpenAIValidationTests.swift
@@ -564,6 +564,11 @@ struct ServerArgumentTests {
#expect(arguments.maxContext == 16_384)
#expect(arguments.queueLimit == 4)
#expect(arguments.promptCacheMode == .singlePrefix)
+ #expect(arguments.expertCacheSlots == 16)
+ #expect(arguments.expertCachePolicy == .lfu)
+ #expect(arguments.prefillPolicy == .chunked)
+ #expect(arguments.prefillChunkTokens == 128)
+ #expect(arguments.rdadvisePolicy == .off)
}
@Test func parsesSinglePrefixModeAndRejectsUnknownMode() throws {
@@ -584,4 +589,62 @@ struct ServerArgumentTests {
])
}
}
+
+ @Test func runtimeFlagsReachTheResolvedConfiguration() throws {
+ let arguments = try ServerArguments.parse([
+ "--model", "model.gturbo",
+ "--expert-cache-slots", "32",
+ "--expert-cache-policy", "lru",
+ "--prefill", "on",
+ "--prefill-chunk-tokens", "64",
+ "--rdadvise", "adaptive",
+ ])
+ #expect(arguments.expertCacheSlots == 32)
+ #expect(arguments.expertCachePolicy == .lru)
+ #expect(arguments.prefillPolicy == .chunked)
+ #expect(arguments.prefillChunkTokens == 64)
+ #expect(arguments.rdadvisePolicy == .adaptive)
+
+ let configuration = try arguments.resolvedRuntimeConfiguration()
+ #expect(configuration.expertCacheSlots == 32)
+ #expect(configuration.expertCachePolicy == .lru)
+ #expect(configuration.prefillPolicy == .chunked)
+ #expect(configuration.prefillChunkTokens == 64)
+ #expect(configuration.rdadvisePolicy == .adaptive)
+ }
+
+ @Test func prefillOffIsResolvableBelowTheChunkedPrefillSlotFloor() throws {
+ let arguments = try ServerArguments.parse([
+ "--model", "model.gturbo",
+ "--expert-cache-slots", "8",
+ "--prefill", "off",
+ ])
+ let configuration = try arguments.resolvedRuntimeConfiguration()
+ #expect(configuration.expertCacheSlots == 8)
+ #expect(configuration.prefillPolicy == .off)
+ }
+
+ @Test func chunkedPrefillBelowTheSlotFloorIsRejected() throws {
+ let arguments = try ServerArguments.parse([
+ "--model", "model.gturbo",
+ "--expert-cache-slots", "8",
+ "--prefill", "on",
+ ])
+ #expect(throws: ServerArgumentError.self) {
+ try arguments.resolvedRuntimeConfiguration()
+ }
+ }
+
+ @Test(arguments: [
+ ["--expert-cache-slots", "12"],
+ ["--expert-cache-policy", "mru"],
+ ["--prefill", "maybe"],
+ ["--prefill-chunk-tokens", "256"],
+ ["--rdadvise", "eager"],
+ ])
+ func rejectsUnsupportedRuntimeValues(flag: [String]) throws {
+ #expect(throws: ServerArgumentError.self) {
+ try ServerArguments.parse(["--model", "model.gturbo"] + flag)
+ }
+ }
}
diff --git a/docs/OPENAI_SERVER.md b/docs/OPENAI_SERVER.md
index d2bf4ebb..212a2106 100644
--- a/docs/OPENAI_SERVER.md
+++ b/docs/OPENAI_SERVER.md
@@ -47,6 +47,31 @@ requests for preparation or queueing. The limit is enforced before prompt
rendering and tokenization. Use `--queue-limit` to change it. Press Control-C
to stop the server.
+## Runtime settings
+
+The server accepts the same runtime flags as the CLI, with the same values and
+defaults. See [Runtime controls](RUNTIME_CONTROLS.md) for what each one does.
+
+```bash
+.build/release/TurboFieldfareServer \
+ --model scratch/gemma4.gturbo \
+ --expert-cache-slots 32 \
+ --expert-cache-policy lru \
+ --prefill on \
+ --prefill-chunk-tokens 64 \
+ --rdadvise bounded
+```
+
+Without these flags the server runs the production defaults: 16 expert-cache
+slots, LFU eviction, chunked prefill on with 128-token chunks, and read advice
+off. Values are validated before the model loads, so an unsupported one exits
+with the usage text rather than failing partway through startup. Chunked
+prefill needs at least 16 expert-cache slots, so `--expert-cache-slots 8`
+requires `--prefill off`.
+
+The settings are fixed for the life of the process. Restart the server to
+change them.
+
## Connect a client
The base URL is `http://127.0.0.1:8080/v1`. Some client libraries require an
diff --git a/docs/RUNTIME_CONTROLS.md b/docs/RUNTIME_CONTROLS.md
index 45da4b90..67d029d4 100644
--- a/docs/RUNTIME_CONTROLS.md
+++ b/docs/RUNTIME_CONTROLS.md
@@ -1,8 +1,9 @@
# Runtime controls
-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.
+The Mac app, CLI, and local server 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,7 +25,11 @@ benchmark protocol.
## Runtime settings
-| Control | Mac values | CLI flag | Production default | Effect |
+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
+model, so an unsupported combination fails immediately with the usage text.
+
+| Control | Mac values | CLI and server 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. |
@@ -36,7 +41,8 @@ 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 CLI invocation loads a new model
-process, so its selected runtime settings apply immediately.
+process, so its selected runtime settings apply immediately. The server fixes
+its runtime settings at startup, so changing one means restarting the process.
## Run an experiment