Gemma 4 26B-A4B inference in ~2 GB of RAM on any M-series MacBook
Swift apple-silicongemmagemma4gemma4-26b-a4bgpgpullmllm-inferencelocal-aimacosmetalon-device-aion-device-llmswift
Update public runtime for Gemma 4 IT (#2)
Andrey Mikhaylova3516662d588
diff --git a/AGENTS.md b/AGENTS.mdindex ed8d7c36..aebebbfd 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -37,4 +37,11 @@ Report the commit, hardware and RAM, macOS, Swift version, exact command, exit c## App controls-The Mac app exposes generation controls plus cache slots, LFU/LRU, prefill, FP16 or K4/V4 KV, RDADVISE, and verification. Interactive generation defaults to 1,024 new tokens, temperature 1.0, Top-K 64, Top-P 0.95, and repetition penalty off at 1.0. Start with production defaults. The HUD reports rate, tokens, and decode-service memory; Last run adds TTFT and I/O. The app must be built with its sibling `TurboFieldfareDecodeService`; it never falls back to loading a second in-process model. See [README](README.md) and [Runtime controls](docs/RUNTIME_CONTROLS.md).+The Mac app sends prompts through the pinned Gemma 4 IT chat format. It+exposes context length, temperature, Top-K, Top-P, expert-cache slots, prefill,+and RDADVISE. The defaults are temperature `0.2`, Top-K `64`, and Top-P `0.95`.+Responses can use the context space left after formatting the prompt, and FP16+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).diff --git a/Package.swift b/Package.swiftindex 3aadd7e2..6faf007e 100644--- a/Package.swift+++ b/Package.swift@@ -51,7 +51,15 @@ let package = Package(.target(name: "TurboFieldfareAppCore",dependencies: ["TurboFieldfare", "TurboFieldfareRepackCore", "TurboFieldfareDecodeProtocol"],- path: "Sources/TurboFieldfareApp/Core"+ path: "Sources/TurboFieldfareApp/Core",+ resources: [+ .copy("Resources/app-prompts.json"),+ ]+ ),+ .target(+ name: "TurboFieldfareMacPresentation",+ dependencies: ["TurboFieldfareAppCore"],+ path: "Sources/TurboFieldfareApp/MacPresentation"),.target(name: "TurboFieldfareDecodeProtocol",@@ -64,7 +72,7 @@ let package = Package(),.executableTarget(name: "TurboFieldfareMac",- dependencies: ["TurboFieldfareAppCore"],+ dependencies: ["TurboFieldfareAppCore", "TurboFieldfareMacPresentation"],path: "Sources/TurboFieldfareApp/Mac",resources: [.copy("Resources/turbofieldfare-app-icon.png"),@@ -90,5 +98,10 @@ let package = Package(dependencies: ["TurboFieldfareAppCore", "TurboFieldfare", "TurboFieldfareRepackCore", "TurboFieldfareDecodeProtocol"],path: "Tests/TurboFieldfareApp/Core"),+ .testTarget(+ name: "TurboFieldfareMacPresentationTests",+ dependencies: ["TurboFieldfareMacPresentation"],+ path: "Tests/TurboFieldfareApp/MacPresentation"+ ),])diff --git a/README.md b/README.mdindex ae57c1ab..7fda65d5 100644--- a/README.md+++ b/README.md@@ -6,7 +6,7 @@<p align="center"><strong>Gemma 4 26B-A4B inference in about 2 GB of RAM</strong><br>- A custom Swift + Metal runtime for Apple Silicon Macs, even the 8 GB ones.+ A custom Swift + Metal runtime for any Apple Silicon Mac, even the 8 GB ones.</p><p align="center">@@ -29,18 +29,12 @@Memory got expensive. So I gave a 26-billion-parameter model a ~2 GB budget.-TurboFieldfare runs **[Gemma 4 26B-A4B](https://ai.google.dev/gemma/docs/core/model_card_4)** on Apple Silicon by keeping the common-weights, working buffers, and a 4K-context KV cache in unified memory. The-routed-expert pool stays on SSD and is read on demand.--Even at 4 bits, the text-only model occupies about 14.5 GB. Keeping the complete-checkpoint resident on the target 8 GB M2 MacBook Air would exceed physical-memory before allocating the KV cache.--Gemma's mixture-of-experts layers create an opening: each layer has 128 routed-experts, but each token uses only 8. TurboFieldfare keeps the 1.58 GB common-core in unified memory and reads only the experts selected for the current-layer.+TurboFieldfare runs the instruction-tuned+**[Gemma 4 26B-A4B](https://ai.google.dev/gemma/docs/core/model_card_4)**+without loading the entire 14.3 GB model into memory. It keeps the shared+1.35 GB core and FP16 KV cache in memory, then streams only the experts needed+for each token from SSD. This is what lets the model run on Macs with 8 GB of+RAM.The runtime, streaming installer, CLI, and native Mac app are written in Swiftand Metal. TurboFieldfare is model-specific rather than a wrapper around MLX or@@ -69,14 +63,14 @@ your prompt, and press **Generate**.| Metric | Value || --------------- | ------------------------------------------------------------------------------------------------------------------------ |-| Model | Gemma 4 26B-A4B, 26B total parameters, ~3.88B active per token |-| Weights | MLX affine 4-bit, group 64, with 8-bit router and shared-expert overrides |-| Memory | ~1.9 GB common model, KV, and scratch allocation at 4K; expert-slot and file-cache residency varies with use |-| Storage | ~14.5 GB text-only `.gturbo` model installation |-| Hardware | Apple Silicon Mac; validated on an 8 GB M2 MacBook Air |+| 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 |+| 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 |-| M5 measured decode | [32.0-36.1 tok/s](docs/BENCHMARKS.md#m5-measured-decode) on a 24 GB M5 Pro |+| M5 measured decode | [31-35 tok/s](docs/BENCHMARKS.md#m5-measured-decode) on a 24 GB M5 Pro |The measured result is a reference point, not a performance ceiling. Promptlength, generated length, page-cache state, and hardware all affect throughput.@@ -96,7 +90,7 @@ The Swift package exposes five products:| `TurboFieldfare` | Swift library containing the runtime and Metal kernels || `TurboFieldfareMac` | Native Mac app for installation and generation || `TurboFieldfareDecodeService` | One-shot local model and Metal owner used by the Mac app |-| `TurboFieldfareCLI` | Command-line text completion |+| `TurboFieldfareCLI` | Command-line instruction chat and raw completion || `TurboFieldfareRepack` | Streaming model installer and install verifier |### Requirements@@ -104,26 +98,24 @@ The Swift package exposes five products:- An Apple Silicon Mac; the validated target is an 8 GB M2 MacBook Air- macOS 26 with Metal 4- Xcode 26 and Swift 6.2 or newer-- Enough free storage for the ~14.5 GB model installation+- Enough free storage for the ~14.3 GB model installation- An internet connection for the first model installThe package is arm64-only. Older macOS and Metal versions are not supported.### Prompting the model-> [!IMPORTANT]-> TurboFieldfare performs **text completion**, not instruction following.-> The Mac app and CLI pass prompts directly to the base model without an-> instruction or chat template. Write text you want continued, such as `The-> capital of France is` or `Q: Why is the sky blue?\nA:`.+The Mac app treats what you type as an instruction and handles Gemma's chat+formatting automatically. Just describe the task and include any context the+model needs.-The interactive default generates up to 1,024 new tokens with temperature-`1.0`, Top-K `64`, and Top-P `0.95`. The repetition penalty is off (`1.0`).-Temperature `0` selects deterministic greedy decoding. The model may still-repeat, loop, or produce incorrect text, so review its continuation.+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.-For help writing effective prompts, see Google’s [Gemma prompt guide](https://ai.google.dev/gemma/docs/capabilities/text/basic).-TurboFieldfare handles model tokenization, so enter only the prompt text rather than Gemma’s control tokens.+TurboFieldfare is text-only. It supports user and model messages, plus an+optional system message at the start of a conversation. Tool calling, images,+and audio are not supported.### Mac app@@ -150,7 +142,7 @@ checkpoint on disk and keeps scratch memory bounded.The first installation transfers about 15 GB through bounded Hugging Facerange requests. Network speed and Hugging Face response times vary, so it can-take a while. The completed `.gturbo` installation occupies about 14.5 GB and+take a while. The completed `.gturbo` installation occupies about 14.3 GB andis accepted only after its manifest and file hashes have been validated.Installation does not load the model into memory.@@ -163,13 +155,10 @@ After installation:3. Choose **Generate**, or press <kbd>Command</kbd>+<kbd>Return</kbd>.4. Use the stop button or <kbd>Escape</kbd> to end generation early.-The status bar reports the current phase, generated tokens, decode rate, and-decode-service memory use. The fixed right settings pane controls sampling,-context length, the expert cache, and runtime options. Settings that affect the-loaded runtime require a reload before the next generation. During chunked-prefill, the app reports exact progress such as `Prefill (128/514)`. See-[Runtime controls](docs/RUNTIME_CONTROLS.md) for the allowed values, defaults,-and result metrics.+The status bar shows generation progress, decode speed, and memory use. Use the+right pane to configure sampling, context length, expert-cache slots, and+runtime options. See [Runtime controls](docs/RUNTIME_CONTROLS.md) for details+and defaults.### Command-line interface@@ -194,9 +183,31 @@ swift run -c release TurboFieldfareRepack \--input-gturbo scratch/gemma4.gturbo```+#### Instruction chat++Put chat messages in a JSON array and pass it with `--messages-file`:++```json+[+ {"role": "user", "content": "Explain why chunked prefill reduces time to first token while keeping memory bounded."}+]+```++```bash+swift run -c release TurboFieldfareCLI \+ --model scratch/gemma4.gturbo \+ --messages-file messages.json+```++This formats messages in the same way as the Mac app. The CLI response limit+is set with `--max-new`, which defaults to 1,024 tokens. The Mac app can+generate until the selected context window is full.+#### Raw completion-`--prompt` passes text directly to the model without applying a chat template:+`--prompt` is available for raw completion and reproducible comparisons. It+passes the text directly to the model without chat formatting. Use+`--messages-file` for instruction-response conversations.```bashswift run -c release TurboFieldfareCLI \@@ -206,8 +217,7 @@ swift run -c release TurboFieldfareCLI \--temperature 0```-This example deliberately requests a short greedy completion. Omitting its-generation overrides uses the same interactive defaults as the Mac app.+This example deliberately requests a short greedy completion.Common generation options include `--max-context`, `--temperature`, `--top-k`,`--top-p`, `--repetition-penalty`, `--seed`, and repeatable `--stop` strings.@@ -261,21 +271,21 @@ correctness invariants.TurboFieldfare currently includes:- Remote streaming repack into the `.gturbo` model format-- 4-bit MLX affine weights with 8-bit router and shared-expert overrides+- Instruction-tuned Gemma 4 26B-A4B with verified text-only 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,RoPE, sampling, and production fusions- SSD-backed routed-expert streaming with a bounded expert cache-- Chunked single-prompt prefill and token-by-token generation with a production- FP16 KV ring through 4K+- Chunked single-prompt prefill and token-by-token generation+- FP16 KV storage with bounded circular storage for 25 sliding-window layers+ and linear storage for 5 full-attention layers+- Exact split-K/V decode attention with distinct normalized K and V paths- A Swift library, streaming installer, command-line interface, and nativeSwiftUI/AppKit Mac app with a one-shot local decode serviceCurrent scope is text-only inference from the pinned Gemma 4 26B-A4B-checkpoint on Apple Silicon Macs. The 8 GB M2 MacBook Air is the deployment-and compatibility reference; the 24 GB M5 Pro is the current performance host.--The Mac app exposes the experimental packed K4/V4 KV path as an explicit-control. It is not the default because it failed the full quality gate.+instruction checkpoint on Apple Silicon Macs with at least 8 GB of RAM.### Future work@@ -289,8 +299,8 @@ control. It is not the default because it failed the full quality gate.The [experiments that shaped TurboFieldfare](docs/OPTIMIZATION_JOURNEY.md)explain the largest wins, the plausible ideas that failed, and the earlyresults that reversed under stronger validation. The detailed-[experiment record](docs/experiments/EXPERIMENT_INVENTORY.md) keeps all 102 audited entries-as optional evidence; neither document requires the private benchmark archive.+[experiment record](docs/experiments/EXPERIMENT_INVENTORY.md) keeps all 102+audited entries as optional evidence.Useful entry points:diff --git a/Sources/TurboFieldfare/Infrastructure/Metal/MetalContext.swift b/Sources/TurboFieldfare/Infrastructure/Metal/MetalContext.swiftindex 117a0b71..450c1513 100644--- a/Sources/TurboFieldfare/Infrastructure/Metal/MetalContext.swift+++ b/Sources/TurboFieldfare/Infrastructure/Metal/MetalContext.swift@@ -73,7 +73,7 @@ public final class MetalContext: @unchecked Sendable {"attention","moe","logit",- "turboquant",+ "utility","fused","prefill",]@@ -90,7 +90,7 @@ public final class MetalContext: @unchecked Sendable {"rmsnorm": "Metal/Primitives","rope": "Metal/Primitives","tensorops": "Metal/TensorCore",- "turboquant": "Metal/KVCache",+ "utility": "Metal/Primitives",]private static func shaderURL(module: String) -> URL? {diff --git a/Sources/TurboFieldfare/Infrastructure/ModelIO/ManifestReader.swift b/Sources/TurboFieldfare/Infrastructure/ModelIO/ManifestReader.swiftindex c8848e65..a7276626 100644--- a/Sources/TurboFieldfare/Infrastructure/ModelIO/ManifestReader.swift+++ b/Sources/TurboFieldfare/Infrastructure/ModelIO/ManifestReader.swift@@ -29,13 +29,31 @@ public struct ManifestArch: Decodable, Equatable, Sendable {public let fullAttentionLayerMask: [Int]}+public struct ManifestQuantSlot: Decodable, Equatable, Sendable {+ public let weightBits: Int+ public let scheme: String+ public let scaleType: String+ public let biasType: String+ public let groupSize: Int+}++public struct ManifestQuant: Decodable, Equatable, Sendable {+ public let embedding: ManifestQuantSlot+ public let attention: ManifestQuantSlot+ public let router: ManifestQuantSlot+ public let sharedExpert: ManifestQuantSlot+ public let routedExpert: ManifestQuantSlot+}+public struct Manifest: Decodable, Equatable, Sendable {public let magic: Stringpublic let versionMajor: Intpublic let versionMinor: Intpublic let flags: [String: Bool]public let modelID: String+ public let sourceSnapshotHash: String?public let arch: ManifestArch+ public let quant: ManifestQuant?public let files: [String: ManifestFileEntry]public let expertsPerLayer: Intpublic let numLayers: Int@@ -80,7 +98,8 @@ public enum ManifestReader {throw ModelError.indexCorrupt(detail: "manifest.json: \(error)")}- try validate(manifest, against: expecting)+ try validate(manifest, against: expecting,+ directoryURL: directoryURL)return manifest}@@ -94,7 +113,8 @@ public enum ManifestReader {}static func validate(_ m: Manifest,- against expected: ArchConfig) throws {+ against expected: ArchConfig,+ directoryURL: URL) throws {guard m.magic == "GTURBO" else { throw ModelError.notAGTurboDirectory }guard m.versionMajor == 1 else {throw ModelError.unsupportedVersion(major: m.versionMajor, minor: m.versionMinor)@@ -104,7 +124,17 @@ public enum ManifestReader {throw ModelError.unknownFlag(name: key)}}+ if m.flags["turboQuantKV"] == true {+ throw ModelError.indexCorrupt(+ detail: "manifest requests removed TurboQuant KV runtime support")+ }try validateArch(m.arch, expected: expected)+ if let quant = m.quant {+ try validateQuant(quant)+ } else if expected.numLayers == ArchConfig.gemma4_26B_A4B.numLayers,+ expected.hiddenSize == ArchConfig.gemma4_26B_A4B.hiddenSize {+ throw ModelError.indexCorrupt(detail: "manifest.quant is required for the production architecture")+ }let pageSize = UInt64(getpagesize())guard m.expertStride % pageSize == 0 else {throw ModelError.expertStrideNotPageAligned(stride: m.expertStride,@@ -122,6 +152,25 @@ public enum ManifestReader {}}+ private static func validateQuant(_ quant: ManifestQuant) throws {+ let slots: [(String, ManifestQuantSlot, Set<Int>)] = [+ ("embedding", quant.embedding, [4]),+ ("attention", quant.attention, [4]),+ ("router", quant.router, [8]),+ ("sharedExpert", quant.sharedExpert, [4, 8]),+ ("routedExpert", quant.routedExpert, [4]),+ ]+ for (name, slot, allowedBits) in slots {+ guard allowedBits.contains(slot.weightBits),+ slot.scheme.lowercased() == "affine",+ slot.scaleType.lowercased() == "bf16",+ slot.biasType.lowercased() == "bf16",+ slot.groupSize == Quantization.groupSize else {+ throw ModelError.indexCorrupt(detail: "unsupported quantization for \(name)")+ }+ }+ }+private static func validateArch(_ a: ManifestArch,expected e: ArchConfig) throws {func check<T: Equatable & CustomStringConvertible>(diff --git a/Sources/TurboFieldfare/Kernels/Attention/Attention.swift b/Sources/TurboFieldfare/Kernels/Attention/Attention.swiftindex 788f0886..2571ea6e 100644--- a/Sources/TurboFieldfare/Kernels/Attention/Attention.swift+++ b/Sources/TurboFieldfare/Kernels/Attention/Attention.swift@@ -1,50 +1,6 @@import Foundationimport Metal-struct AttentionTurboQuantKVParams {- var headDim: UInt32- var numQHeads: UInt32- var numKVHeads: UInt32- var seqLen: UInt32- var kvStart: UInt32- var scale: Float- var layer: UInt32- var rotationSeed: UInt32- var keyBytesPerHead: UInt32- var keyPackedOffset: UInt32- var keyScaleOffset: UInt32- var valueBytesPerHead: UInt32- var valuePackedOffset: UInt32- var valueScaleOffset: UInt32- var qPretransformed: UInt32-- init(headDim: UInt32,- numQHeads: UInt32,- numKVHeads: UInt32,- seqLen: UInt32,- kvStart: UInt32,- scale: Float,- layer: UInt32,- rotationSeed: UInt32,- keyLayout: TurboQuantKVRoleLayout,- valueLayout: TurboQuantKVRoleLayout) {- self.headDim = headDim- self.numQHeads = numQHeads- self.numKVHeads = numKVHeads- self.seqLen = seqLen- self.kvStart = kvStart- self.scale = scale- self.layer = layer- self.rotationSeed = rotationSeed- self.keyBytesPerHead = UInt32(keyLayout.bytesPerHead)- self.keyPackedOffset = UInt32(keyLayout.packedOffsetPerHead)- self.keyScaleOffset = UInt32(keyLayout.scaleOffsetPerHead)- self.valueBytesPerHead = UInt32(valueLayout.bytesPerHead)- self.valuePackedOffset = UInt32(valueLayout.packedOffsetPerHead)- self.valueScaleOffset = UInt32(valueLayout.scaleOffsetPerHead)- self.qPretransformed = 0- }-}struct AttentionSplitGeometry: Sendable, Equatable {let effectiveLength: Int@@ -54,12 +10,6 @@ struct AttentionSplitGeometry: Sendable, Equatable {let useSWAGroupedPartial: Bool}-struct AttentionTurboQuantSplitGeometry: Sendable, Equatable {- let chunkLen: Int- let numChunks: Int- let partialThreadgroups: Int- let useGQAPartial: Bool-}/// Swift wrapper for sliding-window and full-causal decode attention.///@@ -78,7 +28,6 @@ final class Attention {private let psoPartial: MTLComputePipelineStateprivate let psoGQAPartial: MTLComputePipelineStateprivate let psoCombine: MTLComputePipelineState- private let psoMLXGeometryFullV2: MTLComputePipelineStateprivate let psoPartialSWA: MTLComputePipelineStateprivate let psoPartialFull: MTLComputePipelineStateprivate let psoGQAPartialSWA: MTLComputePipelineState@@ -88,10 +37,6 @@ final class Attention {private let psoCombineFull: MTLComputePipelineStateprivate let psoCombineSWAChunks16: MTLComputePipelineStateprivate let psoCombineFullChunks16: MTLComputePipelineState- private let psoTurboQuantQTransformK4V4: MTLComputePipelineState- private let psoTurboQuantPartialK4V4: MTLComputePipelineState- private let psoTurboQuantGQAPartialK4V4: MTLComputePipelineState- private let psoTurboQuantCombineK4V4: MTLComputePipelineState/// Mirrors `kAttnThreads` in `attention.metal`. The kernel was authored/// with a hardcoded 256-thread group so its threadgroup-memory scratch@@ -107,7 +52,6 @@ final class Attention {/// Full attention uses 16 base chunks by default.private static let defaultFullChunks = 16private static let defaultGQASWAChunks = 8- private static let defaultTurboQuantGQASWAChunks = 8// Partial state written by pass 1, read by pass 2. One shared allocation:// attention runs once per layer, serially, and pass 2 hazard-tracks pass 1@@ -115,18 +59,12 @@ final class Attention {private let mPartial: MTLBufferprivate let dPartial: MTLBufferprivate let oPartial: MTLBuffer- private let qTurboQuant: MTLBufferinit(context: MetalContext) throws {self.ctx = contextself.psoPartial = try context.pipeline("attention_decode_partial")self.psoGQAPartial = try context.pipeline("attention_decode_gqa_swa_partial")self.psoCombine = try context.pipeline("attention_decode_combine")- self.psoMLXGeometryFullV2 = try context.pipeline("attention_decode_mlx_geometry_full_v2")- self.psoTurboQuantQTransformK4V4 = try context.pipeline("attention_turboquant_q_rht")- self.psoTurboQuantPartialK4V4 = try context.pipeline("attention_turboquant_decode_partial")- self.psoTurboQuantGQAPartialK4V4 = try context.pipeline("attention_turboquant_decode_gqa_swa_partial")- self.psoTurboQuantCombineK4V4 = try context.pipeline("attention_turboquant_decode_combine")self.psoPartialSWA = try Self.specializedPipeline(context,"attention_decode_partial",headDim: 256,@@ -182,13 +120,10 @@ final class Attention {let d = context.device.makeBuffer(length: md * MemoryLayout<Float>.size,options: .storageModeShared),let o = context.device.makeBuffer(length: md * Self.maxHeadDim * MemoryLayout<Float>.size,- options: .storageModeShared),- let tq = context.device.makeBuffer(length: Self.maxQHeads * Self.maxHeadDim * MemoryLayout<Float16>.size,- options: .storageModeShared) else {+ options: .storageModeShared) else {throw MetalError.missingFunction("attention split-KV scratch")}self.mPartial = m; self.dPartial = d; self.oPartial = o- self.qTurboQuant = tq}/// Number of K/V chunks for a range of `effLen` positions — the split@@ -221,32 +156,6 @@ final class Attention {useSWAGroupedPartial: useSWAGQAPartial)}- static func turboQuantChunkCount(effLen: Int, preferGQASWA: Bool = false) -> Int {- let eff = max(1, effLen)- let defaultChunks = preferGQASWA ? defaultTurboQuantGQASWAChunks : defaultFullChunks- return max(1, min(defaultChunks, min(maxChunks, eff)))- }-- static func turboQuantSplitGeometry(- params: AttentionTurboQuantKVParams- ) -> AttentionTurboQuantSplitGeometry {- precondition(params.numQHeads % params.numKVHeads == 0,- "numQHeads must be a multiple of numKVHeads for GQA")- let qPerKV = Int(params.numQHeads / params.numKVHeads)- let useGQAPartial = qPerKV <= 2- let effLen = Int(params.seqLen - params.kvStart)- let baseChunks = Self.turboQuantChunkCount(effLen: effLen,- preferGQASWA: useGQAPartial)- let nChunks = useGQAPartial- ? max(baseChunks, min(Self.maxChunks, baseChunks * qPerKV))- : baseChunks- let chunkLen = (max(1, effLen) + nChunks - 1) / nChunks- let partialGroups = (useGQAPartial ? Int(params.numKVHeads) : Int(params.numQHeads)) * nChunks- return AttentionTurboQuantSplitGeometry(chunkLen: chunkLen,- numChunks: nChunks,- partialThreadgroups: partialGroups,- useGQAPartial: useGQAPartial)- }/// Sliding-window attention. `window` caps the K/V positions to the most/// recent `window` entries (`[max(0, seqLen-window), seqLen)`).@@ -301,21 +210,6 @@ final class Attention {precondition(seqLen > 0, "full attention requires at least one KV position")let sc = scale ?? Self.defaultScale(headDim: headDim)- if headDim == 512,- numQHeads == 16,- numKVHeads == 2,- sc == 1.0,- psoMLXGeometryFullV2.maxTotalThreadsPerThreadgroup >= 1024 {- encodeMLXGeometryFullV2(commandBuffer: commandBuffer,- pipeline: psoMLXGeometryFullV2,- q: q, qOffset: qOffset,- k: k, kOffset: kOffset,- v: v, vOffset: vOffset,- out: out, outOffset: outOffset,- seqLen: seqLen,- scale: sc)- return- }encodeSplit(commandBuffer: commandBuffer,q: q, qOffset: qOffset, k: k, kOffset: kOffset,@@ -325,149 +219,6 @@ final class Attention {preferGQASWA: false)}- private func encodeMLXGeometryFullV2(commandBuffer: MTLCommandBuffer,- pipeline: MTLComputePipelineState,- q: MTLBuffer, qOffset: Int,- k: MTLBuffer, kOffset: Int,- v: MTLBuffer, vOffset: Int,- out: MTLBuffer, outOffset: Int,- seqLen: UInt32,- scale: Float) {- guard let enc = commandBuffer.makeComputeCommandEncoder() else { return }- enc.setComputePipelineState(pipeline)- enc.setBuffer(q, offset: qOffset, index: 0)- enc.setBuffer(k, offset: kOffset, index: 1)- enc.setBuffer(v, offset: vOffset, index: 2)- enc.setBuffer(out, offset: outOffset, index: 3)- var length = seqLen- var scoreScale = scale- enc.setBytes(&length, length: MemoryLayout<UInt32>.size, index: 4)- enc.setBytes(&scoreScale, length: MemoryLayout<Float>.size, index: 5)- enc.dispatchThreadgroups(MTLSize(width: 16, height: 1, depth: 1),- threadsPerThreadgroup: MTLSize(width: 1024,- height: 1,- depth: 1))- enc.endEncoding()- }-- /// Split-KV packed-TurboQuant attention. Pass 1 computes per-chunk online- /// softmax state in RHT domain; pass 2 merges chunks and inverse-RHTs once.- func encodeTurboQuantSplit(commandBuffer: MTLCommandBuffer,- q: MTLBuffer, qOffset: Int = 0,- keyCache: MTLBuffer, keyCacheOffset: Int = 0,- valueCache: MTLBuffer, valueCacheOffset: Int = 0,- out: MTLBuffer, outOffset: Int = 0,- params: AttentionTurboQuantKVParams) {- precondition(params.numQHeads % params.numKVHeads == 0,- "numQHeads must be a multiple of numKVHeads for GQA")- precondition(Int(params.numQHeads) <= Self.maxQHeads,- "numQHeads \(params.numQHeads) exceeds split-KV scratch (max \(Self.maxQHeads))")- precondition(Int(params.headDim) <= Self.maxHeadDim,- "head_dim \(params.headDim) exceeds split-KV scratch (max \(Self.maxHeadDim))")- precondition(params.kvStart <= params.seqLen,- "kvStart must be inside the KV range")-- let geometry = Self.turboQuantSplitGeometry(params: params)-- encodeTurboQuantQTransform(commandBuffer: commandBuffer,- q: q,- qOffset: qOffset,- params: params)-- encodeTurboQuantPartial(commandBuffer: commandBuffer,- keyCache: keyCache,- keyCacheOffset: keyCacheOffset,- valueCache: valueCache,- valueCacheOffset: valueCacheOffset,- params: params,- geometry: geometry)-- encodeTurboQuantCombine(commandBuffer: commandBuffer,- out: out,- outOffset: outOffset,- params: params,- geometry: geometry)- }-- func encodeTurboQuantQTransform(commandBuffer: MTLCommandBuffer,- q: MTLBuffer,- qOffset: Int = 0,- params: AttentionTurboQuantKVParams) {- guard let qEnc = commandBuffer.makeComputeCommandEncoder() else { return }- let qTransformPSO = psoTurboQuantQTransformK4V4- qEnc.setComputePipelineState(qTransformPSO)- qEnc.setBuffer(q, offset: qOffset, index: 0)- qEnc.setBuffer(qTurboQuant, offset: 0, index: 1)- var qParams = params- qEnc.setBytes(&qParams, length: MemoryLayout<AttentionTurboQuantKVParams>.size, index: 2)- let qTGWidth = min(Self.threadsPerGroup,- Int(qTransformPSO.maxTotalThreadsPerThreadgroup))- qEnc.dispatchThreadgroups(MTLSize(width: Int(params.numQHeads), height: 1, depth: 1),- threadsPerThreadgroup: MTLSize(width: qTGWidth,- height: 1,- depth: 1))- qEnc.endEncoding()- }-- func encodeTurboQuantPartial(commandBuffer: MTLCommandBuffer,- keyCache: MTLBuffer,- keyCacheOffset: Int = 0,- valueCache: MTLBuffer,- valueCacheOffset: Int = 0,- params: AttentionTurboQuantKVParams,- geometry: AttentionTurboQuantSplitGeometry) {- guard let p1 = commandBuffer.makeComputeCommandEncoder() else { return }- p1.setComputePipelineState(- geometry.useGQAPartial ? psoTurboQuantGQAPartialK4V4 : psoTurboQuantPartialK4V4)- p1.setBuffer(qTurboQuant, offset: 0, index: 0)- p1.setBuffer(keyCache, offset: keyCacheOffset, index: 1)- p1.setBuffer(valueCache, offset: valueCacheOffset, index: 2)- p1.setBuffer(mPartial, offset: 0, index: 3)- p1.setBuffer(dPartial, offset: 0, index: 4)- p1.setBuffer(oPartial, offset: 0, index: 5)- var p = params- p.qPretransformed = 1- var cl = UInt32(geometry.chunkLen)- var nc = UInt32(geometry.numChunks)- p1.setBytes(&p, length: MemoryLayout<AttentionTurboQuantKVParams>.size, index: 6)- p1.setBytes(&cl, length: MemoryLayout<UInt32>.size, index: 7)- p1.setBytes(&nc, length: MemoryLayout<UInt32>.size, index: 8)- let partialTGWidth = min(Self.threadsPerGroup,- Int(psoTurboQuantPartialK4V4.maxTotalThreadsPerThreadgroup))- p1.dispatchThreadgroups(MTLSize(width: geometry.partialThreadgroups,- height: 1,- depth: 1),- threadsPerThreadgroup: MTLSize(width: partialTGWidth,- height: 1,- depth: 1))- p1.endEncoding()- }-- func encodeTurboQuantCombine(commandBuffer: MTLCommandBuffer,- out: MTLBuffer,- outOffset: Int = 0,- params: AttentionTurboQuantKVParams,- geometry: AttentionTurboQuantSplitGeometry) {- guard let p2 = commandBuffer.makeComputeCommandEncoder() else { return }- let combinePSO = psoTurboQuantCombineK4V4- p2.setComputePipelineState(combinePSO)- p2.setBuffer(mPartial, offset: 0, index: 0)- p2.setBuffer(dPartial, offset: 0, index: 1)- p2.setBuffer(oPartial, offset: 0, index: 2)- p2.setBuffer(out, offset: outOffset, index: 3)- var p = params- p.qPretransformed = 1- var nc = UInt32(geometry.numChunks)- p2.setBytes(&p, length: MemoryLayout<AttentionTurboQuantKVParams>.size, index: 4)- p2.setBytes(&nc, length: MemoryLayout<UInt32>.size, index: 5)- let combineTGWidth = min(Self.threadsPerGroup,- Int(combinePSO.maxTotalThreadsPerThreadgroup))- p2.dispatchThreadgroups(MTLSize(width: Int(params.numQHeads), height: 1, depth: 1),- threadsPerThreadgroup: MTLSize(width: combineTGWidth,- height: 1,- depth: 1))- p2.endEncoding()- }/// Two-pass split-KV (Flash-Decoding) dispatch shared by SWA and full/// attention — they differ only by `kvStart`. Pass 1 fans the head'sdiff --git a/Sources/TurboFieldfare/Kernels/Attention/PrefillAttention.swift b/Sources/TurboFieldfare/Kernels/Attention/PrefillAttention.swiftindex fcd7fafd..28117011 100644--- a/Sources/TurboFieldfare/Kernels/Attention/PrefillAttention.swift+++ b/Sources/TurboFieldfare/Kernels/Attention/PrefillAttention.swift@@ -39,61 +39,14 @@ struct PrefillAttentionParams: Sendable, Equatable {}}-struct PrefillTurboQuantAttentionParams: Sendable, Equatable {- var startPosition: UInt32- var queryCount: UInt32- var headDim: UInt32- var numQHeads: UInt32- var numKVHeads: UInt32- var kvValidCount: UInt32- var slidingWindow: UInt32- var qTokenStrideElements: UInt32- var oTokenStrideElements: UInt32- var scale: Float- var layer: UInt32- var rotationSeed: UInt32- var keyBytesPerHead: UInt32- var keyPackedOffset: UInt32- var keyScaleOffset: UInt32- var valueBytesPerHead: UInt32- var valuePackedOffset: UInt32- var valueScaleOffset: UInt32-- init(prefill: PrefillAttentionParams,- layer: UInt32,- rotationSeed: UInt32,- keyLayout: TurboQuantKVRoleLayout,- valueLayout: TurboQuantKVRoleLayout) {- self.startPosition = prefill.startPosition- self.queryCount = prefill.queryCount- self.headDim = prefill.headDim- self.numQHeads = prefill.numQHeads- self.numKVHeads = prefill.numKVHeads- self.kvValidCount = prefill.kvValidCount- self.slidingWindow = prefill.slidingWindow- self.qTokenStrideElements = prefill.qTokenStrideElements- self.oTokenStrideElements = prefill.oTokenStrideElements- self.scale = prefill.scale- self.layer = layer- self.rotationSeed = rotationSeed- self.keyBytesPerHead = UInt32(keyLayout.bytesPerHead)- self.keyPackedOffset = UInt32(keyLayout.packedOffsetPerHead)- self.keyScaleOffset = UInt32(keyLayout.scaleOffsetPerHead)- self.valueBytesPerHead = UInt32(valueLayout.bytesPerHead)- self.valuePackedOffset = UInt32(valueLayout.packedOffsetPerHead)- self.valueScaleOffset = UInt32(valueLayout.scaleOffsetPerHead)- }-}final class PrefillAttention {private let context: MetalContextprivate let psoCausalTiled: MTLComputePipelineState- private let psoCausalTurboQuantTiled: MTLComputePipelineStateinit(context: MetalContext) throws {self.context = contextself.psoCausalTiled = try context.pipeline("attention_prefill_causal_tiled")- self.psoCausalTurboQuantTiled = try context.pipeline("attention_prefill_turboquant_causal_tiled")}func encodeCausal(commandBuffer: MTLCommandBuffer,@@ -126,33 +79,6 @@ final class PrefillAttention {enc.endEncoding()}- func encodeTurboQuantCausal(commandBuffer: MTLCommandBuffer,- q: MTLBuffer, qOffset: Int = 0,- keyCache: MTLBuffer, keyCacheOffset: Int = 0,- valueCache: MTLBuffer, valueCacheOffset: Int = 0,- out: MTLBuffer, outOffset: Int = 0,- params: PrefillTurboQuantAttentionParams) {- validateTurboQuant(params)-- let threadWidth = max(1, psoCausalTurboQuantTiled.threadExecutionWidth)- let threadCount = roundUp(max(threadWidth, min(Int(params.headDim), 256)),- toMultipleOf: threadWidth)- precondition(threadCount <= psoCausalTurboQuantTiled.maxTotalThreadsPerThreadgroup,- "TurboQuant prefill attention requires headDim <= maxTotalThreadsPerThreadgroup")-- guard let enc = commandBuffer.makeComputeCommandEncoder() else { return }- enc.setComputePipelineState(psoCausalTurboQuantTiled)- enc.setBuffer(q, offset: qOffset, index: 0)- enc.setBuffer(keyCache, offset: keyCacheOffset, index: 1)- enc.setBuffer(valueCache, offset: valueCacheOffset, index: 2)- enc.setBuffer(out, offset: outOffset, index: 3)- var p = params- enc.setBytes(&p, length: MemoryLayout<PrefillTurboQuantAttentionParams>.stride, index: 4)- enc.dispatchThreadgroups(- MTLSize(width: Int(params.queryCount), height: Int(params.numQHeads), depth: 1),- threadsPerThreadgroup: MTLSize(width: threadCount, height: 1, depth: 1))- enc.endEncoding()- }private func validate(_ params: PrefillAttentionParams) {precondition(params.headDim > 0, "headDim must be positive")@@ -171,22 +97,6 @@ final class PrefillAttention {"kvValidCount must include all in-flight query rows")}- private func validateTurboQuant(_ params: PrefillTurboQuantAttentionParams) {- precondition(params.headDim > 0, "headDim must be positive")- precondition(params.queryCount > 0, "queryCount must be positive")- precondition(params.numQHeads > 0, "numQHeads must be positive")- precondition(params.numKVHeads > 0, "numKVHeads must be positive")- precondition(params.numQHeads % params.numKVHeads == 0,- "numQHeads must be divisible by numKVHeads")- precondition(params.qTokenStrideElements >= params.numQHeads * params.headDim,- "q token stride is too small")- precondition(params.oTokenStrideElements >= params.numQHeads * params.headDim,- "output token stride is too small")- precondition(params.keyBytesPerHead > 0, "key bytes per head must be positive")- precondition(params.valueBytesPerHead > 0, "value bytes per head must be positive")- precondition(params.startPosition + params.queryCount <= params.kvValidCount,- "kvValidCount must include all in-flight query rows")- }private func roundUp(_ value: Int, toMultipleOf multiple: Int) -> Int {((value + multiple - 1) / multiple) * multiplediff --git a/Sources/TurboFieldfare/Kernels/KVCache/TurboQuant.swift b/Sources/TurboFieldfare/Kernels/KVCache/TurboQuant.swiftdeleted file mode 100644index 71c67966..00000000--- a/Sources/TurboFieldfare/Kernels/KVCache/TurboQuant.swift+++ /dev/null@@ -1,196 +0,0 @@-import Foundation-import Metal--struct TurboQuantKVWriteParams {- var d: UInt32- var numHeads: UInt32- var bytesPerHead: UInt32- var packedOffset: UInt32- var scaleOffset: UInt32- var tokenBase: UInt32- var bytesPerToken: UInt32-- init(d: UInt32,- numHeads: UInt32,- roleLayout: TurboQuantKVRoleLayout,- tokenBase: UInt32 = 0) {- self.d = d- self.numHeads = numHeads- self.bytesPerHead = UInt32(roleLayout.bytesPerHead)- self.packedOffset = UInt32(roleLayout.packedOffsetPerHead)- self.scaleOffset = UInt32(roleLayout.scaleOffsetPerHead)- self.tokenBase = tokenBase- self.bytesPerToken = UInt32(roleLayout.bytesPerToken)- }-}--enum TurboQuantKVBulkWriteError: Error, Equatable, CustomStringConvertible {- case invalidTokenCount(Int)- case invalidDestinationTokenBase(Int)- case invalidCacheCapacity(Int)- case rangeExceedsCache(start: Int, count: Int, capacity: Int)- case unsupportedSourceTokenStride(actual: Int, expected: Int)-- public var description: String {- switch self {- case .invalidTokenCount(let count):- return "invalid TurboQuant bulk token count \(count)"- case .invalidDestinationTokenBase(let base):- return "invalid TurboQuant bulk destination token base \(base)"- case .invalidCacheCapacity(let capacity):- return "invalid TurboQuant bulk cache capacity \(capacity)"- case let .rangeExceedsCache(start, count, capacity):- return "TurboQuant bulk write range start=\(start) count=\(count) exceeds capacity=\(capacity)"- case let .unsupportedSourceTokenStride(actual, expected):- return "TurboQuant bulk source token stride \(actual) does not match contiguous stride \(expected)"- }- }-}--struct TurboQuantKVBulkWriteParams {- var kv: TurboQuantKVWriteParams- var tokenCount: Int- var dstTokenBase: Int- var cacheTokenCapacity: Int- var sourceTokenStrideElements: Int-- init(kv: TurboQuantKVWriteParams,- tokenCount: Int,- dstTokenBase: Int,- cacheTokenCapacity: Int,- sourceTokenStrideElements: Int) {- self.kv = kv- self.tokenCount = tokenCount- self.dstTokenBase = dstTokenBase- self.cacheTokenCapacity = cacheTokenCapacity- self.sourceTokenStrideElements = sourceTokenStrideElements- }-}--struct TurboQuantWHTParams {- var numHeads: UInt32- var layer: UInt32- var rotationSeed: UInt32- var applyRotation: UInt32-- init(numHeads: UInt32 = 1,- layer: UInt32 = 0,- rotationSeed: UInt32 = 0,- applyRotation: Bool = false) {- self.numHeads = numHeads- self.layer = layer- self.rotationSeed = rotationSeed- self.applyRotation = applyRotation ? 1 : 0- }-}--/// Packs pre-WHT FP16 K/V rows directly into the production TurboQuant cache-/// layout. One threadgroup handles each flattened `(token, head)` pair.-final class TurboQuantQuant {- private struct Shape: Hashable {- var d: UInt32- var numHeads: UInt32- }-- private let kvWriteWHTPSO: MTLComputePipelineState- private let kvWriteWHTSpecializedPSOs: [Shape: MTLComputePipelineState]- private static let realDecodeShapes: [Shape] = [- Shape(d: 256, numHeads: 8),- Shape(d: 512, numHeads: 2),- ]-- init(context: MetalContext) throws {- self.kvWriteWHTPSO = try context.pipeline("turboquant_quant_kv_write_wht")- var variants: [Shape: MTLComputePipelineState] = [:]- for shape in Self.realDecodeShapes {- variants[shape] = try context.pipeline(- "turboquant_quant_kv_write_wht",- constants: [- MetalFunctionConstant(index: 100, value: .uint32(shape.d)),- MetalFunctionConstant(index: 101, value: .uint32(shape.numHeads)),- MetalFunctionConstant(index: 103, value: .bool(true)),- ])- }- self.kvWriteWHTSpecializedPSOs = variants- }-- func encodeKVWriteWHT(commandBuffer: MTLCommandBuffer,- x: MTLBuffer,- xOffset: Int = 0,- cache: MTLBuffer,- cacheOffset: Int = 0,- params: TurboQuantKVWriteParams,- whtParams: TurboQuantWHTParams,- pairs: Int) {- guard let encoder = commandBuffer.makeComputeCommandEncoder() else { return }- encoder.setComputePipelineState(- kvWriteWHTSpecializedPSOs[Shape(d: params.d,- numHeads: params.numHeads)] ?? kvWriteWHTPSO)- encoder.setBuffer(x, offset: xOffset, index: 0)- encoder.setBuffer(cache, offset: cacheOffset, index: 1)- var writeParams = params- var transformParams = whtParams- encoder.setBytes(&writeParams,- length: MemoryLayout<TurboQuantKVWriteParams>.size,- index: 2)- encoder.setBytes(&transformParams,- length: MemoryLayout<TurboQuantWHTParams>.size,- index: 3)- let threads = Int(params.d)- encoder.dispatchThreadgroups(- MTLSize(width: pairs, height: 1, depth: 1),- threadsPerThreadgroup: MTLSize(width: threads, height: 1, depth: 1))- encoder.endEncoding()- }-- func encodeKVWriteWHTBulk(commandBuffer: MTLCommandBuffer,- x: MTLBuffer,- xOffset: Int = 0,- cache: MTLBuffer,- cacheOffset: Int = 0,- params: TurboQuantKVBulkWriteParams,- whtParams: TurboQuantWHTParams) throws {- let writeParams = try validateBulkWriteParams(params)- let destinationOffset = cacheOffset- + params.dstTokenBase * Int(writeParams.bytesPerToken)- encodeKVWriteWHT(commandBuffer: commandBuffer,- x: x,- xOffset: xOffset,- cache: cache,- cacheOffset: destinationOffset,- params: writeParams,- whtParams: whtParams,- pairs: params.tokenCount * Int(writeParams.numHeads))- }-- private func validateBulkWriteParams(- _ params: TurboQuantKVBulkWriteParams- ) throws -> TurboQuantKVWriteParams {- guard params.tokenCount > 0 else {- throw TurboQuantKVBulkWriteError.invalidTokenCount(params.tokenCount)- }- guard params.dstTokenBase >= 0 else {- throw TurboQuantKVBulkWriteError.invalidDestinationTokenBase(params.dstTokenBase)- }- guard params.cacheTokenCapacity >= 0 else {- throw TurboQuantKVBulkWriteError.invalidCacheCapacity(params.cacheTokenCapacity)- }- guard params.dstTokenBase + params.tokenCount <= params.cacheTokenCapacity else {- throw TurboQuantKVBulkWriteError.rangeExceedsCache(- start: params.dstTokenBase,- count: params.tokenCount,- capacity: params.cacheTokenCapacity)- }-- let expectedStride = Int(params.kv.numHeads) * Int(params.kv.d)- guard params.sourceTokenStrideElements == expectedStride else {- throw TurboQuantKVBulkWriteError.unsupportedSourceTokenStride(- actual: params.sourceTokenStrideElements,- expected: expectedStride)- }-- var writeParams = params.kv- writeParams.tokenBase = UInt32(params.dstTokenBase)- return writeParams- }-}diff --git a/Sources/TurboFieldfare/Kernels/MoE/SharedExpertInt4.swift b/Sources/TurboFieldfare/Kernels/MoE/SharedExpertInt4.swiftnew file mode 100644index 00000000..0650cce2--- /dev/null+++ b/Sources/TurboFieldfare/Kernels/MoE/SharedExpertInt4.swift@@ -0,0 +1,137 @@+import Foundation+import Metal++public enum SharedExpertError: Error, CustomStringConvertible {+ case unsupportedWeightBits(Int)+ case dimensionMismatch(String)+ case scratchTooSmall(String)++ public var description: String {+ switch self {+ case .unsupportedWeightBits(let bits):+ return "SharedExpert unsupported weight bits: \(bits)"+ case .dimensionMismatch(let detail):+ return "SharedExpert dimension mismatch: \(detail)"+ case .scratchTooSmall(let detail):+ return "SharedExpert scratch too small: \(detail)"+ }+ }+}++public final class SharedExpertInt4 {+ private let int4: DequantInt4GEMV+ private let geluMulPSO: MTLComputePipelineState++ public init(context: MetalContext) throws {+ self.int4 = try DequantInt4GEMV(context: context)+ self.geluMulPSO = try context.pipeline("gelu_mul_fp16")+ }++ public func encode(commandBuffer cb: MTLCommandBuffer,+ x: MTLBuffer, xOffset: Int = 0,+ gate: SharedExpertProjection,+ up: SharedExpertProjection,+ down: SharedExpertProjection,+ y: MTLBuffer, yOffset: Int = 0,+ scratchGate: MTLBuffer, scratchGateOffset: Int = 0,+ scratchUp: MTLBuffer, scratchUpOffset: Int = 0,+ scratchAct: MTLBuffer, scratchActOffset: Int = 0) throws {+ guard gate.rows == up.rows, gate.cols == up.cols,+ down.rows == gate.cols, down.cols == gate.rows else {+ throw SharedExpertError.dimensionMismatch(+ "gate=(\(gate.rows),\(gate.cols)) up=(\(up.rows),\(up.cols)) down=(\(down.rows),\(down.cols))")+ }+ let intermediate = Int(gate.rows)+ let required = intermediate * MemoryLayout<Float16>.stride+ guard scratchGateOffset >= 0, scratchGateOffset + required <= scratchGate.length,+ scratchUpOffset >= 0, scratchUpOffset + required <= scratchUp.length,+ scratchActOffset >= 0, scratchActOffset + required <= scratchAct.length else {+ throw SharedExpertError.scratchTooSmall("need \(required) bytes per intermediate buffer")+ }+ let inputBytes = Int(gate.cols) * MemoryLayout<Float16>.stride+ let outputBytes = Int(down.rows) * MemoryLayout<Float16>.stride+ guard xOffset >= 0, xOffset + inputBytes <= x.length else {+ throw SharedExpertError.scratchTooSmall("input range exceeds x buffer")+ }+ guard yOffset >= 0, yOffset + outputBytes <= y.length else {+ throw SharedExpertError.scratchTooSmall("output range exceeds y buffer")+ }++ int4.encode(commandBuffer: cb,+ weights: gate.weights, weightsOffset: gate.weightsOffset,+ scales: gate.scales, scalesOffset: gate.scalesOffset,+ biases: gate.biases, biasesOffset: gate.biasesOffset,+ x: x, xOffset: xOffset,+ y: scratchGate, yOffset: scratchGateOffset,+ m: gate.rows, n: gate.cols)+ int4.encode(commandBuffer: cb,+ weights: up.weights, weightsOffset: up.weightsOffset,+ scales: up.scales, scalesOffset: up.scalesOffset,+ biases: up.biases, biasesOffset: up.biasesOffset,+ x: x, xOffset: xOffset,+ y: scratchUp, yOffset: scratchUpOffset,+ m: up.rows, n: up.cols)++ guard let encoder = cb.makeComputeCommandEncoder() else { return }+ encoder.setComputePipelineState(geluMulPSO)+ encoder.setBuffer(scratchGate, offset: scratchGateOffset, index: 0)+ encoder.setBuffer(scratchUp, offset: scratchUpOffset, index: 1)+ encoder.setBuffer(scratchAct, offset: scratchActOffset, index: 2)+ var count = UInt32(intermediate)+ encoder.setBytes(&count, length: MemoryLayout<UInt32>.size, index: 3)+ let width = min(geluMulPSO.maxTotalThreadsPerThreadgroup, 256)+ encoder.dispatchThreads(MTLSize(width: intermediate, height: 1, depth: 1),+ threadsPerThreadgroup: MTLSize(width: width, height: 1, depth: 1))+ encoder.endEncoding()++ int4.encode(commandBuffer: cb,+ weights: down.weights, weightsOffset: down.weightsOffset,+ scales: down.scales, scalesOffset: down.scalesOffset,+ biases: down.biases, biasesOffset: down.biasesOffset,+ x: scratchAct, xOffset: scratchActOffset,+ y: y, yOffset: yOffset,+ m: down.rows, n: down.cols)+ }+}++public final class SharedExpertRuntime {+ private enum Implementation {+ case int4(SharedExpertInt4)+ case int8(SharedExpertInt8)+ }++ private let implementation: Implementation+ public let weightBits: Int++ public init(context: MetalContext, weightBits: Int) throws {+ self.weightBits = weightBits+ switch weightBits {+ case 4: self.implementation = .int4(try SharedExpertInt4(context: context))+ case 8: self.implementation = .int8(try SharedExpertInt8(context: context))+ default: throw SharedExpertError.unsupportedWeightBits(weightBits)+ }+ }++ public func encode(commandBuffer: MTLCommandBuffer,+ x: MTLBuffer, xOffset: Int = 0,+ gate: SharedExpertProjection,+ up: SharedExpertProjection,+ down: SharedExpertProjection,+ y: MTLBuffer, yOffset: Int = 0,+ scratchGate: MTLBuffer, scratchGateOffset: Int = 0,+ scratchUp: MTLBuffer, scratchUpOffset: Int = 0,+ scratchAct: MTLBuffer, scratchActOffset: Int = 0) throws {+ switch implementation {+ case .int4(let runtime):+ try runtime.encode(commandBuffer: commandBuffer, x: x, xOffset: xOffset,+ gate: gate, up: up, down: down, y: y, yOffset: yOffset,+ scratchGate: scratchGate, scratchGateOffset: scratchGateOffset,+ scratchUp: scratchUp, scratchUpOffset: scratchUpOffset,+ scratchAct: scratchAct, scratchActOffset: scratchActOffset)+ case .int8(let runtime):+ try runtime.encode(commandBuffer: commandBuffer, x: x, xOffset: xOffset,+ gate: gate, up: up, down: down, y: y, yOffset: yOffset,+ scratchAct: scratchAct, scratchActOffset: scratchActOffset)+ }+ }+}diff --git a/Sources/TurboFieldfare/Kernels/MoE/SharedExpertInt8.swift b/Sources/TurboFieldfare/Kernels/MoE/SharedExpertInt8.swiftindex 11fdf6c0..1dc2c37c 100644--- a/Sources/TurboFieldfare/Kernels/MoE/SharedExpertInt8.swift+++ b/Sources/TurboFieldfare/Kernels/MoE/SharedExpertInt8.swift@@ -6,17 +6,17 @@ import Metal/// The Gemma 4 26B-A4B manifest stores `mlp.gate/up/down_proj.weight` at 8-bit/// MLX affine (group=64, BF16 scale + BF16 bias). Shapes:/// gate: [F=2112, D=2816] up: [F=2112, D=2816] down: [D=2816, F=2112]-struct SharedExpertInt8Proj {- let weights: MTLBuffer- let scales: MTLBuffer- let biases: MTLBuffer- let weightsOffset: Int- let scalesOffset: Int- let biasesOffset: Int- let rows: UInt32- let cols: UInt32+public struct SharedExpertProjection {+ public let weights: MTLBuffer+ public let scales: MTLBuffer+ public let biases: MTLBuffer+ public let weightsOffset: Int+ public let scalesOffset: Int+ public let biasesOffset: Int+ public let rows: UInt32+ public let cols: UInt32- init(weights: MTLBuffer, scales: MTLBuffer, biases: MTLBuffer,+ public init(weights: MTLBuffer, scales: MTLBuffer, biases: MTLBuffer,weightsOffset: Int = 0, scalesOffset: Int = 0, biasesOffset: Int = 0,rows: UInt32, cols: UInt32) {self.weights = weights@@ -30,6 +30,8 @@ struct SharedExpertInt8Proj {}}+public typealias SharedExpertInt8Proj = SharedExpertProjection+enum SharedExpertInt8Error: Error, CustomStringConvertible {case dimensionMismatch(String)case scratchTooSmall(String)diff --git a/Sources/TurboFieldfare/Kernels/Prefill/MoE/PrefillSharedExpert.swift b/Sources/TurboFieldfare/Kernels/Prefill/MoE/PrefillSharedExpert.swiftindex 45762965..e93feea1 100644--- a/Sources/TurboFieldfare/Kernels/Prefill/MoE/PrefillSharedExpert.swift+++ b/Sources/TurboFieldfare/Kernels/Prefill/MoE/PrefillSharedExpert.swift@@ -2,10 +2,10 @@ import Foundationimport Metalfinal class PrefillSharedExpert {- private let shared: SharedExpertInt8+ private let shared: SharedExpertRuntime- init(context: MetalContext) throws {- self.shared = try SharedExpertInt8(context: context)+ init(context: MetalContext, weightBits: Int = 8) throws {+ self.shared = try SharedExpertRuntime(context: context, weightBits: weightBits)}func encodeBlock(commandBuffer cb: MTLCommandBuffer,@@ -16,6 +16,10 @@ final class PrefillSharedExpert {gate: SharedExpertInt8Proj,up: SharedExpertInt8Proj,down: SharedExpertInt8Proj,+ scratchGate: MTLBuffer,+ scratchGateOffset: Int = 0,+ scratchUp: MTLBuffer,+ scratchUpOffset: Int = 0,scratchAct: MTLBuffer,scratchActOffset: Int = 0,queryCount: Int,@@ -45,6 +49,10 @@ final class PrefillSharedExpert {down: down,y: y,yOffset: yOffset + row * yStrideElements * halfBytes,+ scratchGate: scratchGate,+ scratchGateOffset: scratchGateOffset,+ scratchUp: scratchUp,+ scratchUpOffset: scratchUpOffset,scratchAct: scratchAct,scratchActOffset: scratchActOffset)}diff --git a/Sources/TurboFieldfare/Metal/Attention/attention.metal b/Sources/TurboFieldfare/Metal/Attention/attention.metalindex 7222c3c0..9e215022 100644--- a/Sources/TurboFieldfare/Metal/Attention/attention.metal+++ b/Sources/TurboFieldfare/Metal/Attention/attention.metal@@ -110,646 +110,10 @@ inline float block_reduce_sum(float v,return *bcast;}-// ============================================================================-// TurboQuant packed-KV attention.-// ============================================================================--struct AttentionTurboQuantKVParams {- uint head_dim;- uint num_q_heads;- uint num_kv_heads;- uint seq_len;- uint kv_start;- float scale;- uint layer;- uint rotation_seed;- uint key_bytes_per_head;- uint key_packed_offset;- uint key_scale_offset;- uint value_bytes_per_head;- uint value_packed_offset;- uint value_scale_offset;- uint q_pretransformed;-};--static inline uint attn_tq_key_bit_width(constant AttentionTurboQuantKVParams&) {- return 4u;-}--static inline uint attn_tq_value_bit_width(constant AttentionTurboQuantKVParams&) {- return 4u;-}--constant constexpr float kAttnTQCodebook4[16] = {- -2.7326f, -2.0690f, -1.6181f, -1.2562f,- -0.9424f, -0.6568f, -0.3881f, -0.1284f,- 0.1284f, 0.3881f, 0.6568f, 0.9424f,- 1.2562f, 1.6181f, 2.0690f, 2.7326f-};--static inline float attn_tq_centroid(uint idx) {- return kAttnTQCodebook4[idx];-}--static inline ulong attn_tq_mix64(ulong z) {- z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ul;- z = (z ^ (z >> 27)) * 0x94D049BB133111EBul;- return z ^ (z >> 31);-}--static inline bool attn_tq_rotation_is_negative(uint layer, uint head, uint dim, uint seed) {- ulong z = ulong(seed);- z ^= ulong(layer) * 0x9E3779B97F4A7C15ul;- z ^= ulong(head) * 0xBF58476D1CE4E5B9ul;- z ^= ulong(dim) * 0x94D049BB133111EBul;- return (attn_tq_mix64(z) >> 63) != 0ul;-}--static inline float attn_tq_apply_rotation(float v,- uint layer,- uint head,- uint dim,- uint seed) {- return attn_tq_rotation_is_negative(layer, head, dim, seed) ? -v : v;-}--static inline void attn_tq_wht_inplace(threadgroup float* data,- uint D,- uint lid,- uint lsize) {- for (uint stride = 1u; stride < D; stride <<= 1u) {- for (uint j = lid; j < D / 2u; j += lsize) {- const uint block = j / stride;- const uint lane = j - block * stride;- const uint a_idx = block * stride * 2u + lane;- const uint b_idx = a_idx + stride;- const float a = data[a_idx];- const float b = data[b_idx];- data[a_idx] = (a + b) * 0.7071067811865475f;- data[b_idx] = (a - b) * 0.7071067811865475f;- }- threadgroup_barrier(mem_flags::mem_threadgroup);- }-}--static inline void attn_tq_wht_inplace_d256(threadgroup float* data,- uint lid,- uint simd_lane) {- float v = data[lid];- for (uint stride = 1u; stride < 32u; stride <<= 1u) {- float other = simd_shuffle_xor(v, stride);- v = ((simd_lane & stride) == 0u)- ? (v + other) * 0.7071067811865475f- : (other - v) * 0.7071067811865475f;- }-- data[lid] = v;- for (uint stride = 32u; stride < 256u; stride <<= 1u) {- threadgroup_barrier(mem_flags::mem_threadgroup);- if ((lid & stride) == 0u) {- uint j = lid | stride;- float a = data[lid];- float b = data[j];- data[lid] = (a + b) * 0.7071067811865475f;- data[j] = (a - b) * 0.7071067811865475f;- }- }- threadgroup_barrier(mem_flags::mem_threadgroup);-}--static inline void attn_tq_wht_inplace_d512(threadgroup float* data,- uint lid,- uint simd_lane) {- float v0 = data[lid];- float v1 = data[lid + 256u];- for (uint stride = 1u; stride < 32u; stride <<= 1u) {- float other0 = simd_shuffle_xor(v0, stride);- float other1 = simd_shuffle_xor(v1, stride);- const bool lo = (simd_lane & stride) == 0u;- v0 = lo- ? (v0 + other0) * 0.7071067811865475f- : (other0 - v0) * 0.7071067811865475f;- v1 = lo- ? (v1 + other1) * 0.7071067811865475f- : (other1 - v1) * 0.7071067811865475f;- }-- data[lid] = v0;- data[lid + 256u] = v1;- for (uint stride = 32u; stride < 256u; stride <<= 1u) {- threadgroup_barrier(mem_flags::mem_threadgroup);- if ((lid & stride) == 0u) {- uint j = lid | stride;- float a0 = data[lid];- float b0 = data[j];- data[lid] = (a0 + b0) * 0.7071067811865475f;- data[j] = (a0 - b0) * 0.7071067811865475f;-- float a1 = data[lid + 256u];- float b1 = data[j + 256u];- data[lid + 256u] = (a1 + b1) * 0.7071067811865475f;- data[j + 256u] = (a1 - b1) * 0.7071067811865475f;- }- }-- threadgroup_barrier(mem_flags::mem_threadgroup);- float a = data[lid];- float b = data[lid + 256u];- data[lid] = (a + b) * 0.7071067811865475f;- data[lid + 256u] = (a - b) * 0.7071067811865475f;- threadgroup_barrier(mem_flags::mem_threadgroup);-}--static inline void attn_tq_wht_inplace_fast(threadgroup float* data,- uint D,- uint lid,- uint lsize,- uint simd_lane) {- if (D == 256u && lsize >= 256u) {- attn_tq_wht_inplace_d256(data, lid, simd_lane);- } else if (D == 512u && lsize >= 256u) {- attn_tq_wht_inplace_d512(data, lid, simd_lane);- } else {- attn_tq_wht_inplace(data, D, lid, lsize);- }-}--static inline float attn_tq_read_packed(device const uint8_t* cache,- uint head_base,- uint packed_bits,- uint packed_offset,- uint D,- uint dim,- float scale) {- const uint packed_base = head_base + packed_offset;- const uint byte = dim >> 1u;- const uint shift = (dim & 1u) << 2u;- const uint idx = (uint(cache[packed_base + byte]) >> shift) & 0xFu;- return attn_tq_centroid(idx) * scale;-}--static inline uint attn_tq_read_index(device const uint8_t* cache,- uint head_base,- uint packed_bits,- uint packed_offset,- uint D,- uint dim) {- const uint packed_base = head_base + packed_offset;- const uint byte = dim >> 1u;- const uint shift = (dim & 1u) << 2u;- return (uint(cache[packed_base + byte]) >> shift) & 0xFu;-}--[[kernel, max_total_threads_per_threadgroup(kAttnThreads)]]-void attention_turboquant_q_rht(- device const half* Q [[buffer(0)]],- device half* out [[buffer(1)]],- constant AttentionTurboQuantKVParams& params [[buffer(2)]],- uint tg_id [[threadgroup_position_in_grid]],- uint lid [[thread_position_in_threadgroup]],- uint lsize [[threads_per_threadgroup]],- uint simd_lane_id [[thread_index_in_simdgroup]]-) {- threadgroup float q_smem[kAttnMaxHeadDim];- const uint HD = params.head_dim;- const uint q_head = tg_id;- const uint kv_head = q_head / (params.num_q_heads / params.num_kv_heads);- device const half* Q_row = Q + q_head * HD;- for (uint i = lid; i < HD; i += lsize) {- const float q = float(Q_row[i]);- q_smem[i] = attn_tq_apply_rotation(q,- params.layer,- kv_head,- i,- params.rotation_seed);- }- threadgroup_barrier(mem_flags::mem_threadgroup);- attn_tq_wht_inplace_fast(q_smem, HD, lid, lsize, simd_lane_id);-- device half* out_row = out + q_head * HD;- for (uint i = lid; i < HD; i += lsize) {- out_row[i] = half(q_smem[i]);- }-}--[[kernel, max_total_threads_per_threadgroup(kAttnThreads)]]-void attention_turboquant_decode_partial(- device const half* Q [[buffer(0)]],- device const uint8_t* K_cache [[buffer(1)]],- device const uint8_t* V_cache [[buffer(2)]],- device float* m_out [[buffer(3)]],- device float* d_out [[buffer(4)]],- device float* o_out [[buffer(5)]],- constant AttentionTurboQuantKVParams& params [[buffer(6)]],- constant uint& chunk_len [[buffer(7)]],- constant uint& num_chunks [[buffer(8)]],- uint tg_id [[threadgroup_position_in_grid]],- uint lid [[thread_position_in_threadgroup]],- uint lsize [[threads_per_threadgroup]],- uint simd_lane_id [[thread_index_in_simdgroup]],- uint simd_group_id [[simdgroup_index_in_threadgroup]],- uint simdgroups [[simdgroups_per_threadgroup]]-) {- threadgroup float q_smem[kAttnMaxHeadDim];- threadgroup float reduce_scratch[kAttnMaxSimdGroups];- threadgroup float bcast;-- const uint HD = attn_fc_head_dim(params.head_dim);- const uint NQ = attn_fc_num_q_heads(params.num_q_heads);- const uint NKV = attn_fc_num_kv_heads(params.num_kv_heads);- const uint NC = attn_fc_num_chunks(num_chunks);- const uint q_head = tg_id / NC;- const uint chunk = tg_id % NC;- const uint kv_head = q_head / (NQ / NKV);- const uint key_bytes_per_token = params.key_bytes_per_head * NKV;- const uint value_bytes_per_token = params.value_bytes_per_head * NKV;- const uint p_start = params.kv_start + chunk * chunk_len;- uint p_end = p_start + chunk_len;- if (p_end > params.seq_len) { p_end = params.seq_len; }-- device const half* Q_row = Q + q_head * HD;- for (uint i = lid; i < HD; i += lsize) {- if (params.q_pretransformed != 0u) {- q_smem[i] = float(Q_row[i]);- } else {- const float q = float(Q_row[i]);- q_smem[i] = attn_tq_apply_rotation(q,- params.layer,- kv_head,- i,- params.rotation_seed);- }- }- threadgroup_barrier(mem_flags::mem_threadgroup);- if (params.q_pretransformed == 0u) {- attn_tq_wht_inplace_fast(q_smem, HD, lid, lsize, simd_lane_id);- }-- constexpr uint kPerThread = (kAttnMaxHeadDim + kAttnThreads - 1) / kAttnThreads;- float o_local[kPerThread];- for (uint k = 0; k < kPerThread; ++k) { o_local[k] = 0.0f; }-- float m_run = -INFINITY;- float d_run = 0.0f;-- for (uint p = p_start; p < p_end; ++p) {- const uint key_head_base = p * key_bytes_per_token- + kv_head * params.key_bytes_per_head;- const uint value_head_base = p * value_bytes_per_token- + kv_head * params.value_bytes_per_head;- const device half* key_scale_ptr = reinterpret_cast<const device half*>(- K_cache + key_head_base + params.key_scale_offset);- const device half* value_scale_ptr = reinterpret_cast<const device half*>(- V_cache + value_head_base + params.value_scale_offset);- const float key_scale = float(*key_scale_ptr);- const float value_scale = float(*value_scale_ptr);-- float partial = 0.0f;- for (uint i = lid; i < HD; i += lsize) {- const float k_val = attn_tq_read_packed(K_cache,- key_head_base,- 4u,- params.key_packed_offset,- HD,- i,- key_scale);- partial = fma(q_smem[i], k_val, partial);- }- float s = block_reduce_sum(partial,- simd_lane_id, simd_group_id, simdgroups,- reduce_scratch, &bcast);- s *= params.scale;-- const float m_new = max(m_run, s);- const float alpha = attn_softmax_exp(m_run - m_new);- const float p_exp = attn_softmax_exp(s - m_new);- d_run = d_run * alpha + p_exp;-- uint slot = 0;- for (uint i = lid; i < HD; i += lsize) {- float v_val = attn_tq_read_packed(V_cache,- value_head_base,- 4u,- params.value_packed_offset,- HD,- i,- value_scale);- o_local[slot] = o_local[slot] * alpha + p_exp * v_val;- slot += 1;- }- m_run = m_new;- }-- const uint base = q_head * NC + chunk;- if (lid == 0) {- m_out[base] = m_run;- d_out[base] = d_run;- }- device float* o_row = o_out + base * HD;- uint slot = 0;- for (uint i = lid; i < HD; i += lsize) {- o_row[i] = o_local[slot];- slot += 1;- }-}--[[kernel, max_total_threads_per_threadgroup(kAttnThreads)]]-void attention_turboquant_decode_gqa_swa_partial(- device const half* Q [[buffer(0)]],- device const uint8_t* K_cache [[buffer(1)]],- device const uint8_t* V_cache [[buffer(2)]],- device float* m_out [[buffer(3)]],- device float* d_out [[buffer(4)]],- device float* o_out [[buffer(5)]],- constant AttentionTurboQuantKVParams& params [[buffer(6)]],- constant uint& chunk_len [[buffer(7)]],- constant uint& num_chunks [[buffer(8)]],- uint tg_id [[threadgroup_position_in_grid]],- uint lid [[thread_position_in_threadgroup]],- uint lsize [[threads_per_threadgroup]],- uint simd_lane_id [[thread_index_in_simdgroup]],- uint simd_group_id [[simdgroup_index_in_threadgroup]]-) {- threadgroup float q_smem[kAttnMaxQPerKV * kAttnMaxHeadDim];- threadgroup float reduce_scratch[kAttnMaxQPerKV * kAttnMaxSimdGroups];- threadgroup float bcast[kAttnMaxQPerKV];-- const uint HD = attn_fc_head_dim(params.head_dim);- const uint NQ = attn_fc_num_q_heads(params.num_q_heads);- const uint NKV = attn_fc_num_kv_heads(params.num_kv_heads);- const uint NC = attn_fc_num_chunks(num_chunks);- const uint q_per_kv = NQ / NKV;- if (q_per_kv > kAttnMaxQPerKV) { return; }-- const uint kv_head = tg_id / NC;- const uint chunk = tg_id % NC;- const uint q_base = kv_head * q_per_kv;- const uint key_bytes_per_token = params.key_bytes_per_head * NKV;- const uint value_bytes_per_token = params.value_bytes_per_head * NKV;- const uint p_start = params.kv_start + chunk * chunk_len;- uint p_end = p_start + chunk_len;- if (p_end > params.seq_len) { p_end = params.seq_len; }-- for (uint qg = 0; qg < q_per_kv; ++qg) {- device const half* Q_row = Q + (q_base + qg) * HD;- threadgroup float* Q_s = q_smem + qg * kAttnMaxHeadDim;- for (uint i = lid; i < HD; i += lsize) {- if (params.q_pretransformed != 0u) {- Q_s[i] = float(Q_row[i]);- } else {- const float q = float(Q_row[i]);- Q_s[i] = attn_tq_apply_rotation(q,- params.layer,- kv_head,- i,- params.rotation_seed);- }- }- }- threadgroup_barrier(mem_flags::mem_threadgroup);- if (params.q_pretransformed == 0u) {- for (uint qg = 0; qg < q_per_kv; ++qg) {- attn_tq_wht_inplace_fast(q_smem + qg * kAttnMaxHeadDim, HD, lid, lsize, simd_lane_id);- }- }-- const uint groups_per_q = max(1u, (lsize / 32u) / q_per_kv);- const uint active_q = min(q_per_kv - 1u, simd_group_id / groups_per_q);- const uint local_group = simd_group_id - active_q * groups_per_q;- const uint threads_per_q = groups_per_q * 32u;- const uint local_lid = local_group * 32u + simd_lane_id;-- constexpr uint kGQAPerThread =- (kAttnMaxHeadDim + (kAttnThreads / kAttnMaxQPerKV) - 1) /- (kAttnThreads / kAttnMaxQPerKV);- float o_local[kGQAPerThread];- for (uint k = 0; k < kGQAPerThread; ++k) { o_local[k] = 0.0f; }-- float m_run = -INFINITY;- float d_run = 0.0f;-- for (uint p = p_start; p < p_end; ++p) {- const uint key_head_base = p * key_bytes_per_token- + kv_head * params.key_bytes_per_head;- const uint value_head_base = p * value_bytes_per_token- + kv_head * params.value_bytes_per_head;- const device half* key_scale_ptr = reinterpret_cast<const device half*>(- K_cache + key_head_base + params.key_scale_offset);- const device half* value_scale_ptr = reinterpret_cast<const device half*>(- V_cache + value_head_base + params.value_scale_offset);- const float key_scale = float(*key_scale_ptr);- const float value_scale = float(*value_scale_ptr);-- float partial = 0.0f;- for (uint i = local_lid; i < HD; i += threads_per_q) {- const float k_val = attn_tq_read_packed(K_cache,- key_head_base,- 4u,- params.key_packed_offset,- HD,- i,- key_scale);- partial = fma(q_smem[active_q * kAttnMaxHeadDim + i], k_val, partial);- }-- float s = simd_sum(partial);- if (simd_lane_id == 0) {- reduce_scratch[active_q * kAttnMaxSimdGroups + local_group] = s;- }- threadgroup_barrier(mem_flags::mem_threadgroup);- if (local_group == 0) {- float t = (simd_lane_id < groups_per_q)- ? reduce_scratch[active_q * kAttnMaxSimdGroups + simd_lane_id]- : 0.0f;- t = simd_sum(t);- if (simd_lane_id == 0) { bcast[active_q] = t; }- }- threadgroup_barrier(mem_flags::mem_threadgroup);- s = bcast[active_q] * params.scale;-- const float m_new = max(m_run, s);- const float alpha = attn_softmax_exp(m_run - m_new);- const float p_exp = attn_softmax_exp(s - m_new);- d_run = d_run * alpha + p_exp;- for (uint slot = 0; slot < kGQAPerThread; ++slot) { o_local[slot] *= alpha; }- m_run = m_new;-- uint slot = 0;- for (uint i = local_lid; i < HD; i += threads_per_q) {- float v_val = attn_tq_read_packed(V_cache,- value_head_base,- 4u,- params.value_packed_offset,- HD,- i,- value_scale);- o_local[slot] += p_exp * v_val;- slot += 1;- }- }-- const uint q_head = q_base + active_q;- const uint base = q_head * NC + chunk;- if (local_lid == 0) {- m_out[base] = m_run;- d_out[base] = d_run;- }- device float* o_row = o_out + base * HD;- uint slot = 0;- for (uint i = local_lid; i < HD; i += threads_per_q) {- o_row[i] = o_local[slot];- slot += 1;- }-}--[[kernel, max_total_threads_per_threadgroup(kAttnThreads)]]-void attention_turboquant_decode_combine(- device const float* m_in [[buffer(0)]],- device const float* d_in [[buffer(1)]],- device const float* o_in [[buffer(2)]],- device half* out [[buffer(3)]],- constant AttentionTurboQuantKVParams& params [[buffer(4)]],- constant uint& num_chunks [[buffer(5)]],- uint tg_id [[threadgroup_position_in_grid]],- uint lid [[thread_position_in_threadgroup]],- uint lsize [[threads_per_threadgroup]],- uint simd_lane_id [[thread_index_in_simdgroup]]-) {- threadgroup float out_smem[kAttnMaxHeadDim];- const uint HD = attn_fc_head_dim(params.head_dim);- const uint NQ = attn_fc_num_q_heads(params.num_q_heads);- const uint NKV = attn_fc_num_kv_heads(params.num_kv_heads);- const uint NC = attn_fc_num_chunks(num_chunks);- const uint q_head = tg_id;- const uint kv_head = q_head / (NQ / NKV);- device const float* m_row = m_in + q_head * NC;- device const float* d_row = d_in + q_head * NC;- device const float* o_base = o_in + q_head * NC * HD;-- float m_glob = -INFINITY;- for (uint c = 0; c < NC; ++c) {- m_glob = max(m_glob, m_row[c]);- }- float D = 0.0f;- for (uint c = 0; c < NC; ++c) {- D += d_row[c] * attn_softmax_exp(m_row[c] - m_glob);- }- const float inv_d = (D > 0.0f) ? (1.0f / D) : 0.0f;-- for (uint i = lid; i < HD; i += lsize) {- float acc = 0.0f;- for (uint c = 0; c < NC; ++c) {- acc += o_base[c * HD + i] * attn_softmax_exp(m_row[c] - m_glob);- }- out_smem[i] = acc * inv_d;- }-- threadgroup_barrier(mem_flags::mem_threadgroup);- attn_tq_wht_inplace_fast(out_smem, HD, lid, lsize, simd_lane_id);-- device half* out_row = out + q_head * HD;- for (uint i = lid; i < HD; i += lsize) {- out_row[i] = half(attn_tq_apply_rotation(out_smem[i],- params.layer,- kv_head,- i,- params.rotation_seed));- }-}// ============================================================================// Split-KV (Flash-Decoding) decode attention — the default path.//-// The single-pass kernels above run one threadgroup per Q head, each serially-// streaming the whole K/V history. At decode (M_q=1) that is occupancy- and-// latency-bound: 16 Q heads -> 16 threadgroups (cannot fill the GPU's cores),-// and the per-head critical path is seq_len positions long. Splitting each-// head's [kv_start, seq_len) range across `num_chunks` threadgroups turns it-// into 16 * num_chunks threadgroups whose critical path is ~seq_len/num_chunks.-//-// This D512 specialization adapts MLX v0.32.0's one-pass vector geometry. MLX-// does not instantiate its vector kernel at D512. TurboFieldfare selects this path-// for full-attention decode.-kernel void attention_decode_mlx_geometry_full_v2(- device const half* Q [[buffer(0)]],- device const half* K [[buffer(1)]],- device const half* V [[buffer(2)]],- device half* out [[buffer(3)]],- constant uint& seq_len [[buffer(4)]],- constant float& scale [[buffer(5)]],- uint q_head [[threadgroup_position_in_grid]],- uint simd_gid [[simdgroup_index_in_threadgroup]],- uint simd_lid [[thread_index_in_simdgroup]])-{- constexpr uint kHeadDim = 512;- constexpr uint kNumKVHeads = 2;- constexpr uint kQPerKV = 8;- constexpr uint kSIMDGroups = 32;- constexpr uint kComponentsPerLane = 16;-- thread float q[kComponentsPerLane];- thread float key[kComponentsPerLane];- thread float output[kComponentsPerLane];- threadgroup float output_exchange[kSIMDGroups * 32];- threadgroup float max_scores[kSIMDGroups];- threadgroup float sum_exp_scores[kSIMDGroups];-- const uint kv_head = q_head / kQPerKV;- const uint component = simd_lid * kComponentsPerLane;- const uint q_base = q_head * kHeadDim + component;- for (uint i = 0; i < kComponentsPerLane; ++i) {- q[i] = scale * float(Q[q_base + i]);- output[i] = 0.0f;- }-- float max_score = -INFINITY;- float sum_exp_score = 0.0f;- for (uint position = simd_gid; position < seq_len; position += kSIMDGroups) {- const uint kv_base = (position * kNumKVHeads + kv_head) * kHeadDim + component;- float score = 0.0f;- for (uint i = 0; i < kComponentsPerLane; ++i) {- key[i] = float(K[kv_base + i]);- score += q[i] * key[i];- }- score = simd_sum(score);-- const float new_max = max(max_score, score);- const float old_factor = fast::exp(max_score - new_max);- const float score_factor = fast::exp(score - new_max);- max_score = new_max;- sum_exp_score = sum_exp_score * old_factor + score_factor;- for (uint i = 0; i < kComponentsPerLane; ++i) {- output[i] = output[i] * old_factor + score_factor * float(V[kv_base + i]);- }- }-- if (simd_lid == 0) {- max_scores[simd_gid] = max_score;- sum_exp_scores[simd_gid] = sum_exp_score;- }- threadgroup_barrier(mem_flags::mem_threadgroup);-- max_score = max_scores[simd_lid];- const float merged_max = simd_max(max_score);- const float merge_factor = fast::exp(max_score - merged_max);- sum_exp_score = simd_sum(sum_exp_scores[simd_lid] * merge_factor);-- for (uint i = 0; i < kComponentsPerLane; ++i) {- output_exchange[simd_lid * kSIMDGroups + simd_gid] = output[i];- threadgroup_barrier(mem_flags::mem_threadgroup);- float merged = simd_sum(- output_exchange[simd_gid * kSIMDGroups + simd_lid] * merge_factor);- output[i] = sum_exp_score == 0.0f ? merged : merged / sum_exp_score;- threadgroup_barrier(mem_flags::mem_threadgroup);- }-- if (simd_lid == 0) {- const uint out_base = q_head * kHeadDim + simd_gid * kComponentsPerLane;- for (uint i = 0; i < kComponentsPerLane; ++i) {- out[out_base + i] = half(output[i]);- }- }-}// Pass 1 (attention_decode_partial): grid = num_q_heads * num_chunks. Each TG// runs the same online-softmax recurrence over its chunk [p_start, p_end) anddiff --git a/Sources/TurboFieldfare/Metal/KVCache/turboquant.metal b/Sources/TurboFieldfare/Metal/KVCache/turboquant.metaldeleted file mode 100644index 6825905f..00000000--- a/Sources/TurboFieldfare/Metal/KVCache/turboquant.metal+++ /dev/null@@ -1,238 +0,0 @@-#include <metal_stdlib>-using namespace metal;--// Fused Walsh-Hadamard transform and K4/V4 Lloyd-Max cache packing.-// One threadgroup handles each flattened (token, head) pair.--constant constexpr float kTQCodebook4[16] = {- -2.7326f, -2.0690f, -1.6181f, -1.2562f,- -0.9424f, -0.6568f, -0.3881f, -0.1284f,- 0.1284f, 0.3881f, 0.6568f, 0.9424f,- 1.2562f, 1.6181f, 2.0690f, 2.7326f-};--constant constexpr float kTQDecision4[15] = {- (-2.7326f + -2.0690f) * 0.5f,- (-2.0690f + -1.6181f) * 0.5f,- (-1.6181f + -1.2562f) * 0.5f,- (-1.2562f + -0.9424f) * 0.5f,- (-0.9424f + -0.6568f) * 0.5f,- (-0.6568f + -0.3881f) * 0.5f,- (-0.3881f + -0.1284f) * 0.5f,- (-0.1284f + 0.1284f) * 0.5f,- ( 0.1284f + 0.3881f) * 0.5f,- ( 0.3881f + 0.6568f) * 0.5f,- ( 0.6568f + 0.9424f) * 0.5f,- ( 0.9424f + 1.2562f) * 0.5f,- ( 1.2562f + 1.6181f) * 0.5f,- ( 1.6181f + 2.0690f) * 0.5f,- ( 2.0690f + 2.7326f) * 0.5f-};--inline uint tq_nearest_index4(float v) {- uint idx = 0;- idx += (v >= kTQDecision4[ 0]) ? 1u : 0u;- idx += (v >= kTQDecision4[ 1]) ? 1u : 0u;- idx += (v >= kTQDecision4[ 2]) ? 1u : 0u;- idx += (v >= kTQDecision4[ 3]) ? 1u : 0u;- idx += (v >= kTQDecision4[ 4]) ? 1u : 0u;- idx += (v >= kTQDecision4[ 5]) ? 1u : 0u;- idx += (v >= kTQDecision4[ 6]) ? 1u : 0u;- idx += (v >= kTQDecision4[ 7]) ? 1u : 0u;- idx += (v >= kTQDecision4[ 8]) ? 1u : 0u;- idx += (v >= kTQDecision4[ 9]) ? 1u : 0u;- idx += (v >= kTQDecision4[10]) ? 1u : 0u;- idx += (v >= kTQDecision4[11]) ? 1u : 0u;- idx += (v >= kTQDecision4[12]) ? 1u : 0u;- idx += (v >= kTQDecision4[13]) ? 1u : 0u;- idx += (v >= kTQDecision4[14]) ? 1u : 0u;- return idx;-}--inline float tq_centroid4(uint idx) {- return kTQCodebook4[idx];-}--// =========================================================================-// Walsh-Hadamard transform-//-// Iterative butterfly, log2(D) stages. Each stage:-// stride s = 1, 2, 4, ..., D/2-// for each (i, j=i+s) with (i & s) == 0:-// a = x[i]; b = x[j]-// x[i] = (a + b) * INV_SQRT2-// x[j] = (a - b) * INV_SQRT2-//-// One threadgroup per (token, head). D threads, one element per thread held in-// threadgroup memory. Cross-thread butterflies are handled by reading the-// partner element across the threadgroup with a barrier between stages. The-// largest supported head uses 2 KiB of shared float storage, keeping the fused-// cache-write path bounded.-// =========================================================================--constant constexpr float kInvSqrt2 = 0.7071067811865475f;--struct TurboQuantWHTParams {- uint num_heads;- uint layer;- uint rotation_seed;- uint apply_rotation;-};--inline ulong tq_mix64(ulong z) {- z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ul;- z = (z ^ (z >> 27)) * 0x94D049BB133111EBul;- return z ^ (z >> 31);-}--inline uint tq_rotation_sign(uint layer, uint head, uint dim, uint seed) {- ulong z = ulong(seed);- z ^= ulong(layer) * 0x9E3779B97F4A7C15ul;- z ^= ulong(head) * 0xBF58476D1CE4E5B9ul;- z ^= ulong(dim) * 0x94D049BB133111EBul;- return uint(tq_mix64(z) >> 63);-}--inline float tq_apply_rotation(float v,- constant TurboQuantWHTParams& params,- uint pair,- uint dim) {- if (params.apply_rotation == 0u) {- return v;- }- const uint head = pair % params.num_heads;- return tq_rotation_sign(params.layer, head, dim, params.rotation_seed) != 0u ? -v : v;-}--inline float wht_body(float v,- threadgroup float* shared,- uint lid,- uint D,- uint simd_lane) {- // FP32 throughout for stability; D=512 with FP16 amax ~1 produces a- // post-WHT scale roughly sqrt(D)=22, well within FP16 range, but- // intermediate sums overflow if accumulated in FP16.- for (uint stride = 1u; stride < 32u; stride <<= 1u) {- float other = simd_shuffle_xor(v, stride);- v = ((simd_lane & stride) == 0u)- ? (v + other) * kInvSqrt2- : (other - v) * kInvSqrt2;- }-- shared[lid] = v;- for (uint stride = 32u; stride < D; stride <<= 1u) {- threadgroup_barrier(mem_flags::mem_threadgroup);- if ((lid & stride) == 0u) {- uint j = lid | stride;- float a = shared[lid];- float b = shared[j];- shared[lid] = (a + b) * kInvSqrt2;- shared[j] = (a - b) * kInvSqrt2;- }- }- threadgroup_barrier(mem_flags::mem_threadgroup);- return shared[lid];-}--struct TurboQuantKVWriteParams {- uint D;- uint num_heads;- uint bytes_per_head;- uint packed_offset;- uint scale_offset;- uint token_base;- uint bytes_per_token;-};--constant uint FC_TQ_D [[function_constant(100)]];-constant uint FC_TQ_NUM_HEADS [[function_constant(101)]];-constant bool FC_TQ_USE_FC [[function_constant(103)]];--static inline bool tq_use_fc() {- return is_function_constant_defined(FC_TQ_USE_FC) && FC_TQ_USE_FC;-}--static inline uint tq_kv_fc_d(constant TurboQuantKVWriteParams& params) {- return (tq_use_fc() && is_function_constant_defined(FC_TQ_D)) ? FC_TQ_D : params.D;-}--static inline uint tq_kv_fc_num_heads(constant TurboQuantKVWriteParams& params) {- return (tq_use_fc() && is_function_constant_defined(FC_TQ_NUM_HEADS)) ? FC_TQ_NUM_HEADS : params.num_heads;-}--static inline uint tq_kv_write_head_base(constant TurboQuantKVWriteParams& params, uint pair) {- const uint num_heads = tq_kv_fc_num_heads(params);- const uint token_in_span = pair / num_heads;- const uint head = pair % num_heads;- return token_in_span * params.bytes_per_token + head * params.bytes_per_head;-}--[[kernel, max_total_threads_per_threadgroup(512)]]-void turboquant_quant_kv_write_wht(- device const half* x [[buffer(0)]], // [pairs, D] FP16, pre-WHT- device uint8_t* cache [[buffer(1)]], // [heads, packed values + scale]- constant TurboQuantKVWriteParams& params [[buffer(2)]],- constant TurboQuantWHTParams& wht_params [[buffer(3)]],- uint lid [[thread_position_in_threadgroup]],- uint lsize [[threads_per_threadgroup]],- uint pair [[threadgroup_position_in_grid]],- uint simd_lane [[thread_index_in_simdgroup]],- uint simd_group [[simdgroup_index_in_threadgroup]],- uint simdgroups [[simdgroups_per_threadgroup]]-) {- const uint D = tq_kv_fc_d(params);- threadgroup float values[512];- threadgroup float partial[16];-- const uint base = pair * D;- float v = tq_apply_rotation(float(x[base + lid]), wht_params, pair, lid);- v = wht_body(v, values, lid, D, simd_lane);- values[lid] = float(half(v));- threadgroup_barrier(mem_flags::mem_threadgroup);-- float acc = 0.0f;- for (uint i = lid; i < D; i += lsize) {- float w = values[i];- acc = fma(w, w, acc);- }- acc = simd_sum(acc);- if (simd_lane == 0) {- partial[simd_group] = acc;- }- threadgroup_barrier(mem_flags::mem_threadgroup);-- threadgroup float l2_inv_tg;- threadgroup float l2_scale_tg;- if (simd_group == 0) {- float sum = (simd_lane < simdgroups) ? partial[simd_lane] : 0.0f;- sum = simd_sum(sum);- if (simd_lane == 0) {- float s = sqrt(max(sum / float(D), 1e-12f));- l2_scale_tg = s;- l2_inv_tg = 1.0f / s;- }- }- threadgroup_barrier(mem_flags::mem_threadgroup);-- const uint head_base = tq_kv_write_head_base(params, pair);-- if (lid == 0) {- device half* scale = reinterpret_cast<device half*>(cache + head_base + params.scale_offset);- *scale = half(l2_scale_tg);- }-- threadgroup uint8_t code4[1024];- const float inv = l2_inv_tg;- for (uint i = lid; i < D; i += lsize) {- float qv = values[i] * inv;- code4[i] = uint8_t(tq_nearest_index4(qv));- }- threadgroup_barrier(mem_flags::mem_threadgroup);-- if (lid < D / 2u) {- uint d0 = lid * 2u;- uint packed = (uint(code4[d0 + 0]) & 0xFu)- | ((uint(code4[d0 + 1]) & 0xFu) << 4);- cache[head_base + params.packed_offset + lid] = uint8_t(packed);- }-}diff --git a/Sources/TurboFieldfare/Metal/Prefill/prefill.metal b/Sources/TurboFieldfare/Metal/Prefill/prefill.metalindex 651681c8..742ff410 100644--- a/Sources/TurboFieldfare/Metal/Prefill/prefill.metal+++ b/Sources/TurboFieldfare/Metal/Prefill/prefill.metal@@ -18,7 +18,6 @@ static inline float prefill_gelu_pytorch_tanh(float x) {inner = clamp(inner, -20.0f, 20.0f);return 0.5f * x * (1.0f + tanh(inner));}-kernel void prefill_embed_lookup_int4_block(device const uint8_t* table [[buffer(0)]],device const bfloat* scales [[buffer(1)]],@@ -892,222 +891,3 @@ kernel void attention_prefill_causal_tiled(out_row[d] = row_sum > 0.0f ? half(acc / row_sum) : half(0.0f);}}--struct PrefillTurboQuantAttentionParams {- uint startPosition;- uint queryCount;- uint headDim;- uint numQHeads;- uint numKVHeads;- uint kvValidCount;- uint slidingWindow;- uint qTokenStrideElements;- uint oTokenStrideElements;- float scale;- uint layer;- uint rotationSeed;- uint keyBytesPerHead;- uint keyPackedOffset;- uint keyScaleOffset;- uint valueBytesPerHead;- uint valuePackedOffset;- uint valueScaleOffset;-};--constant constexpr float kPrefillTQCodebook4[16] = {- -2.7326f, -2.0690f, -1.6181f, -1.2562f,- -0.9424f, -0.6568f, -0.3881f, -0.1284f,- 0.1284f, 0.3881f, 0.6568f, 0.9424f,- 1.2562f, 1.6181f, 2.0690f, 2.7326f-};--static inline float prefill_tq_centroid(uint idx) {- return kPrefillTQCodebook4[idx];-}--static inline ulong prefill_tq_mix64(ulong z) {- z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ul;- z = (z ^ (z >> 27)) * 0x94D049BB133111EBul;- return z ^ (z >> 31);-}--static inline bool prefill_tq_rotation_is_negative(uint layer,- uint head,- uint dim,- uint seed) {- ulong z = ulong(seed);- z ^= ulong(layer) * 0x9E3779B97F4A7C15ul;- z ^= ulong(head) * 0xBF58476D1CE4E5B9ul;- z ^= ulong(dim) * 0x94D049BB133111EBul;- return (prefill_tq_mix64(z) >> 63) != 0ul;-}--static inline float prefill_tq_apply_rotation(float v,- uint layer,- uint head,- uint dim,- uint seed) {- return prefill_tq_rotation_is_negative(layer, head, dim, seed) ? -v : v;-}--static inline void prefill_tq_wht_inplace(threadgroup float* data,- uint D,- uint lid,- uint lsize) {- for (uint stride = 1u; stride < D; stride <<= 1u) {- for (uint j = lid; j < D / 2u; j += lsize) {- const uint block = j / stride;- const uint lane = j - block * stride;- const uint a_idx = block * stride * 2u + lane;- const uint b_idx = a_idx + stride;- const float a = data[a_idx];- const float b = data[b_idx];- data[a_idx] = (a + b) * 0.7071067811865475f;- data[b_idx] = (a - b) * 0.7071067811865475f;- }- threadgroup_barrier(mem_flags::mem_threadgroup);- }-}--static inline uint prefill_tq_read_index(device const uint8_t* cache,- uint head_base,- uint packed_offset,- uint dim) {- const uint packed_base = head_base + packed_offset;- const uint byte = dim >> 1u;- const uint shift = (dim & 1u) << 2u;- return (uint(cache[packed_base + byte]) >> shift) & 0xFu;-}--static inline float prefill_tq_read_packed(device const uint8_t* cache,- uint head_base,- uint packed_offset,- uint dim,- float scale) {- return prefill_tq_centroid(- prefill_tq_read_index(cache, head_base, packed_offset, dim)) * scale;-}--[[kernel, max_total_threads_per_threadgroup(256)]]-kernel void attention_prefill_turboquant_causal_tiled(- device const half* Q [[buffer(0)]],- device const uint8_t* K_cache [[buffer(1)]],- device const uint8_t* V_cache [[buffer(2)]],- device half* O [[buffer(3)]],- constant PrefillTurboQuantAttentionParams& p [[buffer(4)]],- uint3 tg [[threadgroup_position_in_grid]],- uint3 tid3 [[thread_position_in_threadgroup]],- uint3 lsize3 [[threads_per_threadgroup]],- uint lane [[thread_index_in_simdgroup]],- uint simd_group [[simdgroup_index_in_threadgroup]],- uint simdgroups [[simdgroups_per_threadgroup]]-) {- const uint t = tg.x;- const uint qh = tg.y;- if (t >= p.queryCount || qh >= p.numQHeads) return;-- threadgroup float q_smem[512];- threadgroup float out_smem[512];- threadgroup float partial[kPrefillAttentionMaxSimdGroups];-- const uint D = p.headDim;- const uint tid = tid3.x;- const uint lsize = lsize3.x;- const uint q_per_kv = p.numQHeads / p.numKVHeads;- const uint kvh = qh / q_per_kv;- const uint key_bytes_per_token = p.keyBytesPerHead * p.numKVHeads;- const uint value_bytes_per_token = p.valueBytesPerHead * p.numKVHeads;- const uint abs_q = p.startPosition + t;-- uint first = 0u;- 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);-- device const half* q_row = Q + t * p.qTokenStrideElements + qh * D;- for (uint i = tid; i < D; i += lsize) {- const float qv = float(q_row[i]);- q_smem[i] = prefill_tq_apply_rotation(qv, p.layer, kvh, i, p.rotationSeed);- }- threadgroup_barrier(mem_flags::mem_threadgroup);- prefill_tq_wht_inplace(q_smem, D, tid, lsize);-- float row_max = -INFINITY;- float row_sum = 0.0f;- float acc0 = 0.0f;- float acc1 = 0.0f;- const uint d0 = tid;- const uint d1 = tid + lsize;- const bool owns0 = d0 < D;- const bool owns1 = d1 < D;-- for (uint key = first; key < last_exclusive; ++key) {- const uint key_head_base = key * key_bytes_per_token + kvh * p.keyBytesPerHead;- const uint value_head_base = key * value_bytes_per_token + kvh * p.valueBytesPerHead;- const device half* key_scale_ptr = reinterpret_cast<const device half*>(- K_cache + key_head_base + p.keyScaleOffset);- const device half* value_scale_ptr = reinterpret_cast<const device half*>(- V_cache + value_head_base + p.valueScaleOffset);- const float key_scale = float(*key_scale_ptr);- const float value_scale = float(*value_scale_ptr);-- float partial_dot = 0.0f;- for (uint i = tid; i < D; i += lsize) {- const float k_val = prefill_tq_read_packed(K_cache,- key_head_base,- p.keyPackedOffset,- i,- key_scale);- partial_dot = fma(q_smem[i], k_val, partial_dot);- }-- float score = prefill_attention_tg_sum_single_bank(- partial_dot, lane, simd_group, simdgroups, partial);- score *= p.scale;-- const float new_max = max(row_max, score);- const float old_scale = row_sum > 0.0f ? fast::exp(row_max - new_max) : 0.0f;- const float new_scale = fast::exp(score - new_max);- if (owns0) {- const float v0 = prefill_tq_read_packed(V_cache,- value_head_base,- p.valuePackedOffset,- d0,- value_scale);- acc0 = fma(new_scale, v0, acc0 * old_scale);- }- if (owns1) {- const float v1 = prefill_tq_read_packed(V_cache,- value_head_base,- p.valuePackedOffset,- d1,- value_scale);- acc1 = fma(new_scale, v1, acc1 * old_scale);- }- row_sum = row_sum * old_scale + new_scale;- row_max = new_max;- }-- if (owns0) {- out_smem[d0] = row_sum > 0.0f ? acc0 / row_sum : 0.0f;- }- if (owns1) {- out_smem[d1] = row_sum > 0.0f ? acc1 / row_sum : 0.0f;- }- threadgroup_barrier(mem_flags::mem_threadgroup);-- prefill_tq_wht_inplace(out_smem, D, tid, lsize);-- if (owns0) {- device half* out_row = O + t * p.oTokenStrideElements + qh * D;- const float value0 = prefill_tq_apply_rotation(- out_smem[d0], p.layer, kvh, d0, p.rotationSeed);- out_row[d0] = half(value0);- if (owns1) {- const float value1 = prefill_tq_apply_rotation(- out_smem[d1], p.layer, kvh, d1, p.rotationSeed);- out_row[d1] = half(value1);- }- }-}diff --git a/Sources/TurboFieldfare/Metal/Primitives/utility.metal b/Sources/TurboFieldfare/Metal/Primitives/utility.metalnew file mode 100644index 00000000..11d8c770--- /dev/null+++ b/Sources/TurboFieldfare/Metal/Primitives/utility.metal@@ -0,0 +1,18 @@+#include <metal_stdlib>+using namespace metal;++// Kept in the shared library so both INT4 and INT8 shared-expert paths use+// the same Gemma activation without compiling a private shader module.+[[kernel, max_total_threads_per_threadgroup(256)]]+void gelu_mul_fp16(+ device const half* gate [[buffer(0)]],+ device const half* up [[buffer(1)]],+ device half* out [[buffer(2)]],+ constant uint& count [[buffer(3)]],+ uint tid [[thread_position_in_grid]]+) {+ if (tid >= count) return;+ const float g = float(gate[tid]);+ const float u = float(up[tid]);+ out[tid] = half(gelu_pytorch_tanh(g) * u);+}diff --git a/Sources/TurboFieldfare/Runtime/Configuration/RuntimeConfiguration.swift b/Sources/TurboFieldfare/Runtime/Configuration/RuntimeConfiguration.swiftindex 99d7e22b..4da2dbcc 100644--- a/Sources/TurboFieldfare/Runtime/Configuration/RuntimeConfiguration.swift+++ b/Sources/TurboFieldfare/Runtime/Configuration/RuntimeConfiguration.swift@@ -1,8 +1,3 @@-public enum RuntimeKVStorage: String, Codable, Sendable {- case fp16- case packedK4V4 = "packed-k4v4"-}-public enum RuntimeHeadPath: String, Codable, Sendable {case fusedRows = "fused-rows"case logits@@ -22,7 +17,6 @@ public struct RuntimeConfiguration: Sendable, Equatable {public static let allowedExpertCacheSlots = [8, 16, 24, 32]public static let allowedPrefillChunkTokens = [32, 64, 128]- public let kvStorage: RuntimeKVStoragepublic let expertCacheSlots: Intpublic let expertCachePolicy: RuntimeExpertCachePolicypublic let rdadvisePolicy: RDAdvicePolicyMode@@ -35,13 +29,11 @@ public struct RuntimeConfiguration: Sendable, Equatable {rdadvisePolicy: RDAdvicePolicyMode = .off,prefillEnabled: Bool = true,prefillChunkTokens: Int = 128,- turboQuantKVEnabled: Bool = false,forceLogitsHead: Bool = false) {precondition(Self.allowedExpertCacheSlots.contains(expertCacheSlots),"unsupported expert-cache slot count")precondition(Self.allowedPrefillChunkTokens.contains(prefillChunkTokens),"unsupported prefill chunk size")- self.kvStorage = turboQuantKVEnabled ? .packedK4V4 : .fp16self.expertCacheSlots = expertCacheSlotsself.expertCachePolicy = expertCachePolicyself.rdadvisePolicy = rdadvisePolicy@@ -54,7 +46,7 @@ public struct RuntimeConfiguration: Sendable, Equatable {RuntimeConfiguration()}- public var fp16RingEnabled: Bool { kvStorage == .fp16 }+ public var fp16RingEnabled: Bool { true }public var rdadviseEnabled: Bool { rdadvisePolicy != .off }public var prefillConfig: PrefillRuntimeConfig {switch prefillPolicy {@@ -64,7 +56,6 @@ public struct RuntimeConfiguration: Sendable, Equatable {return .production(chunkTokens: prefillChunkTokens)}}- public var turboQuantKVEnabled: Bool { kvStorage == .packedK4V4 }public var modelExpertCachePolicy: ExpertCachePolicy {expertCachePolicy == .lru ? .lru : .lfu}diff --git a/Sources/TurboFieldfare/Runtime/Inference/Model.swift b/Sources/TurboFieldfare/Runtime/Inference/Model.swiftindex 7cf217a1..f8d07534 100644--- a/Sources/TurboFieldfare/Runtime/Inference/Model.swift+++ b/Sources/TurboFieldfare/Runtime/Inference/Model.swift@@ -31,6 +31,9 @@ public struct Model {public let streamingMode: ExpertStreamingModepublic let expertCachePolicy: ExpertCachePolicypublic let integrityPolicy: ModelIntegrityPolicy+ public var modelID: String { manifest.modelID }+ public var sourceSnapshotHash: String? { manifest.sourceSnapshotHash }+ public var sharedExpertWeightBits: Int { manifest.quant?.sharedExpert.weightBits ?? 8 }let residentBuffer: ResidentBufferlet residentIndex: ResidentIndexdiff --git a/Sources/TurboFieldfare/Runtime/Inference/RealForwardRunner.swift b/Sources/TurboFieldfare/Runtime/Inference/RealForwardRunner.swiftindex 2d5a5cac..81c949db 100644--- a/Sources/TurboFieldfare/Runtime/Inference/RealForwardRunner.swift+++ b/Sources/TurboFieldfare/Runtime/Inference/RealForwardRunner.swift@@ -141,7 +141,6 @@ public final class RealForwardRunner: ChunkedPrefillRunner, ContextWindowReportiprivate let model: Modelprivate let ctx: MetalContextprivate let kv: KVCacheManager?- private let turboQuantKV: KVCacheManager?private let cfg: ArchConfig// Kernels@@ -149,14 +148,13 @@ public final class RealForwardRunner: ChunkedPrefillRunner, ContextWindowReportiprivate let rms: RMSNormprivate let int4: DequantInt4GEMVprivate let attention: Attention- private let shared: SharedExpertInt8+ private let shared: SharedExpertRuntimeprivate let moe: MoEprivate let fusionHead: LMHeadChainInt4private let fusedQKVGEMV: FusedQKVGEMVprivate let fusedQKVEpilogue: FusedQKVEpilogueprivate let fusedPostAttentionSetup: FusedPostAttentionSetupprivate let fusedTail: FusedLayerTail- private let turboQuantQuant: TurboQuantQuant?// Prefill kernels. These are initialized once per runner so the chunk path// cannot accidentally rebuild PSOs inside a per-layer loop.@@ -186,7 +184,9 @@ public final class RealForwardRunner: ChunkedPrefillRunner, ContextWindowReportiprivate let h2Buf: MTLBuffer // [D] FP16 (routed output)private let routedX: MTLBuffer // [D] FP16 (pre_feedforward_layernorm_2 output)private let denseX: MTLBuffer // [D] FP16 (pre_feedforward_layernorm output)- private let denseScratchA: MTLBuffer // [F=2112] FP16+ private let denseScratchGate: MTLBuffer // [F=2112] FP16+ private let denseScratchUp: MTLBuffer // [F=2112] FP16+ private let denseScratchAct: MTLBuffer // [F=2112] FP16private let routerInput: MTLBuffer // [D] FP16 (rmsnorm_no_scale(h))private let zeroResidual: MTLBuffer // [D] FP16 zeros — for routed branch baseprivate let outIndices: MTLBuffer // [topK] UInt32@@ -204,7 +204,6 @@ public final class RealForwardRunner: ChunkedPrefillRunner, ContextWindowReportiprivate static let rdadviseAdaptiveMissCap = 12private static let rdadviseAdaptiveByteCap: UInt64 = 384 * 1_048_576private static let rdadviseAdaptiveSlowCallNanos: UInt64 = 1_000_000- private static let turboQuantRotationSeed: UInt32 = 0xA11CEprivate static let prefillRoutedTileSchedulerConfig = PrefillRoutedTileSchedulerConfig()/// Per-layer `router.scale * D^-0.5` pre-folded into one BF16 buffer@@ -220,7 +219,6 @@ public final class RealForwardRunner: ChunkedPrefillRunner, ContextWindowReporti/// callers that sample from the logits buffer (non-greedy configs) must pass/// `forceLogitsHead: true` or they read a never-written buffer.private let useFusedGreedyHead: Bool- private let useTurboQuantKV: Boolpublic let rdadviseEnabled: Boolpublic let rdadvisePolicyMode: RDAdvicePolicyModeprivate var rdadviseSkipUntilPosition: Int = -1@@ -242,27 +240,19 @@ public final class RealForwardRunner: ChunkedPrefillRunner, ContextWindowReportibyteCap: Self.rdadviseAdaptiveByteCap,slowCallNanos: Self.rdadviseAdaptiveSlowCallNanos))self.rdadviseEnabled = runtimeConfiguration.rdadviseEnabled- self.useTurboQuantKV = runtimeConfiguration.turboQuantKVEnabled- self.kv = useTurboQuantKV- ? nil- : try KVCacheManager(device: context.device,- config: cfg,- maxContext: maxContext,- fp16RingEnabled: useFP16Ring,- slidingWindow: cfg.slidingWindow,- maxPrefillChunkTokens: PrefillRuntimeConfig.maxChunkTokens)- self.turboQuantKV = useTurboQuantKV- ? try KVCacheManager(device: context.device,- config: cfg,- maxContext: maxContext,- storageMode: .turboQuant(.k4v4NormCorrected))- : nil+ self.kv = try KVCacheManager(device: context.device,+ config: cfg,+ maxContext: maxContext,+ fp16RingEnabled: useFP16Ring,+ slidingWindow: cfg.slidingWindow,+ maxPrefillChunkTokens: PrefillRuntimeConfig.maxChunkTokens)self.embedInt4 = try EmbedLookupInt4(context: context)self.rms = try RMSNorm(context: context)self.int4 = try DequantInt4GEMV(context: context)self.attention = try Attention(context: context)- self.shared = try SharedExpertInt8(context: context)+ self.shared = try SharedExpertRuntime(context: context,+ weightBits: model.sharedExpertWeightBits)self.moe = try MoE(context: context)self.fusionHead = try LMHeadChainInt4(context: context,maxD: cfg.hiddenSize,@@ -271,9 +261,6 @@ public final class RealForwardRunner: ChunkedPrefillRunner, ContextWindowReportiself.fusedQKVEpilogue = try FusedQKVEpilogue(context: context)self.fusedPostAttentionSetup = try FusedPostAttentionSetup(context: context)self.fusedTail = try FusedLayerTail(context: context)- self.turboQuantQuant = useTurboQuantKV- ? try TurboQuantQuant(context: context)- : nilself.prefillEmbed = try PrefillEmbedLookupInt4(context: context)self.prefillRMS = try PrefillRMSNorm(context: context)self.prefillQMM = try PrefillInt4QMM(context: context)@@ -282,7 +269,9 @@ public final class RealForwardRunner: ChunkedPrefillRunner, ContextWindowReportiself.prefillAttention = try PrefillAttention(context: context)self.prefillPostAttention = try PrefillPostAttentionSetup(context: context)self.prefillRouter = try PrefillRouter(context: context)- self.prefillSharedExpert = try PrefillSharedExpert(context: context)+ self.prefillSharedExpert = try PrefillSharedExpert(+ context: context,+ weightBits: model.sharedExpertWeightBits)self.prefillGroupedMoE = try PrefillGroupedRoutedMoE(context: context)self.prefillMoE = try PrefillMoE(context: context)self.prefillLayerTail = try PrefillLayerTail(context: context)@@ -314,7 +303,9 @@ public final class RealForwardRunner: ChunkedPrefillRunner, ContextWindowReportiself.h2Buf = try buf(D)self.routedX = try buf(D)self.denseX = try buf(D)- self.denseScratchA = try buf(F)+ self.denseScratchGate = try buf(F)+ self.denseScratchUp = try buf(F)+ self.denseScratchAct = try buf(F)self.routerInput = try buf(D)self.zeroResidual = try buf(D)// The routed MoE kernel seeds y[d] = residual[d]; pinning this buffer@@ -332,8 +323,8 @@ public final class RealForwardRunner: ChunkedPrefillRunner, ContextWindowReporti}self.greedyTokenBuf = tok- func sharedProj(_ view: TensorView, rows: UInt32, cols: UInt32) -> SharedExpertInt8Proj {- SharedExpertInt8Proj(weights: view.buffer,+ func sharedProj(_ view: TensorView, rows: UInt32, cols: UInt32) -> SharedExpertProjection {+ SharedExpertProjection(weights: view.buffer,scales: view.buffer,biases: view.buffer,weightsOffset: Int(view.offset),@@ -385,7 +376,6 @@ public final class RealForwardRunner: ChunkedPrefillRunner, ContextWindowReportipublic func reset() {kv?.reset()- turboQuantKV?.reset()prefillChunkState.reset()rdadviseSkipUntilPosition = -1rdadviseAdaptiveState.reset()@@ -487,7 +477,7 @@ public final class RealForwardRunner: ChunkedPrefillRunner, ContextWindowReportithrow PrefillError.chunkedUnsupported("chunked prefill startPosition must be non-negative")}- let kvPosition = kv?.position ?? turboQuantKV?.position ?? 0+ let kvPosition = kv?.position ?? 0guard kvPosition == startPosition else {throw PrefillError.chunkedUnsupported("chunked prefill cursor \(kvPosition) != startPosition \(startPosition)")@@ -544,11 +534,10 @@ public final class RealForwardRunner: ChunkedPrefillRunner, ContextWindowReporticonfig: PrefillRuntimeConfig,writeFinalHead: Bool) async throws {guard !tokens.isEmpty else { return }- if kv == nil && turboQuantKV == nil {- throw PrefillError.chunkedUnsupported(- "chunked prefill attention requires fp16 or packed TurboQuant KV")+ guard kv != nil else {+ throw PrefillError.chunkedUnsupported("chunked prefill attention requires FP16 KV")}- let kvPosition = kv?.position ?? turboQuantKV?.position ?? 0+ let kvPosition = kv?.position ?? 0guard kvPosition == startPosition else {throw PrefillError.chunkedUnsupported("chunked prefill cursor \(kvPosition) != startPosition \(startPosition)")@@ -847,50 +836,6 @@ public final class RealForwardRunner: ChunkedPrefillRunner, ContextWindowReportivalueSource: scratch.vStage,bytesPerToken: bytes / t)}- if let tqKV = turboQuantKV,- let tqQuant = turboQuantQuant,- let layerLayout = tqKV.turboQuantLayout(layer: L) {- let whtParams = TurboQuantWHTParams(numHeads: UInt32(numKVHeads),- layer: UInt32(L),- rotationSeed: Self.turboQuantRotationSeed,- applyRotation: true)- let keyWriteParams = TurboQuantKVWriteParams(- d: UInt32(headDim),- numHeads: UInt32(numKVHeads),- roleLayout: layerLayout.key,- tokenBase: UInt32(startPosition))- let keyBulk = TurboQuantKVBulkWriteParams(- kv: keyWriteParams,- tokenCount: t,- dstTokenBase: startPosition,- cacheTokenCapacity: maxContext,- sourceTokenStrideElements: kvDim)- let keyBuffer = tqKV.quantizedKeyBuffer(layer: L, validTokenCount: maxContext)- try tqQuant.encodeKVWriteWHTBulk(commandBuffer: cb,- x: scratch.kStage,- cache: keyBuffer,- params: keyBulk,- whtParams: whtParams)-- let valueWriteParams = TurboQuantKVWriteParams(- d: UInt32(headDim),- numHeads: UInt32(numKVHeads),- roleLayout: layerLayout.value,- tokenBase: UInt32(startPosition))- let valueBulk = TurboQuantKVBulkWriteParams(- kv: valueWriteParams,- tokenCount: t,- dstTokenBase: startPosition,- cacheTokenCapacity: maxContext,- sourceTokenStrideElements: kvDim)- let valueBuffer = tqKV.quantizedValueBuffer(layer: L, validTokenCount: maxContext)- try tqQuant.encodeKVWriteWHTBulk(commandBuffer: cb,- x: scratch.vStage,- cache: valueBuffer,- params: valueBulk,- whtParams: whtParams)- }-let params = PrefillAttentionParams(startPosition: UInt32(startPosition),queryCount: UInt32(t),@@ -917,29 +862,9 @@ public final class RealForwardRunner: ChunkedPrefillRunner, ContextWindowReportiout: scratch.attentionOutput,params: params,kvRingCapacity: activeRingCapacity)- } else if let tqKV = turboQuantKV,- let layerLayout = tqKV.turboQuantLayout(layer: L) {- let keyBuffer = tqKV.quantizedKeyBuffer(- layer: L,- validTokenCount: startPosition + t)- let valueBuffer = tqKV.quantizedValueBuffer(- layer: L,- validTokenCount: startPosition + t)- let tqParams = PrefillTurboQuantAttentionParams(- prefill: params,- layer: UInt32(L),- rotationSeed: Self.turboQuantRotationSeed,- keyLayout: layerLayout.key,- valueLayout: layerLayout.value)- prefillAttention.encodeTurboQuantCausal(commandBuffer: cb,- q: scratch.q,- keyCache: keyBuffer,- valueCache: valueBuffer,- out: scratch.attentionOutput,- params: tqParams)} else {throw PrefillError.chunkedUnsupported(- "chunked prefill attention requires fp16 or packed TurboQuant KV")+ "chunked prefill attention requires FP16 KV")}encodeInt4Projection(commandBuffer: cb,family: .o,@@ -1043,6 +968,8 @@ public final class RealForwardRunner: ChunkedPrefillRunner, ContextWindowReportigate: sharedProj.gate,up: sharedProj.up,down: sharedProj.down,+ scratchGate: scratch.sharedGateScratch,+ scratchUp: scratch.sharedUpScratch,scratchAct: scratch.sharedActScratch,queryCount: t,d: D,@@ -1299,7 +1226,6 @@ public final class RealForwardRunner: ChunkedPrefillRunner, ContextWindowReporti}kv?.advance(by: tokens.count)- turboQuantKV?.advance(by: tokens.count)prefillChunkState.markCommitted()}@@ -1308,7 +1234,7 @@ public final class RealForwardRunner: ChunkedPrefillRunner, ContextWindowReportiinto logits: MTLBuffer,emitHead: Bool,outputMode: PrefillOutputMode) async throws {- let kvPosition = kv?.position ?? turboQuantKV?.position ?? 0+ let kvPosition = kv?.position ?? 0guard kvPosition == position else {throw PrefillError.prefillCursorMismatch("produce cursor \(kvPosition) != position \(position)")@@ -1460,85 +1386,7 @@ public final class RealForwardRunner: ChunkedPrefillRunner, ContextWindowReportieps: eps)}- let gTurboQuantKVWrite: (MTLCommandBuffer) -> Void = { [self] cb in- guard let tqKV = turboQuantKV,- let tqQuant = turboQuantQuant,- let layerLayout = tqKV.turboQuantLayout(layer: L) else {- return- }-- let whtParams = TurboQuantWHTParams(numHeads: UInt32(numKVL),- layer: UInt32(L),- rotationSeed: Self.turboQuantRotationSeed,- applyRotation: true)-- let keySlot = tqKV.quantizedKeySlot(layer: L, position: position)- let keyWriteParams = TurboQuantKVWriteParams(- d: UInt32(headDimL),- numHeads: UInt32(numKVL),- roleLayout: layerLayout.key,- tokenBase: UInt32(position))- tqQuant.encodeKVWriteWHT(commandBuffer: cb,- x: kSlot.buffer,- xOffset: kSlot.offset,- cache: keySlot.buffer,- cacheOffset: keySlot.offset,- params: keyWriteParams,- whtParams: whtParams,- pairs: numKVL)-- let valueSlot = tqKV.quantizedValueSlot(layer: L, position: position)- let valueWriteParams = TurboQuantKVWriteParams(- d: UInt32(headDimL),- numHeads: UInt32(numKVL),- roleLayout: layerLayout.value,- tokenBase: UInt32(position))- tqQuant.encodeKVWriteWHT(commandBuffer: cb,- x: vSlot.buffer,- xOffset: vSlot.offset,- cache: valueSlot.buffer,- cacheOffset: valueSlot.offset,- params: valueWriteParams,- whtParams: whtParams,- pairs: numKVL)- }-let gAttention: (MTLCommandBuffer) -> Void = { [self] cb in- if useTurboQuantKV,- let tqKV = turboQuantKV,- let layerLayout = tqKV.turboQuantLayout(layer: L) {- let keyBuffer = tqKV.quantizedKeyBuffer(- layer: L,- validTokenCount: Int(seqLen))- let valueBuffer = tqKV.quantizedValueBuffer(- layer: L,- validTokenCount: Int(seqLen))- let kvStart: UInt32 = isFull- ? 0- : (seqLen > UInt32(cfg.slidingWindow)- ? seqLen - UInt32(cfg.slidingWindow)- : 0)- let params = AttentionTurboQuantKVParams(- headDim: UInt32(headDimL),- numQHeads: UInt32(cfg.numHeads),- numKVHeads: UInt32(numKVL),- seqLen: seqLen,- kvStart: kvStart,- scale: 1.0,- layer: UInt32(L),- rotationSeed: Self.turboQuantRotationSeed,- keyLayout: layerLayout.key,- valueLayout: layerLayout.value)- attention.encodeTurboQuantSplit(- commandBuffer: cb,- q: qScratch,- keyCache: keyBuffer,- valueCache: valueBuffer,- out: attnOut,- params: params)- return- }-guard kv != nil else {preconditionFailure("FP16 attention requires an FP16 KV cache")}@@ -1614,9 +1462,6 @@ public final class RealForwardRunner: ChunkedPrefillRunner, ContextWindowReportigInputNorm(cb)gQKV(cb)gQKVEpilogue(cb)- if useTurboQuantKV {- gTurboQuantKVWrite(cb)- }gAttention(cb)gOProj(cb)gPostAttnSetup(cb)@@ -1731,7 +1576,9 @@ public final class RealForwardRunner: ChunkedPrefillRunner, ContextWindowReportiup: sharedProj.up,down: sharedProj.down,y: h1Buf,- scratchAct: denseScratchA)+ scratchGate: denseScratchGate,+ scratchUp: denseScratchUp,+ scratchAct: denseScratchAct)}let gSharedNorm: (MTLCommandBuffer) -> Void = { [self] cb inrms.encodeBF16W(commandBuffer: cb, x: h1Buf,@@ -1893,7 +1740,6 @@ public final class RealForwardRunner: ChunkedPrefillRunner, ContextWindowReporti}kv?.advance()- turboQuantKV?.advance()}private func runSync(_ body: (MTLCommandBuffer) -> Void) {diff --git a/Sources/TurboFieldfare/Runtime/KVCache/KVCacheManager.swift b/Sources/TurboFieldfare/Runtime/KVCache/KVCacheManager.swiftindex 650b7daa..91336587 100644--- a/Sources/TurboFieldfare/Runtime/KVCache/KVCacheManager.swift+++ b/Sources/TurboFieldfare/Runtime/KVCache/KVCacheManager.swift@@ -3,13 +3,24 @@ import Darwinimport Metal/// Which attention variant a layer runs. Gemma 4 interleaves 25 sliding-window-/// layers with 5 full-attention layers. Sourced from-/// `ArchConfig.fullAttentionLayerMask`.-enum LayerKind: Sendable { case swa, full }--enum KVCacheStorageMode: Sendable, Equatable {- case fp16- case turboQuant(TurboQuantKVMode)+/// layers with 5 full-attention layers (the latter carry the K=V shared-tensor+/// quirk). Sourced from `ArchConfig.fullAttentionLayerMask`.+public enum LayerKind: Sendable { case swa, full }++/// A read view the attention kernels bind. `offset` stays 0; ring-enabled SWA+/// layers expose the physical start slot for diagnostics while kernels map+/// logical positions with the supplied ring capacity.+public struct KVView: @unchecked Sendable {+ public let buffer: MTLBuffer+ /// Byte offset of logical position 0. Always 0 under linear storage.+ public let offset: Int+ /// Bytes per token (numKVHeads * headDim * sizeof(FP16)).+ public let stride: Int+ /// Number of valid positions written so far (== `position`). Attention reads+ /// `[0, validTokenCount]` (inclusive of the just-written token).+ public let validTokenCount: Int+ /// Ring start slot. 0 under linear storage; the hook for the wrap-aware path.+ public let startSlot: Int}/// Per-layer FP16 K/V storage for the decode loop.@@ -19,9 +30,14 @@ enum KVCacheStorageMode: Sendable, Equatable {/// `maxContext`; FP16 ring storage caps SWA layers to their physical capacity/// while full-attention layers remain linear.///-/// Full-attention layers share the raw `k_proj` output. K then runs scaled-/// per-head normalization plus RoPE, while V runs no-scale normalization and-/// skips RoPE. The cache buffers must therefore remain separate.+/// Gemma 4 full-attention layers carry the `attention_k_eq_v` quirk: K and V+/// share the `k_proj` weight, so a single 4-bit dequant + GEMV produces the+/// raw projection. But after that the K-slot runs `k_norm` (per-head, with+/// scale) + RoPE while the V-slot runs `v_norm` (per-head, no scale) and+/// skips RoPE — they diverge before entering attention. So the cache buffers+/// must be separate; aliasing them would smash the V values with K's normed,+/// rotated bytes (gemma4-block.md §2.2). We always allocate K and V slots,+/// independent of `attentionKEqV`.////// The K/V projection GEMV writes straight into the slot returned by/// `kSlot`/`vSlot` (no separate `kv_write` kernel); the runner then norms +@@ -31,42 +47,33 @@ enum KVCacheStorageMode: Sendable, Equatable {/// 8 GB rule: storage is bounded by per-layer physical capacity, allocated/// once. `reset()` returns physical pages to the OS via `MADV_DONTNEED` so a/// finished generation does not keep its KV resident into the next turn.-final class KVCacheManager {- let config: ArchConfig- let maxContext: Int- let storageMode: KVCacheStorageMode- let fp16RingEnabled: Bool+public final class KVCacheManager {+ public let config: ArchConfig+ public let maxContext: Int+ public let fp16RingEnabled: Boolprivate let kBuffers: [MTLBuffer]private let vBuffers: [MTLBuffer]- private let quantizedKBuffers: [MTLBuffer]- private let quantizedVBuffers: [MTLBuffer]- private let turboQuantLayouts: [TurboQuantKVLayerLayout]private let strides: [Int] // bytes per token, per layerprivate let kinds: [LayerKind]private let capacityTokens: [Int]- private(set) var position: Int = 0+ public private(set) var position: Int = 0private static let fp16Size = 2- init(device: MTLDevice,+ public init(device: MTLDevice,config: ArchConfig,maxContext: Int,- storageMode: KVCacheStorageMode = .fp16,fp16RingEnabled: Bool = false,slidingWindow: Int? = nil,maxPrefillChunkTokens: Int = 128,fp16RingCapacityOverride: Int? = nil) throws {precondition(maxContext > 0, "maxContext must be positive")precondition(maxPrefillChunkTokens > 0, "maxPrefillChunkTokens must be positive")- if case .turboQuant(.disabled) = storageMode {- preconditionFailure("disabled TurboQuant mode cannot be used as a storage mode")- }self.config = configself.maxContext = maxContext- self.storageMode = storageMode- let ringEnabled = storageMode == .fp16 && fp16RingEnabled+ let ringEnabled = fp16RingEnabledself.fp16RingEnabled = ringEnabledlet swaStride = config.numKVHeads * config.headDim * Self.fp16Size@@ -77,17 +84,11 @@ final class KVCacheManager {var ks: [MTLBuffer] = []var vs: [MTLBuffer] = []- var qks: [MTLBuffer] = []- var qvs: [MTLBuffer] = []- var qls: [TurboQuantKVLayerLayout] = []var st: [Int] = []var kd: [LayerKind] = []var caps: [Int] = []ks.reserveCapacity(config.numLayers)vs.reserveCapacity(config.numLayers)- qks.reserveCapacity(config.numLayers)- qvs.reserveCapacity(config.numLayers)- qls.reserveCapacity(config.numLayers)st.reserveCapacity(config.numLayers)kd.reserveCapacity(config.numLayers)caps.reserveCapacity(config.numLayers)@@ -96,42 +97,19 @@ final class KVCacheManager {let isFull = config.fullAttentionLayerMask[layer] != 0let stride = isFull ? fullStride : swaStridelet capacity = ringEnabled && !isFull ? swaCapacity : maxContext- switch storageMode {- case .fp16:- let length = capacity * stride-- guard let kBuf = device.makeBuffer(length: length, options: .storageModeShared) else {- throw ModelError.residentBufferWrapFailed- }- kBuf.label = "kv.K.layer\(layer)"- ks.append(kBuf)-- guard let vBuf = device.makeBuffer(length: length, options: .storageModeShared) else {- throw ModelError.residentBufferWrapFailed- }- vBuf.label = "kv.V.layer\(layer)"- vs.append(vBuf)-- case .turboQuant(let mode):- let layout = TurboQuantKVLayout.layer(mode: mode,- config: config,- layer: layer,- capacity: maxContext)- guard let kBuf = device.makeBuffer(length: maxContext * layout.key.bytesPerToken,- options: .storageModeShared) else {- throw ModelError.residentBufferWrapFailed- }- kBuf.label = "kv.tq.K.layer\(layer)"- qks.append(kBuf)-- guard let vBuf = device.makeBuffer(length: maxContext * layout.value.bytesPerToken,- options: .storageModeShared) else {- throw ModelError.residentBufferWrapFailed- }- vBuf.label = "kv.tq.V.layer\(layer)"- qvs.append(vBuf)- qls.append(layout)+ let length = capacity * stride++ guard let kBuf = device.makeBuffer(length: length, options: .storageModeShared) else {+ throw ModelError.residentBufferWrapFailed}+ kBuf.label = "kv.K.layer\(layer)"+ ks.append(kBuf)++ guard let vBuf = device.makeBuffer(length: length, options: .storageModeShared) else {+ throw ModelError.residentBufferWrapFailed+ }+ vBuf.label = "kv.V.layer\(layer)"+ vs.append(vBuf)st.append(stride)kd.append(isFull ? .full : .swa)@@ -140,99 +118,91 @@ final class KVCacheManager {self.kBuffers = ksself.vBuffers = vs- self.quantizedKBuffers = qks- self.quantizedVBuffers = qvs- self.turboQuantLayouts = qlsself.strides = stself.kinds = kdself.capacityTokens = caps}+ public func layerKind(_ layer: Int) -> LayerKind { kinds[layer] }++ /// Bytes per token for `layer` (K and V share the same stride).+ public func stride(layer: Int) -> Int { strides[layer] }+/// Physical token capacity for `layer`. Ring-enabled SWA layers can be/// smaller than `maxContext`; full layers and ring-off storage stay linear.- func capacity(layer: Int) -> Int { capacityTokens[layer] }+ public func capacity(layer: Int) -> Int { capacityTokens[layer] }- func ringCapacity(layer: Int) -> Int {- guard storageMode == .fp16, fp16RingEnabled, kinds[layer] == .swa else { return 0 }+ public func ringCapacity(layer: Int) -> Int {+ guard fp16RingEnabled, kinds[layer] == .swa else { return 0 }return capacityTokens[layer]}- func turboQuantLayout(layer: Int) -> TurboQuantKVLayerLayout? {- guard case .turboQuant = storageMode else { return nil }- return turboQuantLayouts[layer]+ /// Total bytes of the K buffer for `layer`.+ public func bufferLength(layer: Int) -> Int {+ return capacityTokens[layer] * strides[layer]}/// Write target for this layer's K projection at `position`.- func kSlot(layer: Int, position: Int) -> (buffer: MTLBuffer, offset: Int) {- precondition(storageMode == .fp16, "FP16 K slots are unavailable for TurboQuant storage")+ public func kSlot(layer: Int, position: Int) -> (buffer: MTLBuffer, offset: Int) {validateRange(start: position, count: 1)return (kBuffers[layer], physicalSlot(layer: layer, position: position) * strides[layer])}- /// Write target for this layer's V projection at `position`. It is distinct- /// from `kSlot` because full layers normalize K and V differently and apply- /// RoPE only to K.- func vSlot(layer: Int, position: Int) -> (buffer: MTLBuffer, offset: Int) {- precondition(storageMode == .fp16, "FP16 V slots are unavailable for TurboQuant storage")+ /// Write target for this layer's V projection at `position`. Always+ /// distinct from `kSlot` — full layers no longer alias K and V (Gemma 4+ /// applies different per-head norms + RoPE to K vs V; gemma4-block.md §2.2).+ public func vSlot(layer: Int, position: Int) -> (buffer: MTLBuffer, offset: Int) {validateRange(start: position, count: 1)return (vBuffers[layer], physicalSlot(layer: layer, position: position) * strides[layer])}- func kRange(layer: Int, start: Int, count: Int) -> (buffer: MTLBuffer, offset: Int, stride: Int) {- precondition(storageMode == .fp16, "FP16 K ranges are unavailable for TurboQuant storage")+ public func kRange(layer: Int, start: Int, count: Int) -> (buffer: MTLBuffer, offset: Int, stride: Int) {validateRange(start: start, count: count)validateContiguousPhysicalRange(layer: layer, start: start, count: count)return (kBuffers[layer], physicalSlot(layer: layer, position: start) * strides[layer], strides[layer])}- func vRange(layer: Int, start: Int, count: Int) -> (buffer: MTLBuffer, offset: Int, stride: Int) {- precondition(storageMode == .fp16, "FP16 V ranges are unavailable for TurboQuant storage")+ public func vRange(layer: Int, start: Int, count: Int) -> (buffer: MTLBuffer, offset: Int, stride: Int) {validateRange(start: start, count: count)validateContiguousPhysicalRange(layer: layer, start: start, count: count)return (vBuffers[layer], physicalSlot(layer: layer, position: start) * strides[layer], strides[layer])}- func keyBuffer(layer: Int, validTokenCount: Int) -> MTLBuffer {- precondition(storageMode == .fp16, "FP16 K buffers are unavailable for TurboQuant storage")- validateValidTokenCount(validTokenCount)- return kBuffers[layer]+ public func keyView(layer: Int) -> KVView {+ keyView(layer: layer, validTokenCount: position)}- func valueBuffer(layer: Int, validTokenCount: Int) -> MTLBuffer {- precondition(storageMode == .fp16, "FP16 V buffers are unavailable for TurboQuant storage")+ public func keyView(layer: Int, validTokenCount: Int) -> KVView {validateValidTokenCount(validTokenCount)- return vBuffers[layer]+ return KVView(buffer: kBuffers[layer], offset: 0, stride: strides[layer],+ validTokenCount: validTokenCount, startSlot: ringStartSlot(layer: layer,+ validTokenCount: validTokenCount))}- func quantizedKeySlot(layer: Int, position: Int) -> (buffer: MTLBuffer, offset: Int) {- let layout = requireTurboQuantLayout(layer: layer)- validateRange(start: position, count: 1)- return (quantizedKBuffers[layer], position * layout.key.bytesPerToken)+ public func valueView(layer: Int) -> KVView {+ valueView(layer: layer, validTokenCount: position)}- func quantizedValueSlot(layer: Int, position: Int) -> (buffer: MTLBuffer, offset: Int) {- let layout = requireTurboQuantLayout(layer: layer)- validateRange(start: position, count: 1)- return (quantizedVBuffers[layer], position * layout.value.bytesPerToken)+ func keyBuffer(layer: Int, validTokenCount: Int) -> MTLBuffer {+ keyView(layer: layer, validTokenCount: validTokenCount).buffer}- func quantizedKeyBuffer(layer: Int, validTokenCount: Int) -> MTLBuffer {- _ = requireTurboQuantLayout(layer: layer)- validateValidTokenCount(validTokenCount)- return quantizedKBuffers[layer]+ func valueBuffer(layer: Int, validTokenCount: Int) -> MTLBuffer {+ valueView(layer: layer, validTokenCount: validTokenCount).buffer}- func quantizedValueBuffer(layer: Int, validTokenCount: Int) -> MTLBuffer {- _ = requireTurboQuantLayout(layer: layer)+ public func valueView(layer: Int, validTokenCount: Int) -> KVView {validateValidTokenCount(validTokenCount)- return quantizedVBuffers[layer]+ return KVView(buffer: vBuffers[layer], offset: 0, stride: strides[layer],+ validTokenCount: validTokenCount, startSlot: ringStartSlot(layer: layer,+ validTokenCount: validTokenCount))}/// Advance the position cursor once the current token's K/V are written/// across all layers.- func advance() { advance(by: 1) }+ public func advance() { advance(by: 1) }- func advance(by count: Int) {+ public func advance(by count: Int) {precondition(count >= 0, "advance count must be non-negative")precondition(position + count <= maxContext, "advance would exceed maxContext")position += count@@ -243,29 +213,16 @@ final class KVCacheManager {/// No buffer zeroing — the attention kernels read only `[0, validTokenCount]`,/// and `validTokenCount` is now 0. `MADV_DONTNEED` on the page-aligned span/// releases resident memory between turns; pages fault back in on next write.- func reset() {+ public func reset() {position = 0let pageSize = Int(getpagesize())var advised = Set<ObjectIdentifier>()for layer in 0..<config.numLayers {- switch storageMode {- case .fp16:- advise(kBuffers[layer], pageSize: pageSize, seen: &advised)- advise(vBuffers[layer], pageSize: pageSize, seen: &advised)- case .turboQuant:- advise(quantizedKBuffers[layer], pageSize: pageSize, seen: &advised)- advise(quantizedVBuffers[layer], pageSize: pageSize, seen: &advised)- }+ advise(kBuffers[layer], pageSize: pageSize, seen: &advised)+ advise(vBuffers[layer], pageSize: pageSize, seen: &advised)}}- private func requireTurboQuantLayout(layer: Int) -> TurboQuantKVLayerLayout {- guard case .turboQuant = storageMode else {- preconditionFailure("TurboQuant KV layout is unavailable for FP16 storage")- }- return turboQuantLayouts[layer]- }-private func validateRange(start: Int, count: Int) {precondition(count >= 0, "count must be non-negative")precondition(start >= 0, "start must be non-negative")@@ -283,8 +240,15 @@ final class KVCacheManager {position % capacityTokens[layer]}+ private func ringStartSlot(layer: Int, validTokenCount: Int) -> Int {+ guard fp16RingEnabled, kinds[layer] == .swa else { return 0 }+ let capacity = capacityTokens[layer]+ guard validTokenCount > capacity else { return 0 }+ return validTokenCount % capacity+ }+private func validateContiguousPhysicalRange(layer: Int, start: Int, count: Int) {- guard count > 0, storageMode == .fp16, fp16RingEnabled, kinds[layer] == .swa else { return }+ guard count > 0, fp16RingEnabled, kinds[layer] == .swa else { return }let capacity = capacityTokens[layer]let physicalStart = start % capacityprecondition(physicalStart + count <= capacity,diff --git a/Sources/TurboFieldfare/Runtime/KVCache/TurboQuantKVLayout.swift b/Sources/TurboFieldfare/Runtime/KVCache/TurboQuantKVLayout.swiftdeleted file mode 100644index 6f5cd7bc..00000000--- a/Sources/TurboFieldfare/Runtime/KVCache/TurboQuantKVLayout.swift+++ /dev/null@@ -1,67 +0,0 @@-import Foundation--enum TurboQuantKVMode: Sendable, Equatable {- case disabled- case k4v4NormCorrected-}--struct TurboQuantKVRoleLayout: Sendable, Equatable {- let packedOffsetPerHead: Int- let scaleOffsetPerHead: Int- let bytesPerHead: Int- let bytesPerToken: Int--}--struct TurboQuantKVLayerLayout: Sendable, Equatable {- let key: TurboQuantKVRoleLayout- let value: TurboQuantKVRoleLayout--}--enum TurboQuantKVLayout {- static let fp16ScaleBytes = 2-- static func layer(mode: TurboQuantKVMode,- config: ArchConfig,- layer: Int,- capacity: Int) -> TurboQuantKVLayerLayout {- let isFull = config.fullAttentionLayerMask[layer] != 0- let headDim = isFull ? config.fullHeadDim : config.headDim- let numKVHeads = isFull ? config.numFullKVHeads : config.numKVHeads- return self.layer(mode: mode,- headDim: headDim,- numKVHeads: numKVHeads,- capacity: capacity)- }-- static func layer(mode: TurboQuantKVMode,- headDim: Int,- numKVHeads: Int,- capacity: Int) -> TurboQuantKVLayerLayout {- precondition(mode != .disabled, "disabled mode has no TurboQuant layout")- precondition(headDim > 0 && headDim % 8 == 0,- "headDim must be positive and byte-packable")- precondition(numKVHeads > 0)- precondition(capacity > 0)- let roleLayout = role(mode: mode,- headDim: headDim,- numKVHeads: numKVHeads)- return TurboQuantKVLayerLayout(key: roleLayout,- value: roleLayout)- }-- static func role(mode: TurboQuantKVMode,- headDim: Int,- numKVHeads: Int) -> TurboQuantKVRoleLayout {- precondition(mode == .k4v4NormCorrected)- let packed = (headDim * 4 + 7) / 8- let packedOffset = 0- let scaleOffset = packedOffset + packed- let perHead = scaleOffset + fp16ScaleBytes- return TurboQuantKVRoleLayout(packedOffsetPerHead: packedOffset,- scaleOffsetPerHead: scaleOffset,- bytesPerHead: perHead,- bytesPerToken: perHead * numKVHeads)- }-}diff --git a/Sources/TurboFieldfare/Runtime/Prefill/PrefillChunkScratch.swift b/Sources/TurboFieldfare/Runtime/Prefill/PrefillChunkScratch.swiftindex e8825142..e154e8b0 100644--- a/Sources/TurboFieldfare/Runtime/Prefill/PrefillChunkScratch.swift+++ b/Sources/TurboFieldfare/Runtime/Prefill/PrefillChunkScratch.swift@@ -43,9 +43,7 @@ struct PrefillChunkScratchLayout: Sendable, Equatable {var routePartialElements: Int { chunkTokens * topK * hiddenSize }var routeIDElements: Int { chunkTokens * topK }var routeWeightElements: Int { routeIDElements }- var sharedExpertActScratchElements: Int {- sharedIntermediate- }+ var sharedExpertScratchElements: Int { sharedIntermediate }var routedGateUpActElements: Int { 3 * routedPairMicrobatchRows * routedIntermediate }var routedDownOutputElements: Int { routedPairMicrobatchRows * hiddenSize }@@ -62,7 +60,7 @@ struct PrefillChunkScratchLayout: Sendable, Equatable {+ h1Elements+ h2Elements+ routePartialElements- + sharedExpertActScratchElements+ + 3 * sharedExpertScratchElements+ routedGateUpActElements+ routedDownOutputElementsreturn fp16Elements * MemoryLayout<Float16>.stride@@ -94,6 +92,8 @@ struct PrefillChunkScratchBuffers {let routePartials: MTLBufferlet routeIDs: MTLBufferlet routeWeights: MTLBuffer+ let sharedGateScratch: MTLBuffer+ let sharedUpScratch: MTLBufferlet sharedActScratch: MTLBufferlet routedGateUpActScratch: MTLBufferlet routedDownScratch: MTLBuffer@@ -138,7 +138,11 @@ struct PrefillChunkScratchBuffers {label: "prefill.routeIDs"),routeWeights: try sharedBuffer(layout.routeWeightElements * MemoryLayout<Float16>.stride,label: "prefill.routeWeights"),- sharedActScratch: try privateBuffer(layout.sharedExpertActScratchElements,+ sharedGateScratch: try privateBuffer(layout.sharedExpertScratchElements,+ label: "prefill.sharedGateScratch"),+ sharedUpScratch: try privateBuffer(layout.sharedExpertScratchElements,+ label: "prefill.sharedUpScratch"),+ sharedActScratch: try privateBuffer(layout.sharedExpertScratchElements,label: "prefill.sharedActScratch"),routedGateUpActScratch: try privateBuffer(layout.routedGateUpActElements,label: "prefill.routedGateUpActScratch"),diff --git a/Sources/TurboFieldfare/Runtime/Prefill/PrefillRuntimeConfig.swift b/Sources/TurboFieldfare/Runtime/Prefill/PrefillRuntimeConfig.swiftindex f82c4f22..b72fa7be 100644--- a/Sources/TurboFieldfare/Runtime/Prefill/PrefillRuntimeConfig.swift+++ b/Sources/TurboFieldfare/Runtime/Prefill/PrefillRuntimeConfig.swift@@ -118,7 +118,6 @@ enum PrefillChunkPlanner {public enum PrefillKVStorageMode: String, Sendable, Equatable {case fp16- case packedOnly = "packed-only"}public enum PrefillExecutedMode: String, Sendable, Equatable {diff --git a/Sources/TurboFieldfare/Tokenization/Tokenizer.swift b/Sources/TurboFieldfare/Tokenization/Tokenizer.swiftindex ac030cbd..2efdcda9 100644--- a/Sources/TurboFieldfare/Tokenization/Tokenizer.swift+++ b/Sources/TurboFieldfare/Tokenization/Tokenizer.swift@@ -1,25 +1,38 @@import Foundationimport Tokenizers-enum GFTokenizerError: Error, CustomStringConvertible {+public enum GFTokenizerError: Error, CustomStringConvertible {case missingSpecialToken(String)+ case invalidChatTemplate(String)public var description: String {switch self {case .missingSpecialToken(let t): return "tokenizer missing required special token: \(t)"+ case .invalidChatTemplate(let detail): return "invalid chat messages: \(detail)"}}}-/// Gemma 4 tokenizer wrapper. It prefers the tokenizer included in a completed-/// `.gturbo` directory and adapts token IDs to the Int32 runtime boundary.+/// Gemma 4 tokenizer wrapper.+///+/// Prefers tokenizer sidecars in a completed `.gturbo/tokenizer/` directory,+/// then falls back to the IT variant's Hugging Face Hub tokenizer cache. Exposes+/// typed accessors for the IDs the generator actually needs (BOS / EOS / pad /+/// end-of-turn) and adapts encode/decode to Int32 to match the buffer types+/// kernels consume.+///+/// TurboFieldfare owns the minimal chat framing because the upstream+/// `tokenizer_config.json` has no `chat_template`. Literal control-token text in+/// user content is accepted as a trusted-input research-runtime limitation.public struct GFTokenizer: @unchecked Sendable {public static let modelID = "google/gemma-4-26B-A4B-it"+ public static let chatTemplateIdentity = "gemma4-it-text-no-tools-v1"public let bosID: Int32public let eosID: Int32public let padID: Int32public let endOfTurnID: Int32+ public let toolResponseID: Int32public let stopTokenIDs: Set<Int32>public let vocabSize: Int@@ -34,14 +47,16 @@ public struct GFTokenizer: @unchecked Sendable {try await GFTokenizerLoadCoordinator.shared.load(.local(folder.standardizedFileURL.path))}- public static func load(forModelDirectory modelDirectory: URL) async throws -> GFTokenizer {- if let folder = tokenizerFolder(forModelDirectory: modelDirectory) {+ public static func load(forModelDirectory modelDirectory: URL,+ environment: [String: String] = ProcessInfo.processInfo.environment) async throws -> GFTokenizer {+ if let folder = tokenizerFolder(forModelDirectory: modelDirectory, environment: environment) {return try await load(from: folder)}return try await load()}public static func tokenizerFolder(forModelDirectory modelDirectory: URL,+ environment: [String: String] = ProcessInfo.processInfo.environment,fileManager: FileManager = .default) -> URL? {let sidecar = modelDirectory.standardizedFileURL@@ -50,7 +65,11 @@ public struct GFTokenizer: @unchecked Sendable {return sidecar}- return nil+ guard let override = environment["TURBO_FIELDFARE_TOKENIZER_DIR"], !override.isEmpty else {+ return nil+ }+ let overrideURL = URL(fileURLWithPath: override).standardizedFileURL+ return hasTokenizerJSON(in: overrideURL, fileManager: fileManager) ? overrideURL : nil}static func loadUncached(pretrained modelID: String = Self.modelID) async throws -> GFTokenizer {@@ -82,12 +101,16 @@ public struct GFTokenizer: @unchecked Sendable {guard let eot = tokenizer.convertTokenToId("<turn|>") else {throw GFTokenizerError.missingSpecialToken("<turn|>")}+ guard let toolResponse = tokenizer.convertTokenToId("<|tool_response>") else {+ throw GFTokenizerError.missingSpecialToken("<|tool_response>")+ }self.bosID = Int32(bos)self.eosID = Int32(eos)self.padID = Int32(pad)self.endOfTurnID = Int32(eot)- self.stopTokenIDs = [self.eosID, self.endOfTurnID]+ self.toolResponseID = Int32(toolResponse)+ self.stopTokenIDs = [self.eosID, self.endOfTurnID, self.toolResponseID]self.vocabSize = 262_144}@@ -107,6 +130,38 @@ public struct GFTokenizer: @unchecked Sendable {tokenizer.decode(tokens: ids.map(Int.init), skipSpecialTokens: skipSpecialTokens)}+ // MARK: - Chat template++ public enum Role: String, Sendable { case system, user, assistant }+ public struct Message: Sendable {+ public let role: Role+ public let content: String+ public init(role: Role, content: String) {+ self.role = role+ self.content = content+ }+ }++ /// Text-only, no-tool rendering of the pinned IT checkpoint's bundled+ /// `chat_template.jinja`, with thinking disabled. Keeping this narrow makes+ /// unsupported tool/media behavior explicit instead of approximating it.+ private static let turnOpen = "<|turn>"+ private static let turnClose = "<turn|>"+ private static let bosMark = "<bos>"++ public func applyChatTemplate(_ messages: [Message]) throws -> String {+ var s = Self.bosMark+ for (index, message) in messages.enumerated() {+ let content = message.content.trimmingCharacters(in: .whitespacesAndNewlines)+ if message.role == .system && index != 0 {+ throw GFTokenizerError.invalidChatTemplate("system message must be first")+ }+ let role = message.role == .assistant ? "model" : message.role.rawValue+ s += Self.turnOpen + role + "\n" + content + Self.turnClose + "\n"+ }+ s += Self.turnOpen + "model\n<|channel>thought\n<channel|>"+ return s+ }}private enum GFTokenizerLoadSource: Hashable {diff --git a/Sources/TurboFieldfareApp/Core/Configuration/AppContextLengthOption.swift b/Sources/TurboFieldfareApp/Core/Configuration/AppContextLengthOption.swiftnew file mode 100644index 00000000..f5afb237--- /dev/null+++ b/Sources/TurboFieldfareApp/Core/Configuration/AppContextLengthOption.swift@@ -0,0 +1,45 @@+import TurboFieldfare++public enum AppContextLengthOption: Int, CaseIterable, Identifiable, Sendable {+ case fourK = 4_096+ case eightK = 8_192+ case sixteenK = 16_384+ case thirtyTwoK = 32_768+ case sixtyFourK = 65_536++ public var id: Int { rawValue }+ public var tokens: Int { rawValue }++ public var shortLabel: String {+ "\(tokens / 1_024)K"+ }++ public var fp16KVBytes: UInt64 {+ let architecture = ArchConfig.gemma4_26B_A4B+ let fullLayers = architecture.fullAttentionLayerMask.reduce(0) {+ $0 + ($1 == 0 ? 0 : 1)+ }+ let slidingLayers = architecture.numLayers - fullLayers+ let fp16Bytes = 2+ let keyAndValue = 2+ let slidingRows = min(+ tokens,+ architecture.slidingWindow + PrefillRuntimeConfig.defaultChunked.chunkTokens)+ let slidingBytesPerRow = architecture.numKVHeads+ * architecture.headDim * keyAndValue * fp16Bytes+ let fullBytesPerRow = architecture.numFullKVHeads+ * architecture.fullHeadDim * keyAndValue * fp16Bytes+ return UInt64(slidingLayers * slidingRows * slidingBytesPerRow)+ + UInt64(fullLayers * tokens * fullBytesPerRow)+ }++ 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"+ }+ }+}diff --git a/Sources/TurboFieldfareApp/Core/Configuration/AppPromptPreset.swift b/Sources/TurboFieldfareApp/Core/Configuration/AppPromptPreset.swiftindex 8b62aa5a..459e45e4 100644--- a/Sources/TurboFieldfareApp/Core/Configuration/AppPromptPreset.swift+++ b/Sources/TurboFieldfareApp/Core/Configuration/AppPromptPreset.swift@@ -1,81 +1,30 @@-public struct AppPromptPreset: Identifiable, Sendable, Equatable {+import Foundation++public struct AppPromptPreset: Identifiable, Decodable, Sendable, Equatable {public let id: Stringpublic let title: String- public let prefix: String- public let isPrimary: Bool+ public let prompt: String- public init(id: String, title: String, prefix: String, isPrimary: Bool) {+ public init(id: String, title: String, prompt: String) {self.id = idself.title = title- self.prefix = prefix- self.isPrimary = isPrimary+ self.prompt = prompt}- public static let all: [AppPromptPreset] = [- AppPromptPreset(- id: "paris",- title: "Paris",- prefix: "Paris is the capital and largest city of France. Situated on the River Seine, the city is known for",- isPrimary: true),- AppPromptPreset(- id: "fibonacci",- title: "Python Fibonacci",- prefix: """- An iterative Python function can return the first n Fibonacci numbers without recursion. It returns an empty list when n is zero, uses O(n) time, and includes a small correctness check:-- ```python- def fibonacci(n: int) -> list[int]:- """,- isPrimary: true),- AppPromptPreset(- id: "fieldfare",- title: "Meet the fieldfare",- prefix: "The fieldfare (Turdus pilaris) is a grey-headed, chestnut-backed thrush that reaches Britain and Ireland from northern Europe each autumn. Its noisy winter flocks roam the countryside in search of berries, and",- isPrimary: true),- AppPromptPreset(- id: "cosine-similarity",- title: "Dot product and cosine similarity",- prefix: """- The unit vectors u = [1, 0] and v = [0, 1] are orthogonal. Their dot product is 0, both lengths are 1, and their cosine similarity is exactly 0. A compact check is:-- ```python- assert dot([1, 0], [0, 1]) == 0- assert cosine_similarity([1, 0], [0, 1]) ==- """,- isPrimary: false),- AppPromptPreset(- id: "recommendation-systems",- title: "How recommendations learn",- prefix: """- # How Collaborative Filtering Learns Film Recommendations-- A film-streaming service records a sparse user–item matrix: rows represent viewers, columns represent films, and observed entries represent ratings or interactions. Most entries are missing because each viewer has seen only a small fraction of the catalog. Matrix factorization learns a low-dimensional vector for every viewer and every film. Their dot product estimates a missing preference score, so films with the largest estimated scores can be ranked for that viewer.-- The explanation has exactly four sections: the sparse interaction matrix; latent viewer and film vectors; training and prediction; and limitations and evaluation. A missing interaction is unknown, not a negative rating. Training adjusts the vectors to reduce error on observed interactions with regularization. Evaluation uses held-out interactions and ranking measures. The limitations are cold start and popularity bias. The fourth section ends the article without a summary, repeated title, or repeated instructions.-- ## The sparse interaction matrix- """,- isPrimary: false),- AppPromptPreset(- id: "matrix-multiplication",- title: "Matrix multiplication",- prefix: """- # Matrix Multiplication: Why Rows Meet Columns-- For A = [[1, 2], [3, 4]] and B = [[5, 6], [7, 8]], the complete verified calculation is:-- C[1,1] = 1 x 5 + 2 x 7 = 19- C[1,2] = 1 x 6 + 2 x 8 = 22- C[2,1] = 3 x 5 + 4 x 7 = 43- C[2,2] = 3 x 6 + 4 x 8 = 50-- Thus C = AB = [[19, 22], [43, 50]]. The explanation below does not repeat or recompute those numeric equations. It has exactly three sections: why the inner dimensions match; how each output cell is a row-column dot product; and the general m x n by n x p rule. The final section states C[i,j] = sum over k of A[i,k]B[k,j] and then ends, without another example, code, references, or a summary.-- ## Why the inner dimensions match- """,- isPrimary: false),- ]-- public static var primary: [AppPromptPreset] { all.filter(\.isPrimary) }- public static var secondary: [AppPromptPreset] { all.filter { !$0.isPrimary } }+ public static let all: [AppPromptPreset] = loadBundledPrompts()+ public static var primary: [AppPromptPreset] { Array(all.prefix(3)) }+ public static var secondary: [AppPromptPreset] { Array(all.dropFirst(3)) }++ private static func loadBundledPrompts() -> [AppPromptPreset] {+ guard let url = Bundle.module.url(forResource: "app-prompts", withExtension: "json"),+ let data = try? Data(contentsOf: url),+ let prompts = try? JSONDecoder().decode([AppPromptPreset].self, from: data),+ prompts.count == 7,+ Set(prompts.map(\.id)).count == prompts.count,+ prompts.allSatisfy({ !$0.id.isEmpty && !$0.title.isEmpty && !$0.prompt.isEmpty })+ else {+ return []+ }+ return prompts+ }}diff --git a/Sources/TurboFieldfareApp/Core/Configuration/AppRuntimeOptions.swift b/Sources/TurboFieldfareApp/Core/Configuration/AppRuntimeOptions.swiftindex c1270095..5ff8e177 100644--- a/Sources/TurboFieldfareApp/Core/Configuration/AppRuntimeOptions.swift+++ b/Sources/TurboFieldfareApp/Core/Configuration/AppRuntimeOptions.swift@@ -57,7 +57,6 @@ public struct AppRuntimeOptions: Equatable, Sendable {public var expertCachePolicy: AppExpertCachePolicypublic var prefillEnabled: Boolpublic var prefillChunkTokens: Int- public var turboQuantKVEnabled: Boolpublic var rdadvisePolicy: AppRDAdvicePolicypublic var modelVerification: AppModelVerification@@ -65,14 +64,12 @@ public struct AppRuntimeOptions: Equatable, Sendable {expertCachePolicy: AppExpertCachePolicy = .lfu,prefillEnabled: Bool = true,prefillChunkTokens: Int = 128,- turboQuantKVEnabled: Bool = false,rdadvisePolicy: AppRDAdvicePolicy = .off,modelVerification: AppModelVerification = .fullSha256) {self.expertCacheSlots = expertCacheSlotsself.expertCachePolicy = expertCachePolicyself.prefillEnabled = prefillEnabledself.prefillChunkTokens = prefillChunkTokens- self.turboQuantKVEnabled = turboQuantKVEnabledself.rdadvisePolicy = rdadvisePolicyself.modelVerification = modelVerification}@@ -94,13 +91,18 @@ public struct AppRuntimeOptions: Equatable, Sendable {public var resultSummary: String {let prefill = prefillEnabled ? "prefill \(prefillChunkTokens)" : "prefill off"- let kv = turboQuantKVEnabled ? "K4/V4 KV" : "FP16 KV"let verification = modelVerification == .fullSha256 ? "full SHA-256" : "trusted receipt"- return "Cache \(expertCacheSlots) \(expertCachePolicy.label), \(prefill), \(kv), RDADVISE \(rdadvisePolicy.label.lowercased()), \(verification)"+ return "Cache \(expertCacheSlots) \(expertCachePolicy.label), \(prefill), FP16 KV, RDADVISE \(rdadvisePolicy.label.lowercased()), \(verification)"}public static func slotsLabel(for slots: Int) -> String {- slots > 16 ? "\(slots) +RAM" : "\(slots)"+ switch slots {+ case 8: "8, -0.8 GB"+ case 16: "16, Default"+ case 24: "24, +0.8 GB"+ case 32: "32, +1.61 GB"+ default: "\(slots)"+ }}public func resolvedRuntimeConfiguration(forceLogitsHead: Bool) throws -> RuntimeConfiguration {@@ -111,7 +113,6 @@ public struct AppRuntimeOptions: Equatable, Sendable {rdadvisePolicy: rdadvisePolicy.runtimeValue,prefillEnabled: prefillEnabled,prefillChunkTokens: prefillChunkTokens,- turboQuantKVEnabled: turboQuantKVEnabled,forceLogitsHead: forceLogitsHead)}}@@ -119,7 +120,10 @@ public struct AppRuntimeOptions: Equatable, Sendable {public struct AppLoadedRuntimeKey: Equatable, Sendable {public var modelDirectory: URLpublic var maxContextTokens: Int- public var runtimeOptions: AppRuntimeOptions+ public var expertCacheSlots: Int+ public var expertCachePolicy: AppExpertCachePolicy+ public var rdadvisePolicy: AppRDAdvicePolicy+ public var modelVerification: AppModelVerificationpublic var forceLogitsHead: Boolpublic init(modelDirectory: URL,@@ -128,7 +132,10 @@ public struct AppLoadedRuntimeKey: Equatable, Sendable {forceLogitsHead: Bool = false) {self.modelDirectory = modelDirectory.standardizedFileURLself.maxContextTokens = maxContextTokens- self.runtimeOptions = options+ self.expertCacheSlots = options.expertCacheSlots+ self.expertCachePolicy = options.expertCachePolicy+ self.rdadvisePolicy = options.rdadvisePolicy+ self.modelVerification = options.modelVerificationself.forceLogitsHead = forceLogitsHead}}diff --git a/Sources/TurboFieldfareApp/Core/Configuration/MacAppSettings.swift b/Sources/TurboFieldfareApp/Core/Configuration/MacAppSettings.swiftnew file mode 100644index 00000000..8df215cb--- /dev/null+++ b/Sources/TurboFieldfareApp/Core/Configuration/MacAppSettings.swift@@ -0,0 +1,69 @@+import Foundation++struct MacAppSettings: Codable, Equatable, Sendable {+ static let fileName = "mac-app-settings.json"+ static let currentVersion = 1++ var version: Int = currentVersion+ var contextTokens: Int = AppContextLengthOption.fourK.tokens+ var expertCacheSlots: Int = 16+ var temperature: Double = 0.2+ var topKEnabled: Bool = true+ var topK: Int = 64+ var topPEnabled: Bool = true+ var topP: Double = 0.95+ var prefillEnabled: Bool = true++ func isValid() -> Bool {+ version == Self.currentVersion+ && AppContextLengthOption.allCases.contains { $0.tokens == contextTokens }+ && AppRuntimeOptions.allowedSlotCounts.contains(expertCacheSlots)+ && temperature.isFinite && (0...2).contains(temperature)+ && (1...256).contains(topK)+ && topP.isFinite && (0.01...1).contains(topP)+ }+}++enum MacAppSettingsFileStore {+ static func fileURL(forModelDirectory modelDirectory: URL) -> URL {+ modelDirectory.standardizedFileURL+ .deletingLastPathComponent()+ .appendingPathComponent(MacAppSettings.fileName, isDirectory: false)+ }++ static func loadOrCreate(forModelDirectory modelDirectory: URL,+ fileManager: FileManager = .default) -> MacAppSettings {+ let fileURL = fileURL(forModelDirectory: modelDirectory)+ if fileManager.fileExists(atPath: fileURL.path) {+ do {+ let data = try Data(contentsOf: fileURL)+ let settings = try JSONDecoder().decode(MacAppSettings.self, from: data)+ guard settings.isValid() else { throw InvalidSettings() }+ return settings+ } catch {+ try? fileManager.removeItem(at: fileURL)+ }+ }++ let settings = MacAppSettings()+ try? save(settings, forModelDirectory: modelDirectory, fileManager: fileManager)+ return settings+ }++ static func save(_ settings: MacAppSettings,+ forModelDirectory modelDirectory: URL,+ fileManager: FileManager = .default) throws {+ guard settings.isValid() else { throw InvalidSettings() }+ let fileURL = fileURL(forModelDirectory: modelDirectory)+ try fileManager.createDirectory(+ at: fileURL.deletingLastPathComponent(),+ withIntermediateDirectories: true)+ let encoder = JSONEncoder()+ encoder.outputFormatting = [.prettyPrinted, .sortedKeys]+ var data = try encoder.encode(settings)+ data.append(0x0A)+ try data.write(to: fileURL, options: .atomic)+ }++ private struct InvalidSettings: Error {}+}diff --git a/Sources/TurboFieldfareApp/Core/Inference/AppGenerationRequest.swift b/Sources/TurboFieldfareApp/Core/Inference/AppGenerationRequest.swiftindex b56a4925..28f833ca 100644--- a/Sources/TurboFieldfareApp/Core/Inference/AppGenerationRequest.swift+++ b/Sources/TurboFieldfareApp/Core/Inference/AppGenerationRequest.swift@@ -13,9 +13,9 @@ public struct AppGenerationRequest: Equatable, Sendable {public init(modelDirectory: URL,prompt: String,- maxNewTokens: Int = 1_024,+ maxNewTokens: Int = 4_096,maxContextTokens: Int = 4096,- temperature: Float = 1.0,+ temperature: Float = 0.2,topK: Int? = 64,topP: Float? = 0.95,repetitionPenalty: Float = 1.0,diff --git a/Sources/TurboFieldfareApp/Core/Inference/DecodeServiceInferenceClient.swift b/Sources/TurboFieldfareApp/Core/Inference/DecodeServiceInferenceClient.swiftindex ed7f10f2..a4e9e286 100644--- a/Sources/TurboFieldfareApp/Core/Inference/DecodeServiceInferenceClient.swift+++ b/Sources/TurboFieldfareApp/Core/Inference/DecodeServiceInferenceClient.swift@@ -316,7 +316,6 @@ public final class DecodeServiceInferenceClient: AppModelLifecycleClient,expertCachePolicy: options.expertCachePolicy.rawValue,prefillEnabled: options.prefillEnabled,prefillChunkTokens: options.prefillChunkTokens,- turboQuantKVEnabled: options.turboQuantKVEnabled,rdadvisePolicy: options.rdadvisePolicy.rawValue,modelVerification: options.modelVerification.rawValue)}diff --git a/Sources/TurboFieldfareApp/Core/Inference/RealInferenceClient.swift b/Sources/TurboFieldfareApp/Core/Inference/RealInferenceClient.swiftindex 06d96df0..2b2cdeb9 100644--- a/Sources/TurboFieldfareApp/Core/Inference/RealInferenceClient.swift+++ b/Sources/TurboFieldfareApp/Core/Inference/RealInferenceClient.swift@@ -237,14 +237,21 @@ actor RealInferenceSession {!request.isPureGreedy}- static func generationConfig(for request: AppGenerationRequest) -> GenerationConfig {- GenerationConfig(maxNewTokens: request.maxNewTokens,+ static func generationConfig(for request: AppGenerationRequest,+ maxNewTokens: Int? = nil) -> GenerationConfig {+ GenerationConfig(maxNewTokens: maxNewTokens ?? request.maxNewTokens,temperature: request.temperature,topK: request.topK,topP: request.topP,repetitionPenalty: request.repetitionPenalty)}+ static func effectiveMaxNewTokens(requested: Int,+ promptTokenCount: Int,+ maxContext: Int) -> Int {+ min(requested, max(0, maxContext - promptTokenCount))+ }+func unload() {runner = nilscratch = nil@@ -260,13 +267,11 @@ actor RealInferenceSession {let progress = ProgressState()do {try request.validate()- let kvStorageMode: PrefillKVStorageMode =- request.runtimeOptions.turboQuantKVEnabled ? .packedOnly : .fp16let executedPrefillMode: PrefillExecutedMode =prefillConfig.mode == .chunked ? .chunked : .offlet prefillDiagnostics = PrefillExecutionDiagnostics(config: prefillConfig,executedMode: executedPrefillMode,- kvStorageMode: kvStorageMode)+ kvStorageMode: .fp16)let requestKey = SessionLoadKey(directory: request.modelDirectory.standardizedFileURL,maxContext: request.maxContextTokens,@@ -278,16 +283,24 @@ actor RealInferenceSession {throw AppInferenceError.modelLoadFailed("session lost its loaded state")}- let promptIds = tokenizer.encode(request.prompt, addBOS: true)+ let renderedPrompt = try tokenizer.applyChatTemplate([+ GFTokenizer.Message(role: .user, content: request.prompt)+ ])+ let promptIds = tokenizer.encode(renderedPrompt, addBOS: false)progress.promptTokenCount = promptIds.count- guard promptIds.count + request.maxNewTokens <= runner.maxContext else {+ guard promptIds.count < runner.maxContext else {throw AppInferenceError.contextOverflow(prompt: promptIds.count,maxNew: request.maxNewTokens,maxContext: runner.maxContext)}memorySampler.resetPeak()_ = memorySampler.sample()- let config = Self.generationConfig(for: request)+ let config = Self.generationConfig(+ for: request,+ maxNewTokens: Self.effectiveMaxNewTokens(+ requested: request.maxNewTokens,+ promptTokenCount: promptIds.count,+ maxContext: runner.maxContext))runner.reset()progress.prefillStart = Date()@@ -339,14 +352,12 @@ actor RealInferenceSession {prefill: PrefillExecutionDiagnostics(config: prefillConfig,executedMode: prefillConfig.mode == .chunked ? .chunked : .off,- kvStorageMode: request.runtimeOptions.turboQuantKVEnabled ? .packedOnly : .fp16))+ kvStorageMode: .fp16))continuation.yield(.cancelled(diagnostics))continuation.finish(throwing: AppInferenceError.cancelled)} catch let prefillError as PrefillError {- let kvStorageMode: PrefillKVStorageMode =- request.runtimeOptions.turboQuantKVEnabled ? .packedOnly : .fp16let diagnostics = Self.prefillFailureDiagnostics(config: prefillConfig,- kvStorageMode: kvStorageMode,+ kvStorageMode: .fp16,reason: prefillError.description)failGeneration(.unknown(prefillError.description),request: request,diff --git a/Sources/TurboFieldfareApp/Core/Installation/AppModelInstallDescriptor.swift b/Sources/TurboFieldfareApp/Core/Installation/AppModelInstallDescriptor.swiftindex 67ebe73b..7c5fe854 100644--- a/Sources/TurboFieldfareApp/Core/Installation/AppModelInstallDescriptor.swift+++ b/Sources/TurboFieldfareApp/Core/Installation/AppModelInstallDescriptor.swift@@ -5,6 +5,7 @@ public struct AppModelInstallDescriptor: Equatable, Sendable {public let displayName: Stringpublic let repoID: Stringpublic let revision: String+ public let sourceIndexSHA256: Stringpublic let approximateDownloadBytes: UInt64public let installedBytes: UInt64public let rangeStagingBytes: UInt64@@ -13,6 +14,7 @@ public struct AppModelInstallDescriptor: Equatable, Sendable {public init(displayName: String,repoID: String,revision: String,+ sourceIndexSHA256: String,approximateDownloadBytes: UInt64,installedBytes: UInt64,rangeStagingBytes: UInt64,@@ -20,6 +22,7 @@ public struct AppModelInstallDescriptor: Equatable, Sendable {self.displayName = displayNameself.repoID = repoIDself.revision = revision+ self.sourceIndexSHA256 = sourceIndexSHA256self.approximateDownloadBytes = approximateDownloadBytesself.installedBytes = installedBytesself.rangeStagingBytes = rangeStagingBytes@@ -31,20 +34,23 @@ public struct AppModelInstallDescriptor: Equatable, Sendable {}public static let `default` = AppModelInstallDescriptor(- displayName: SupportedModelSource.displayName,- repoID: SupportedModelSource.repoID,- revision: SupportedModelSource.revision,- approximateDownloadBytes: SupportedModelSource.approximateDownloadBytes,- installedBytes: SupportedModelSource.installedBytes,+ displayName: "Gemma 4 26B-A4B IT 4-bit",+ repoID: "mlx-community/gemma-4-26b-a4b-it-4bit",+ revision: "0d77464eeb233a2da68ebf9d7dc4edaac7db956d",+ sourceIndexSHA256: "bf198c9f5ea6462addca1966e5dd669c407537a876e82cf06db9084c5c850b13",+ approximateDownloadBytes: 14_620_479_420,+ installedBytes: 14_291_921_884,rangeStagingBytes: UInt64(RemoteChunkPolicy.defaultBytes),- reserveBytes: SupportedModelSource.reserveBytes)+ reserveBytes: 1_073_741_824)}public struct AppModelInstallRequirement: Equatable, Sendable {+ public let probePath: Stringpublic let requiredBytes: UInt64public let availableBytes: UInt64- public init(requiredBytes: UInt64, availableBytes: UInt64) {+ public init(probePath: String = "", requiredBytes: UInt64, availableBytes: UInt64) {+ self.probePath = probePathself.requiredBytes = requiredBytesself.availableBytes = availableBytes}diff --git a/Sources/TurboFieldfareApp/Core/Installation/AppModelInstallationProbe.swift b/Sources/TurboFieldfareApp/Core/Installation/AppModelInstallationProbe.swiftindex 7401d9d3..d7621841 100644--- a/Sources/TurboFieldfareApp/Core/Installation/AppModelInstallationProbe.swift+++ b/Sources/TurboFieldfareApp/Core/Installation/AppModelInstallationProbe.swift@@ -7,8 +7,11 @@ public enum AppModelInstallationStatus: Equatable, Sendable {case complete}-enum AppModelInstallationProbe {- static func status(at directory: URL) -> AppModelInstallationStatus {+public enum AppModelInstallationProbe {+ public static func status(+ at directory: URL,+ descriptor: AppModelInstallDescriptor = .default+ ) -> AppModelInstallationStatus {let directory = directory.standardizedFileURLlet manifestURL = directory.appendingPathComponent("manifest.json")guard FileManager.default.fileExists(atPath: manifestURL.path) else {@@ -16,7 +19,11 @@ enum AppModelInstallationProbe {}do {- _ = try ManifestReader.load(directoryURL: directory, expecting: .gemma4_26B_A4B)+ let manifest = try ManifestReader.load(directoryURL: directory, expecting: .gemma4_26B_A4B)+ let expectedSource = "sha256:" + descriptor.sourceIndexSHA256+ guard manifest.sourceSnapshotHash == expectedSource else {+ return .partial("installed checkpoint does not match \(descriptor.displayName)")+ }let layout = directory.appendingPathComponent("packed_experts/layout.json")guard FileManager.default.fileExists(atPath: layout.path) else {return .partial("packed_experts/layout.json is missing")diff --git a/Sources/TurboFieldfareApp/Core/Resources/app-prompts.json b/Sources/TurboFieldfareApp/Core/Resources/app-prompts.jsonnew file mode 100644index 00000000..c062f8de--- /dev/null+++ b/Sources/TurboFieldfareApp/Core/Resources/app-prompts.json@@ -0,0 +1,37 @@+[+ {+ "id": "paris",+ "title": "Paris",+ "prompt": "Plan a memorable first trip to Paris for a curious traveller. Give a compact three-day itinerary with morning, afternoon, and evening ideas; explain the easiest ways to get around; suggest the best seasons and two practical ways to control costs. Use clear headings, distinguish timeless advice from details that should be checked before travel, and keep the whole guide under 450 words."+ },+ {+ "id": "fibonacci",+ "title": "Write Fibonacci in Python",+ "prompt": "Write a complete, executable Python 3 example that defines `fibonacci(n: int) -> list[int]` and returns the first n Fibonacci numbers starting with 0, 1. Reject negative n with `ValueError`, return `[]` for n = 0, use iteration rather than recursion, and include exactly three assertions covering n = 0, n = 1, and n = 7. After the code block, use one plain-text sentence without LaTeX notation to state the time complexity and distinguish output space from extra working space. Do not use external packages."+ },+ {+ "id": "fieldfare",+ "title": "Meet the fieldfare",+ "prompt": "What makes the fieldfare's winter migration to Britain so remarkable? Explain where the birds come from, what they eat, and why they gather in flocks. Focus only on these facts, keep it accurate, and stay under 250 words."+ },+ {+ "id": "cosine-similarity",+ "title": "Why perpendicular means zero",+ "prompt": "Show why two perpendicular unit vectors have cosine similarity zero. Use u = [1, 0] and v = [0, 1], calculate the dot product and both lengths step by step, then give the geometric intuition, the general formula, and explain why a zero-length vector makes cosine similarity undefined. Keep it under 250 words. Use plain text only, without LaTeX notation."+ },+ {+ "id": "recommendation-systems",+ "title": "How recommendations learn",+ "prompt": "Explain how a film service can learn recommendations with collaborative filtering and matrix factorization. Use exactly four short titled sections: Interaction matrix; Latent factors; Training and ranking; Limits and evaluation. Make clear that a missing interaction is unknown rather than a negative rating, explain the user-vector/item-vector dot product and regularized learning from observed interactions, then cover held-out ranking evaluation, cold start, and popularity bias. Keep it accessible and technically correct."+ },+ {+ "id": "matrix-multiplication",+ "title": "Matrix multiplication",+ "prompt": "In plain text under 400 words, teach matrix multiplication using A = [[1, 2], [3, 4]] and B = [[5, 6], [7, 8]]. Show one line for each row-by-column calculation and verify AB = [[19, 22], [43, 50]]. Then explain why the inner dimensions must match and state that an m x n matrix times an n x p matrix produces an m x p matrix. End with the general formula `C[i,j] = sum from k=1 to n of A[i,k] * B[k,j]`. Use no LaTeX, no second example, and end immediately after explaining that formula."+ },+ {+ "id": "metal-matmul",+ "title": "Metal matrix multiplication",+ "prompt": "Write a compact Metal Shading Language kernel that multiplies row-major matrices A[M×K] and B[K×N] into C[M×N].\n\nUse one GPU thread per output element and a straightforward loop over K. Do not use tiling, threadgroup memory, helper functions, or optimizations. Pass M, K, and N in a constant parameter struct. Use thread_position_in_grid, check row and column bounds, and store A, B, and C in buffers 0, 1, and 2."+ }+]diff --git a/Sources/TurboFieldfareApp/Core/State/AppModel.swift b/Sources/TurboFieldfareApp/Core/State/AppModel.swiftindex 99068600..f3fbf4c0 100644--- a/Sources/TurboFieldfareApp/Core/State/AppModel.swift+++ b/Sources/TurboFieldfareApp/Core/State/AppModel.swift@@ -16,15 +16,13 @@ public final class AppModel {public var outputText: String = ""public var runState: RunState = .idlepublic var runtimeOptions = AppRuntimeOptions()- public var maxNewTokens: Int = 1_024+ public var maxNewTokensOverride: Int?public var maxContextTokens: Int = 4096- public var temperature: Double = 1.0+ public var temperature: Double = 0.2public var topKEnabled: Bool = truepublic var topK: Int = 64public var topPEnabled: Bool = truepublic var topP: Double = 0.95- public var repetitionPenaltyEnabled: Bool = false- public var repetitionPenalty: Double = 1.1public var diagnostics: AppDiagnostics?public var error: AppInferenceError?public var installState: AppModelInstallState = .idle@@ -54,17 +52,32 @@ public final class AppModel {private var activeRunRuntimeKey: AppLoadedRuntimeKey?private var hasHandledTerminalEvent = falseprivate let memorySampler: AppMemorySampler+ private let settingsPersistenceEnabled: Boolpublic init(modelDirectory: URL? = nil,client: any AppInferenceClient = RealInferenceClient(),installer: any AppModelInstallerClient = RepackModelInstallerClient(),- memorySampler: AppMemorySampler = AppMemorySampler()) {+ memorySampler: AppMemorySampler = AppMemorySampler(),+ settingsPersistenceEnabled: Bool = false) {let directory = (modelDirectory ?? AppModelLocation.defaultURL()).standardizedFileURL+ let settings = settingsPersistenceEnabled+ ? MacAppSettingsFileStore.loadOrCreate(forModelDirectory: directory)+ : MacAppSettings()self.modelPathText = directory.path+ self.runtimeOptions = AppRuntimeOptions(+ expertCacheSlots: settings.expertCacheSlots,+ prefillEnabled: settings.prefillEnabled)+ self.maxContextTokens = settings.contextTokens+ self.temperature = settings.temperature+ self.topKEnabled = settings.topKEnabled+ self.topK = settings.topK+ self.topPEnabled = settings.topPEnabled+ self.topP = settings.topPself.installationStatus = AppModelInstallationProbe.status(at: directory)self.client = clientself.installer = installerself.memorySampler = memorySampler+ self.settingsPersistenceEnabled = settingsPersistenceEnabledrefreshInstallReadiness()}@@ -131,6 +144,23 @@ public final class AppModel {return min(max(Double(done) / Double(total), 0), 1)}+ public var installPhaseLabel: String {+ switch installState {+ case .idle: return "Model required"+ case .checking: return "Checking installation"+ case .downloadingMetadata: return "Downloading metadata"+ case .planning: return "Planning installation"+ case .reservingOutput: return "Reserving storage"+ case .copyingPayload: return "Downloading model"+ case .hashingOutput(let file): return "Verifying \(file)"+ case .finalizing: return "Finalizing installation"+ case .cancelling: return "Cancelling"+ case .cancelled: return "Installation cancelled"+ case .installed: return "Model installed"+ case .failed: return "Installation failed"+ }+ }+public var canRun: Bool {!isRunning && isModelAvailable && !loadState.isLoading&& !hasStaleLoadedRuntime@@ -143,17 +173,21 @@ public final class AppModel {!outputPromptText.isEmpty || !outputText.isEmpty}- public var outputPlainText: String {- let completion = generationTranscriptMailbox?.completeText ?? outputText- switch (outputPromptText.isEmpty, completion.isEmpty) {+ public var outputResponsePlainText: String {+ generationTranscriptMailbox?.completeText ?? outputText+ }++ public var outputConversationPlainText: String {+ let response = outputResponsePlainText+ switch (outputPromptText.isEmpty, response.isEmpty) {case (true, true):return ""case (false, true):- return outputPromptText+ return "You:\n\(outputPromptText)"case (true, false):- return completion+ return "Answer:\n\(response)"case (false, false):- return outputPromptText + completion+ return "You:\n\(outputPromptText)\n\nAnswer:\n\(response)"}}@@ -197,7 +231,7 @@ public final class AppModel {}private var currentForceLogitsHead: Bool {- temperature != 0 || (repetitionPenaltyEnabled && repetitionPenalty != 1)+ temperature != 0}public func setModelURL(_ url: URL) {@@ -206,6 +240,8 @@ public final class AppModel {guard path != modelPathText else { return }modelPathText = path+ applyPersistedSettings(+ forModelDirectory: URL(fileURLWithPath: path, isDirectory: true))loadGeneration &+= 1loadTask?.cancel()loadTask = nil@@ -240,6 +276,17 @@ public final class AppModel {beginLoad()}+ public func perform(_ action: AppModelAction) {+ switch action {+ case .install: installModel()+ case .cancelInstall: cancelInstall()+ case .load, .retryLoad: loadModel()+ case .cancelLoad: cancelLoad()+ case .reload: reloadModel()+ case .unload: unloadModel()+ }+ }+public func reloadModel() {guard canReloadModel else { return }beginLoad()@@ -277,8 +324,12 @@ public final class AppModel {}}} catch is CancellationError {+ } catch let appError as AppInferenceError {+ await self?.applyLoadState(.failed(appError), generation: generation)} catch {- // The attempt-local state relay already surfaced the failure.+ await self?.applyLoadState(+ .failed(.modelLoadFailed("\(error)")),+ generation: generation)}await self?.clearLoadTask(generation: generation)}@@ -353,11 +404,26 @@ public final class AppModel {}public func refreshInstallReadiness() {+ refreshInstallReadiness(+ at: URL(fileURLWithPath: modelPathText, isDirectory: true).standardizedFileURL)+ }++ public func recheckModelAtCurrentLocation() {+ let directory = URL(fileURLWithPath: modelPathText, isDirectory: true)+ .standardizedFileURL+ modelPathText = directory.path+ refreshInstallReadiness(at: directory)+ }++ private func refreshInstallReadiness(at outputDirectory: URL) {+ installationStatus = AppModelInstallationProbe.status(+ at: outputDirectory,+ descriptor: installer.descriptor)guard !isModelInstalled else { return }installReadiness = .checkingdo {let requirement = try installer.checkInstallRequirement(- outputDirectory: URL(fileURLWithPath: modelPathText))+ outputDirectory: outputDirectory)installReadiness = requirement.canInstall? .ready(requirement): .insufficientSpace(requirement)@@ -385,7 +451,9 @@ public final class AppModel {installState = .finalizingcase .installed(let directory):let directory = directory.standardizedFileURL- installationStatus = AppModelInstallationProbe.status(at: directory)+ installationStatus = AppModelInstallationProbe.status(+ at: directory,+ descriptor: installer.descriptor)guard installationStatus == .complete else {finishInstallFailure(RepackError.configurationInvalid(detail: "completed install did not pass metadata validation"),@@ -417,13 +485,46 @@ public final class AppModel {refreshInstallReadiness()}+ private func applyPersistedSettings(forModelDirectory modelDirectory: URL) {+ guard settingsPersistenceEnabled else { return }+ let settings = MacAppSettingsFileStore.loadOrCreate(+ forModelDirectory: modelDirectory)+ runtimeOptions = AppRuntimeOptions(+ expertCacheSlots: settings.expertCacheSlots,+ prefillEnabled: settings.prefillEnabled)+ maxContextTokens = settings.contextTokens+ temperature = settings.temperature+ topKEnabled = settings.topKEnabled+ topK = settings.topK+ topPEnabled = settings.topPEnabled+ topP = settings.topP+ }++ private func persistSettings() {+ guard settingsPersistenceEnabled else { return }+ let settings = MacAppSettings(+ contextTokens: maxContextTokens,+ expertCacheSlots: runtimeOptions.expertCacheSlots,+ temperature: temperature,+ topKEnabled: topKEnabled,+ topK: topK,+ topPEnabled: topPEnabled,+ topP: topP,+ prefillEnabled: runtimeOptions.prefillEnabled)+ let modelDirectory = URL(fileURLWithPath: modelPathText, isDirectory: true)+ try? MacAppSettingsFileStore.save(+ settings,+ forModelDirectory: modelDirectory)+ }+private func finishInstallFailure(_ error: Error, generation: UInt64) {guard generation == installGeneration else { return }installTask = nilinstallState = .failed("\(error)")if let repackError = error as? RepackError,- case .diskSpaceInsufficient(_, let required, let available) = repackError {- let requirement = AppModelInstallRequirement(requiredBytes: required,+ case .diskSpaceInsufficient(let path, let required, let available) = repackError {+ let requirement = AppModelInstallRequirement(probePath: path,+ requiredBytes: required,availableBytes: available)installReadiness = .insufficientSpace(requirement)} else {@@ -448,11 +549,12 @@ public final class AppModel {loadedRuntimeKey = nilcase .loading, .cancelling, .unloading:break- case .ready:+ case .ready(_, let seconds):loadedRuntimeKey = pendingExplicitLoadRuntimeKey?? activeRunRuntimeKey?? currentRuntimeKeypendingExplicitLoadRuntimeKey = nil+ _ = secondscase .failed(let loadError):pendingExplicitLoadRuntimeKey = nilerror = loadError@@ -481,6 +583,7 @@ public final class AppModel {self.error = appErrorreturn}+ persistSettings()generationTranscriptMailbox?.reset()outputPromptText = request.prompt@@ -526,12 +629,12 @@ public final class AppModel {let request = AppGenerationRequest(modelDirectory: URL(fileURLWithPath: modelPathText),prompt: promptText,- maxNewTokens: maxNewTokens,+ maxNewTokens: maxNewTokensOverride ?? maxContextTokens,maxContextTokens: maxContextTokens,temperature: Float(temperature),topK: topKEnabled ? topK : nil,topP: topKEnabled && topPEnabled ? Float(topP) : nil,- repetitionPenalty: repetitionPenaltyEnabled ? Float(repetitionPenalty) : 1.0,+ repetitionPenalty: 1.0,runtimeOptions: runtimeOptions)try request.validate(requireModelDirectory: true)return requestdiff --git a/Sources/TurboFieldfareApp/Core/State/AppPresentationState.swift b/Sources/TurboFieldfareApp/Core/State/AppPresentationState.swiftindex 0098ac09..a6071d08 100644--- a/Sources/TurboFieldfareApp/Core/State/AppPresentationState.swift+++ b/Sources/TurboFieldfareApp/Core/State/AppPresentationState.swift@@ -8,6 +8,16 @@ public enum AppPresentationSeverity: Equatable, Sendable {case error}+public enum AppModelAction: Equatable, Sendable {+ case install+ case cancelInstall+ case load+ case retryLoad+ case cancelLoad+ case reload+ case unload+}+public struct AppPresentationSnapshot: Equatable, Sendable {public var requiresInstallation: Boolpublic var installState: AppModelInstallState@@ -51,15 +61,21 @@ public struct AppPresentationState: Equatable, Sendable {public var detail: String?public var severity: AppPresentationSeveritypublic var showsActivity: Bool+ public var primaryAction: AppModelAction?+ public var secondaryAction: AppModelAction?public init(label: String,detail: String? = nil,severity: AppPresentationSeverity = .neutral,- showsActivity: Bool = false) {+ showsActivity: Bool = false,+ primaryAction: AppModelAction? = nil,+ secondaryAction: AppModelAction? = nil) {self.label = labelself.detail = detailself.severity = severityself.showsActivity = showsActivity+ self.primaryAction = primaryAction+ self.secondaryAction = secondaryAction}public static func resolve(_ snapshot: AppPresentationSnapshot) -> Self {@@ -69,16 +85,18 @@ public struct AppPresentationState: Equatable, Sendable {severity: .active, showsActivity: true)}return Self(label: installLabel(snapshot.installState),- severity: .active, showsActivity: true)+ severity: .active, showsActivity: true,+ primaryAction: snapshot.installState.canCancel ? .cancelInstall : nil)}if snapshot.requiresInstallation {if case .failed(let message) = snapshot.installState {return Self(label: "Installation failed", detail: message,- severity: .error)+ severity: .error, primaryAction: .install)}if case .cancelled = snapshot.installState {- return Self(label: "Installation cancelled", severity: .warning)+ return Self(label: "Installation cancelled", severity: .warning,+ primaryAction: .install)}if case .failed(let message) = snapshot.installReadiness {return Self(label: "Storage check failed", detail: message,@@ -94,21 +112,22 @@ public struct AppPresentationState: Equatable, Sendable {severity: .active, showsActivity: true)}if case .ready = snapshot.installReadiness {- return Self(label: "Model required")+ return Self(label: "Model required", primaryAction: .install)}return Self(label: "Model required")}switch snapshot.loadState {case .loading(let phase):- return Self(label: phase.label, severity: .active, showsActivity: true)+ return Self(label: phase.label, severity: .active, showsActivity: true,+ primaryAction: .cancelLoad)case .cancelling:return Self(label: "Cancelling load", severity: .active, showsActivity: true)case .unloading:return Self(label: "Unloading model", severity: .active, showsActivity: true)case .failed(let error):return Self(label: "Model load failed", detail: error.userMessage,- severity: .error)+ severity: .error, primaryAction: .retryLoad)case .notLoaded, .ready:break}@@ -132,17 +151,19 @@ public struct AppPresentationState: Equatable, Sendable {}if snapshot.hasStaleRuntime {- return Self(label: "Reload required", severity: .warning)+ return Self(label: "Reload required", severity: .warning,+ primaryAction: .reload, secondaryAction: .unload)}if case .ready = snapshot.loadState {if let reason = snapshot.lastStopReason {- return Self(label: "Done · \(reason.rawValue)", severity: .success)+ return Self(label: "Done · \(reason.rawValue)", severity: .success,+ secondaryAction: .unload)}- return Self(label: "Ready", severity: .success)+ return Self(label: "Ready", severity: .success, secondaryAction: .unload)}- return Self(label: "Installed · Not loaded")+ return Self(label: "Installed · Not loaded", primaryAction: .load)}private static func installLabel(_ state: AppModelInstallState) -> String {diff --git a/Sources/TurboFieldfareApp/Mac/App/RootView.swift b/Sources/TurboFieldfareApp/Mac/App/RootView.swiftindex bfdf37b5..f0b81a99 100644--- a/Sources/TurboFieldfareApp/Mac/App/RootView.swift+++ b/Sources/TurboFieldfareApp/Mac/App/RootView.swift@@ -1,8 +1,10 @@import TurboFieldfareAppCore+import TurboFieldfareMacPresentationimport SwiftUIstruct RootView: View {let model: AppModel+ @State private var conversationChromeHeight: CGFloat = 0var body: some View {HStack(spacing: 0) {@@ -20,12 +22,14 @@ struct RootView: View {LinearGradient(colors: [Color(nsColor: .windowBackgroundColor),- Color(nsColor: .windowBackgroundColor).mix(with: .indigo, by: 0.04),+ Color(nsColor: .windowBackgroundColor).mix(+ with: TurboFieldfareMacTheme.accentColor,+ by: 0.04),],startPoint: .top,endPoint: .bottom)}- .tint(.indigo)+ .tint(TurboFieldfareMacTheme.accentColor).animation(.smooth(duration: 0.3), value: model.requiresModelInstallation).animation(.smooth(duration: 0.25), value: model.error).transaction { transaction in@@ -49,20 +53,60 @@ struct RootView: View {}private var conversationView: some View {- OutputPaneView(model: model)- .safeAreaInset(edge: .bottom, spacing: 0) {- VStack(spacing: 10) {- ErrorBanner(model: model)- if model.promptText.isEmpty {- PromptExamplesView { preset in- model.promptText = preset.prefix+ GeometryReader { geometry in+ ZStack(alignment: .bottom) {+ if model.hasOutputTranscript {+ OutputPaneView(model: model)+ .padding(.bottom, conversationChromeHeight)+ } else if conversationChromeHeight > 0 {+ OutputPaneView(model: model)+ .frame(+ height: max(+ 0,+ geometry.size.height - conversationChromeHeight))+ .frame(maxHeight: .infinity, alignment: .top)+ }++ conversationChrome+ .background {+ GeometryReader { chromeGeometry in+ Color.clear.preference(+ key: ConversationChromeHeightKey.self,+ value: chromeGeometry.size.height)}}- PromptComposerView(model: model)+ }+ .onPreferenceChange(ConversationChromeHeightKey.self) { height in+ guard height > 0 else { return }+ var transaction = Transaction()+ transaction.disablesAnimations = true+ withTransaction(transaction) {+ conversationChromeHeight = height}- .padding(.horizontal, 20)- .padding(.bottom, 16)}- .animation(.smooth(duration: 0.2), value: model.promptText.isEmpty)+ }+ }++ private var conversationChrome: some View {+ VStack(spacing: 10) {+ ErrorBanner(model: model)+ if model.promptText.isEmpty {+ PromptExamplesView { preset in+ model.promptText = preset.prompt+ }+ }+ PromptComposerView(model: model)+ }+ .padding(.horizontal, 20)+ .padding(.bottom, 16)+ .animation(.smooth(duration: 0.2), value: model.promptText.isEmpty)+ }+}++private struct ConversationChromeHeightKey: PreferenceKey {+ static let defaultValue: CGFloat = 0++ static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {+ value = max(value, nextValue())}}diff --git a/Sources/TurboFieldfareApp/Mac/App/TurboFieldfareMacApp.swift b/Sources/TurboFieldfareApp/Mac/App/TurboFieldfareMacApp.swiftindex ae19a3aa..1eb67e5b 100644--- a/Sources/TurboFieldfareApp/Mac/App/TurboFieldfareMacApp.swift+++ b/Sources/TurboFieldfareApp/Mac/App/TurboFieldfareMacApp.swift@@ -29,7 +29,9 @@ struct TurboFieldfareMacApp: App {@State private var model: AppModelinit() {- _model = State(initialValue: AppModel(client: DecodeServiceInferenceClient()))+ _model = State(initialValue: AppModel(+ client: DecodeServiceInferenceClient(),+ settingsPersistenceEnabled: true))}var body: some Scene {@@ -51,8 +53,6 @@ struct TurboFieldfareMacApp: App {CommandMenu("Model") {Button("Load Model", action: model.loadModel).disabled(!model.canLoadModel)- Button("Cancel Load", action: model.cancelLoad)- .disabled(!model.canCancelLoad)Button("Reload Model", action: model.reloadModel).disabled(!model.canReloadModel)Button("Unload Model", action: model.unloadModel)diff --git a/Sources/TurboFieldfareApp/Mac/Components/GenerateControl.swift b/Sources/TurboFieldfareApp/Mac/Components/GenerateControl.swiftindex b096adc4..8c8f299c 100644--- a/Sources/TurboFieldfareApp/Mac/Components/GenerateControl.swift+++ b/Sources/TurboFieldfareApp/Mac/Components/GenerateControl.swift@@ -1,4 +1,5 @@import TurboFieldfareAppCore+import TurboFieldfareMacPresentationimport SwiftUIstruct GenerateControl: View {@@ -25,7 +26,7 @@ struct GenerateControl: View {}.buttonStyle(.plain).foregroundStyle(.white)- .background(.indigo, in: .capsule)+ .background(TurboFieldfareMacTheme.accentColor, in: .capsule).overlay {Capsule().stroke(.white.opacity(0.16), lineWidth: 0.5)}@@ -65,7 +66,7 @@ struct GenerateControl: View {}.buttonStyle(.plain).foregroundStyle(.white)- .background(.indigo, in: .capsule)+ .background(TurboFieldfareMacTheme.accentColor, in: .capsule).overlay {Capsule().stroke(.white.opacity(0.16), lineWidth: 0.5)}diff --git a/Sources/TurboFieldfareApp/Mac/Diagnostics/InspectorView.swift b/Sources/TurboFieldfareApp/Mac/Diagnostics/InspectorView.swiftindex 64eeaec2..6a02d746 100644--- a/Sources/TurboFieldfareApp/Mac/Diagnostics/InspectorView.swift+++ b/Sources/TurboFieldfareApp/Mac/Diagnostics/InspectorView.swift@@ -8,8 +8,8 @@ struct InspectorView: View {var body: some View {Form {modelSection- samplingSection- expertCacheSection+ memorySection+ generationSectionruntimeSectionRunnerDiagnosticsSection(diagnostics: model.diagnostics)}@@ -22,7 +22,7 @@ struct InspectorView: View {Section("Model") {LabeledContent("Path") {HStack(spacing: 6) {- Text((model.modelPathText as NSString).abbreviatingWithTildeInPath)+ Text(model.modelPathText).font(.caption).truncationMode(.middle).lineLimit(1)@@ -70,20 +70,37 @@ struct InspectorView: View {.disabled(model.isRunning || model.isInstallingModel)}- private var samplingSection: some View {- Section("Sampling") {- LabeledContent("Max response") {- Stepper(value: $model.maxNewTokens, in: 1...4096, step: 16) {- Text("\(model.maxNewTokens)").monospacedDigit()+ private var memorySection: some View {+ Section("Memory") {+ LabeledContent("Context") {+ Picker("Context", selection: $model.maxContextTokens) {+ ForEach(AppContextLengthOption.allCases) { option in+ Text(option.menuLabel).tag(option.tokens)+ }}+ .pickerStyle(.menu)+ .labelsHidden().fixedSize()}- LabeledContent("Max context") {- Stepper(value: $model.maxContextTokens, in: 256...8192, step: 256) {- Text("\(model.maxContextTokens)").monospacedDigit()+ LabeledContent("Slots") {+ Picker("Slots", selection: $model.runtimeOptions.expertCacheSlots) {+ ForEach(AppRuntimeOptions.allowedSlotCounts, id: \.self) { slots in+ Text(AppRuntimeOptions.slotsLabel(for: slots)).tag(slots)+ }}+ .pickerStyle(.menu)+ .labelsHidden().fixedSize()}+ Text("Memory changes are compared with 4K context and 16 expert slots. Changes apply after reloading the model.")+ .font(.caption)+ .foregroundStyle(.secondary)+ }+ .disabled(model.isRunning || model.loadState.isLoading)+ }++ private var generationSection: some View {+ Section("Generation") {LabeledContent("Temperature") {HStack(spacing: 8) {Slider(value: $model.temperature, in: 0...2, step: 0.05)@@ -115,52 +132,6 @@ struct InspectorView: View {}}}- Toggle("Repetition penalty", isOn: $model.repetitionPenaltyEnabled)- .toggleStyle(.switch)- if model.repetitionPenaltyEnabled {- LabeledContent("Penalty value") {- HStack(spacing: 8) {- Slider(value: $model.repetitionPenalty, in: 1...1.8, step: 0.05)- Text(model.repetitionPenalty, format: .number.precision(.fractionLength(2)))- .monospacedDigit()- .frame(width: 36, alignment: .trailing)- }- }- }- Text("Defaults: 1,024 tokens, temperature 1.00, Top-K 64, Top-P 0.95. Repetition penalty is off.")- .font(.caption)- .foregroundStyle(.secondary)- }- .disabled(model.isRunning || model.loadState.isLoading)- }-- private var expertCacheSection: some View {- Section("Expert cache") {- LabeledContent("Slots") {- Picker("Slots", selection: $model.runtimeOptions.expertCacheSlots) {- ForEach(AppRuntimeOptions.allowedSlotCounts, id: \.self) { slots in- Text(AppRuntimeOptions.slotsLabel(for: slots)).tag(slots)- }- }- .pickerStyle(.menu)- .labelsHidden()- .fixedSize()- }- VStack(alignment: .leading, spacing: 8) {- Text("Policy")- Picker("Policy", selection: $model.runtimeOptions.expertCachePolicy) {- ForEach(AppExpertCachePolicy.allCases) { policy in- Text(policy.label).tag(policy)- }- }- .pickerStyle(.segmented)- .labelsHidden()- }- if model.runtimeOptions.expertCacheSlots > 16 {- Text("Slot counts above 16 trade extra RAM for fewer expert reads.")- .font(.caption)- .foregroundStyle(.secondary)- }}.disabled(model.isRunning || model.loadState.isLoading)}@@ -168,50 +139,22 @@ struct InspectorView: View {private var runtimeSection: some View {Section("Runtime") {Toggle("Prefill", isOn: $model.runtimeOptions.prefillEnabled)- LabeledContent("Prefill chunk") {- Picker("Prefill chunk", selection: $model.runtimeOptions.prefillChunkTokens) {- ForEach(AppRuntimeOptions.allowedPrefillChunkTokens, id: \.self) { tokens in- Text("\(tokens) tokens").tag(tokens)- }- }- .pickerStyle(.menu)- .labelsHidden()- .fixedSize()- }- .disabled(!model.runtimeOptions.prefillEnabled)- Toggle("TurboQuant K4/V4 (Experimental)",- isOn: $model.runtimeOptions.turboQuantKVEnabled)Text("This is an experimental feature and may reduce output quality.").font(.caption).foregroundStyle(.secondary)- VStack(alignment: .leading, spacing: 8) {- Text("RDADVISE")+ LabeledContent("RDADVISE") {Picker("RDADVISE", selection: $model.runtimeOptions.rdadvisePolicy) {- ForEach(AppRDAdvicePolicy.allCases) { mode in- Text(mode.label).tag(mode)+ ForEach(AppRDAdvicePolicy.allCases) { policy in+ Text(policy.label).tag(policy)}}- .pickerStyle(.segmented)+ .pickerStyle(.menu).labelsHidden()+ .fixedSize()}Text("RDADVISE is experimental. It may speed up short decodes but slow down long decodes.").font(.caption).foregroundStyle(.secondary)- LabeledContent("Model verification") {- Picker("Model verification", selection: $model.runtimeOptions.modelVerification) {- ForEach(AppModelVerification.allCases) { choice in- Text(choice.label).tag(choice)- }- }- .pickerStyle(.menu)- .labelsHidden()- .fixedSize()- }- if model.runtimeOptions.modelVerification == .trustedInstall {- Text("Trust verified install checks the signed-off receipt and file sizes instead of hashing all model files again.")- .font(.caption)- .foregroundStyle(.secondary)- }if model.hasStaleLoadedRuntime {Text("Reload required").font(.caption)diff --git a/Sources/TurboFieldfareApp/Mac/Diagnostics/StatusHUDView.swift b/Sources/TurboFieldfareApp/Mac/Diagnostics/StatusHUDView.swiftindex 07025c4a..2d8c8e3c 100644--- a/Sources/TurboFieldfareApp/Mac/Diagnostics/StatusHUDView.swift+++ b/Sources/TurboFieldfareApp/Mac/Diagnostics/StatusHUDView.swift@@ -1,4 +1,5 @@import TurboFieldfareAppCore+import TurboFieldfareMacPresentationimport SwiftUIstruct StatusHUDView: View {@@ -23,6 +24,7 @@ struct StatusHUDView: View {HUDMetricView(value: memoryText, label: "memory", animated: !model.isRunning)}}+ .frame(height: 30).padding(.horizontal, 16).padding(.vertical, 10).background {@@ -71,7 +73,7 @@ private struct PhaseLabel: View {.monospacedDigit().contentTransition(.numericText())case .steady(let label):- Circle().fill(.indigo).frame(width: 7, height: 7)+ Circle().fill(TurboFieldfareMacTheme.accentColor).frame(width: 7, height: 7)Text(label).contentTransition(.opacity)case .quiet(let label):Text(label)@@ -105,7 +107,7 @@ private struct PhaseLabel: View {private struct PulsingDot: View {var body: some View {Circle()- .fill(.indigo)+ .fill(TurboFieldfareMacTheme.accentColor).frame(width: 7, height: 7).phaseAnimator([0.4, 1.0]) { dot, opacity indot.opacity(opacity)diff --git a/Sources/TurboFieldfareApp/Mac/Generation/OutputPaneView.swift b/Sources/TurboFieldfareApp/Mac/Generation/OutputPaneView.swiftindex be456a00..5307de51 100644--- a/Sources/TurboFieldfareApp/Mac/Generation/OutputPaneView.swift+++ b/Sources/TurboFieldfareApp/Mac/Generation/OutputPaneView.swift@@ -1,85 +1,130 @@import AppKitimport TurboFieldfareAppCore+import TurboFieldfareMacPresentationimport SwiftUIstruct OutputPaneView: View {let model: AppModel+ @State private var responseCopyFeedbackID: UUID?var body: some View {Group {- if model.isRunning && !hasVisibleCompletion {- pendingGeneration- } else if model.hasOutputTranscript {+ if model.hasOutputTranscript {transcript} else {placeholder}}+ .task(id: responseCopyFeedbackID) {+ guard let feedbackID = responseCopyFeedbackID else { return }+ try? await Task.sleep(for: .seconds(1.2))+ guard !Task.isCancelled, responseCopyFeedbackID == feedbackID else { return }+ withAnimation(.easeOut(duration: 0.15)) {+ responseCopyFeedbackID = nil+ }+ }.contextMenu {- Button("Copy All") {- NSPasteboard.general.clearContents()- NSPasteboard.general.setString(model.outputPlainText, forType: .string)+ Button("Copy response") {+ copyResponse()+ }+ .disabled(model.outputResponsePlainText.isEmpty)++ Button("Copy prompt") {+ copy(model.outputPromptText)}- .disabled(!model.hasOutputTranscript)+ .disabled(model.outputPromptText.isEmpty)++ Button("Copy conversation") {+ copy(model.outputConversationPlainText)+ }+ .disabled(model.outputConversationPlainText.isEmpty)++ Divider()+Button("Clear") { model.clearOutput() }.disabled(model.isRunning || !model.hasOutputTranscript)}}- @ViewBuilderprivate var placeholder: some View {- ScrollView {- emptyPlaceholder- .padding(.horizontal, 24)- .padding(.vertical, 20)- .frame(maxWidth: .infinity, alignment: .leading)+ EmptyConversationLayout(spacing: 8) {+ EmptyPlaceholderIcon(systemName: placeholderSymbol)+ .frame(width: 32, height: 32)++ emptyPlaceholderContent}- .defaultScrollAnchor(.bottom, for: .sizeChanges)+ .padding(.horizontal, 24)+ .padding(.vertical, 20)+ .frame(maxWidth: .infinity, maxHeight: .infinity)}private var transcript: some View {IncrementalTranscriptView(prompt: model.outputPromptText,output: model.outputText,- mailbox: model.generationTranscriptMailbox)+ mailbox: model.generationTranscriptMailbox,+ isTerminal: !model.isRunning,+ showsPrefillPlaceholder: model.isRunning+ && model.outputResponsePlainText.isEmpty).frame(maxWidth: .infinity, maxHeight: .infinity)- .padding(.horizontal, 24)- .padding(.vertical, 20)- }-- private var pendingGeneration: some View {- VStack(spacing: 10) {- Text("Processing prompt")- .font(.callout)- .foregroundStyle(.secondary)- if model.livePrefillTotal > 0 {- Text("\(model.livePrefillDone) of \(model.livePrefillTotal) tokens")- .font(.caption)- .monospacedDigit()- .foregroundStyle(.tertiary)+ .overlay(alignment: .topTrailing) {+ if !model.isRunning && !model.outputResponsePlainText.isEmpty {+ copyResponseButton+ .padding(8)+ }}- }- .frame(maxWidth: .infinity, maxHeight: .infinity)- .padding(24)+ .padding(.horizontal, 24)+ .padding(.vertical, 20)}- private var hasVisibleCompletion: Bool {- model.outputText.contains { !$0.isWhitespace }+ private var copyResponseButton: some View {+ Button {+ copyResponse()+ } label: {+ Image(systemName: responseCopyFeedbackID == nil+ ? "doc.on.doc"+ : "checkmark.circle.fill")+ .font(.callout.weight(.medium))+ .contentTransition(.symbolEffect(.replace))+ .foregroundStyle(responseCopyFeedbackID == nil+ ? Color.secondary+ : TurboFieldfareMacTheme.accentColor)+ .frame(width: 28, height: 28)+ .contentShape(Circle())+ .background(.regularMaterial, in: Circle())+ .overlay {+ Circle().stroke(.separator.opacity(0.5), lineWidth: 0.5)+ }+ }+ .buttonStyle(.plain)+ .accessibilityLabel(responseCopyFeedbackID == nil+ ? "Copy response"+ : "Response copied")+ .accessibilityHint("Copies only the generated answer")+ .help(responseCopyFeedbackID == nil+ ? "Copy response"+ : "Response copied")}- private var emptyPlaceholder: some View {+ private var emptyPlaceholderContent: some View {VStack(spacing: 8) {- Image(systemName: placeholderSymbol)- .font(.title2)- .foregroundStyle(.quaternary)if !needsModelLoad {- Text("Give TurboFieldfare a beginning, and it will continue the text from there.")+ Text("Choose a predefined example or write your own prompt.")+ .font(.headline)+ Text("Describe the goal, relevant context, and any constraints.").font(.callout).foregroundStyle(.secondary)+ .multilineTextAlignment(.center)+ }+ if isLoadingModel {+ LoadingModelText()+ .font(.callout)+ .foregroundStyle(.tertiary)+ } else if let placeholderHint {+ Text(placeholderHint)+ .font(.callout)+ .foregroundStyle(.tertiary)}- Text(placeholderHint)- .font(.callout)- .foregroundStyle(.tertiary)if let detail = model.presentation.detail {Text(detail).font(.caption)@@ -91,30 +136,122 @@ struct OutputPaneView: View {action: model.loadModel).buttonStyle(.borderedProminent).controlSize(.large)+ } else if isLoadingModel {+ Button("Load Model", action: {})+ .buttonStyle(.borderedProminent)+ .controlSize(.large)+ .hidden()+ .accessibilityHidden(true)} else if model.canReloadModel {Button("Reload Model", action: model.reloadModel).buttonStyle(.borderedProminent)- } else if model.canCancelLoad {- Button("Cancel Load", action: model.cancelLoad)}}- .frame(maxWidth: .infinity, minHeight: 240)+ .frame(maxWidth: .infinity)}private var needsModelLoad: Bool {!model.loadState.isReady}+ private var isLoadingModel: Bool {+ if case .loading = model.loadState { return true }+ return false+ }+private var placeholderSymbol: String {- needsModelLoad ? "cube.transparent" : "text.cursor"+ "cube.transparent"}- private var placeholderHint: String {+ private var placeholderHint: String? {if model.loadState.isFailed { return "The model could not be loaded" }if model.hasStaleLoadedRuntime { return "Reload the model to use changed settings" }- return needsModelLoad- ? "Load the model to begin"- : "Enter a prompt and press \u{2318}\u{21A9} to generate"+ return needsModelLoad ? "Load the model to begin" : nil+ }++ private func copy(_ text: String) {+ NSPasteboard.general.clearContents()+ NSPasteboard.general.setString(text, forType: .string)+ }++ private func copyResponse() {+ copy(model.outputResponsePlainText)+ withAnimation(.easeIn(duration: 0.15)) {+ responseCopyFeedbackID = UUID()+ }+ }+}++private struct EmptyPlaceholderIcon: View {+ let systemName: String++ var body: some View {+ Image(systemName: systemName)+ .font(.title2)+ .foregroundStyle(.quaternary)+ .accessibilityHidden(true)+ }+}++private struct EmptyConversationLayout: Layout {+ let spacing: CGFloat++ func sizeThatFits(+ proposal: ProposedViewSize,+ subviews: Subviews,+ cache: inout ()+ ) -> CGSize {+ proposal.replacingUnspecifiedDimensions()+ }++ func placeSubviews(+ in bounds: CGRect,+ proposal: ProposedViewSize,+ subviews: Subviews,+ cache: inout ()+ ) {+ guard subviews.count == 2 else { return }++ let iconSize = subviews[0].sizeThatFits(.unspecified)+ let iconCenter = CGPoint(x: bounds.midX, y: bounds.midY)+ subviews[0].place(+ at: iconCenter,+ anchor: .center,+ proposal: ProposedViewSize(+ width: iconSize.width,+ height: iconSize.height))++ subviews[1].place(+ at: CGPoint(+ x: bounds.midX,+ y: iconCenter.y + iconSize.height / 2 + spacing),+ anchor: .top,+ proposal: ProposedViewSize(width: bounds.width, height: nil))+ }+}++private struct LoadingModelText: View {+ @Environment(\.accessibilityReduceMotion) private var reduceMotion+ @State private var animationStart = Date()++ var body: some View {+ if reduceMotion {+ label(dotCount: 3)+ } else {+ TimelineView(.periodic(from: .now, by: 0.25)) { context in+ let elapsed = max(0, context.date.timeIntervalSince(animationStart))+ label(dotCount: Int(elapsed / 0.25) % 4)+ }+ }+ }++ private func label(dotCount: Int) -> some View {+ ZStack(alignment: .leading) {+ Text("Loading Model...").hidden()+ Text("Loading Model" + String(repeating: ".", count: dotCount))+ }+ .accessibilityElement(children: .ignore)+ .accessibilityLabel("Loading Model")}}@@ -122,15 +259,20 @@ private struct IncrementalTranscriptView: NSViewRepresentable {var prompt: Stringvar output: Stringvar mailbox: GenerationTranscriptMailbox?+ var isTerminal: Bool+ var showsPrefillPlaceholder: Bool@MainActorfinal class Coordinator: NSObject {- var prompt = ""- var output = ""weak var scrollView: NSScrollView?weak var textView: NSTextView?var mailbox: GenerationTranscriptMailbox?+ var prompt = ""+ var isTerminal = false+ var showsPrefillPlaceholder = falsevar timer: Timer?+ var prefillAnimationTimer: Timer?+ let documentController = InstructionTranscriptDocumentController()func attach(scrollView: NSScrollView, textView: NSTextView) {self.scrollView = scrollView@@ -144,64 +286,129 @@ private struct IncrementalTranscriptView: NSViewRepresentable {self.timer = timer}- func synchronize(prompt: String, output: String,- mailbox: GenerationTranscriptMailbox?) {+ func synchronize(+ prompt: String,+ output: String,+ mailbox: GenerationTranscriptMailbox?,+ isTerminal: Bool,+ showsPrefillPlaceholder: Bool+ ) {self.mailbox = mailbox- let completion = mailbox?.drain().completeText ?? output- apply(prompt: prompt, output: completion)+ self.prompt = prompt+ self.isTerminal = isTerminal+ self.showsPrefillPlaceholder = showsPrefillPlaceholder+ let response = mailbox?.drain().completeText ?? output+ apply(+ prompt: prompt,+ response: response,+ isTerminal: isTerminal,+ showsPrefillPlaceholder: showsPrefillPlaceholder)}@objc private func drainMailbox() {guard let mailbox else { return }let snapshot = mailbox.drain()- guard !snapshot.pendingText.isEmpty || snapshot.completeText != output else { return }- apply(prompt: prompt, output: snapshot.completeText)+ guard !snapshot.pendingText.isEmpty+ || snapshot.completeText != documentController.response else {+ return+ }+ apply(prompt: prompt,+ response: snapshot.completeText,+ isTerminal: isTerminal,+ showsPrefillPlaceholder: showsPrefillPlaceholder)+ }++ @objc private func animatePrefillPlaceholderIfNeeded() {+ guard documentController.showsPrefillPlaceholder,+ let scrollView,+ let textView,+ let storage = textView.textStorage else { return }+ let wasAtBottom = isAtBottom(scrollView)+ let selection = textView.selectedRanges.map(\.rangeValue)++ storage.beginEditing()+ let changed = documentController.advancePrefillAnimation(storage: storage)+ storage.endEditing()+ guard changed else { return }++ let restored = InstructionTranscriptDocumentController.clampedRanges(+ selection,+ toLength: storage.length)+ if restored.isEmpty {+ textView.setSelectedRange(NSRange(location: storage.length, length: 0))+ } else {+ textView.selectedRanges = restored.map(NSValue.init(range:))+ }+ if wasAtBottom { textView.scrollToEndOfDocument(nil) }}func invalidate() {timer?.invalidate()timer = nil+ stopPrefillAnimationTimer()mailbox = nil}- private func apply(prompt: String, output: String) {- guard let scrollView, let textView, let storage = textView.textStorage else {- return+ private func updatePrefillAnimationTimer() {+ if documentController.showsPrefillPlaceholder {+ guard prefillAnimationTimer == nil else { return }+ let timer = Timer(+ timeInterval: 0.25,+ target: self,+ selector: #selector(animatePrefillPlaceholderIfNeeded),+ userInfo: nil,+ repeats: true)+ timer.tolerance = 0.025+ RunLoop.main.add(timer, forMode: .common)+ prefillAnimationTimer = timer+ } else {+ stopPrefillAnimationTimer()}+ }++ private func stopPrefillAnimationTimer() {+ prefillAnimationTimer?.invalidate()+ prefillAnimationTimer = nil+ }++ private func apply(+ prompt: String,+ response: String,+ isTerminal: Bool,+ showsPrefillPlaceholder: Bool+ ) {+ guard let scrollView, let textView, let storage = textView.textStorage else { return }let wasAtBottom = isAtBottom(scrollView)- let selection = textView.selectedRanges+ let selection = textView.selectedRanges.map(\.rangeValue)storage.beginEditing()- if prompt != self.prompt || !output.hasPrefix(self.output) {- let replacement = NSMutableAttributedString(- string: prompt,- attributes: promptAttributes())- replacement.append(NSAttributedString(- string: output,- attributes: outputAttributes()))- storage.setAttributedString(replacement)- } else if output.count > self.output.count {- let delta = String(output.dropFirst(self.output.count))- storage.append(NSAttributedString(- string: delta,- attributes: outputAttributes()))- }+ let update = documentController.synchronize(+ storage: storage,+ prompt: prompt,+ response: response,+ isTerminal: isTerminal,+ showsPrefillPlaceholder: showsPrefillPlaceholder)storage.endEditing()+ updatePrefillAnimationTimer()- self.prompt = prompt- self.output = output- let restoredSelection = selection.map { value in- let range = value.rangeValue- let location = min(range.location, storage.length)- let length = min(range.length, storage.length - location)- return NSValue(range: NSRange(location: location, length: length))- }- if restoredSelection.isEmpty {+ guard update.mutation != .none else { return }+ let restored = InstructionTranscriptDocumentController.clampedRanges(+ selection,+ toLength: storage.length)+ if restored.isEmpty {textView.setSelectedRange(NSRange(location: storage.length, length: 0))} else {- textView.selectedRanges = restoredSelection+ textView.selectedRanges = restored.map(NSValue.init(range:))+ }+ if InstructionTranscriptDocumentController.shouldScrollToBottom(+ wasAtBottom: wasAtBottom,+ mutation: update.mutation+ ) {+ if let textContainer = textView.textContainer {+ textView.layoutManager?.ensureLayout(for: textContainer)+ }+ textView.scrollToEndOfDocument(nil)}- if wasAtBottom { textView.scrollToEndOfDocument(nil) }}private func isAtBottom(_ scrollView: NSScrollView) -> Bool {@@ -209,26 +416,6 @@ private struct IncrementalTranscriptView: NSViewRepresentable {let visible = scrollView.contentView.boundsreturn visible.maxY >= document.bounds.maxY - 24}-- private func outputAttributes() -> [NSAttributedString.Key: Any] {- [.font: NSFont.monospacedSystemFont(- ofSize: NSFont.systemFontSize, weight: .regular),- .foregroundColor: NSColor.labelColor,- .paragraphStyle: paragraphStyle()]- }-- private func promptAttributes() -> [NSAttributedString.Key: Any] {- [.font: NSFont.monospacedSystemFont(- ofSize: NSFont.systemFontSize, weight: .bold),- .foregroundColor: NSColor.labelColor,- .paragraphStyle: paragraphStyle()]- }-- private func paragraphStyle() -> NSParagraphStyle {- let style = NSMutableParagraphStyle()- style.lineSpacing = 3- return style- }}func makeCoordinator() -> Coordinator { Coordinator() }@@ -242,13 +429,17 @@ private struct IncrementalTranscriptView: NSViewRepresentable {let textView = NSTextView()textView.isEditable = falsetextView.isSelectable = true+ textView.isRichText = truetextView.drawsBackground = false- textView.textContainerInset = NSSize(width: 0, height: 0)+ textView.textContainerInset = NSSize(width: 0, height: 4)textView.isVerticallyResizable = truetextView.isHorizontallyResizable = falsetextView.autoresizingMask = [.width]textView.textContainer?.widthTracksTextView = truetextView.textContainer?.lineFragmentPadding = 0+ textView.isAutomaticLinkDetectionEnabled = false+ textView.isAutomaticDataDetectionEnabled = false+ textView.setAccessibilityLabel("Conversation transcript")scrollView.documentView = textViewreturn scrollView}@@ -257,11 +448,77 @@ private struct IncrementalTranscriptView: NSViewRepresentable {guard let textView = scrollView.documentView as? NSTextView else { return }context.coordinator.attach(scrollView: scrollView, textView: textView)context.coordinator.synchronize(- prompt: prompt, output: output, mailbox: mailbox)+ prompt: prompt,+ output: output,+ mailbox: mailbox,+ isTerminal: isTerminal,+ showsPrefillPlaceholder: showsPrefillPlaceholder)}- static func dismantleNSView(_ nsView: NSScrollView,- coordinator: Coordinator) {+ static func dismantleNSView(_ nsView: NSScrollView, coordinator: Coordinator) {coordinator.invalidate()}}++#if DEBUG+private struct TranscriptPreview: View {+ let response: String+ let isTerminal: Bool+ var showsPrefillPlaceholder = false++ var body: some View {+ IncrementalTranscriptView(+ prompt: "Explain this clearly.",+ output: response,+ mailbox: nil,+ isTerminal: isTerminal,+ showsPrefillPlaceholder: showsPrefillPlaceholder)+ .padding(24)+ .frame(width: 720, height: 420)+ }+}++#Preview("Empty") {+ VStack(spacing: 8) {+ Image(systemName: "cube.transparent")+ .font(.title2)+ .foregroundStyle(.quaternary)+ Text("Choose a predefined example or write your own prompt.")+ .font(.headline)+ Text("Describe the goal, relevant context, and any constraints.")+ .foregroundStyle(.secondary)+ }+ .frame(width: 720, height: 420)+}++#Preview("Streaming") {+ TranscriptPreview(+ response: "A response arriving one readable piece at a time...",+ isTerminal: false)+}++#Preview("Prefilling") {+ TranscriptPreview(+ response: "",+ isTerminal: false,+ showsPrefillPlaceholder: true)+}++#Preview("Completed prose") {+ TranscriptPreview(+ response: "# A clear answer\n\nHere is a concise explanation with **useful emphasis**.\n\n- First point\n- Second point",+ isTerminal: true)+}++#Preview("Completed code") {+ TranscriptPreview(+ response: "Use `fibonacci(7)`:\n\n```python\ndef fibonacci(n: int) -> list[int]:\n return []\n```",+ isTerminal: true)+}++#Preview("Incomplete Markdown fallback") {+ TranscriptPreview(+ response: "The partial answer remains readable.\n\n```python\nprint('unfinished')",+ isTerminal: true)+}+#endifdiff --git a/Sources/TurboFieldfareApp/Mac/Generation/PromptComposerView.swift b/Sources/TurboFieldfareApp/Mac/Generation/PromptComposerView.swiftindex 932e54e8..00e5c84f 100644--- a/Sources/TurboFieldfareApp/Mac/Generation/PromptComposerView.swift+++ b/Sources/TurboFieldfareApp/Mac/Generation/PromptComposerView.swift@@ -79,16 +79,16 @@ struct PromptComposerView: View {Text("Prompting this model").font(.headline)- tipSection("It continues text",- "This is a base completion model, not a chat assistant. Write the beginning of the output you want, such as “A concise explanation:” or a function signature.")- tipSection("If it repeats or runs on",- "Keep Temperature at 1.0, retry, shorten Max response, or enable Repetition penalty.")- tipSection("If it drifts or invents facts",- "Put required facts, constraints, and the desired structure directly in the prompt. Keep the requested continuation focused and verify factual output.")- tipSection("For code or exact formats",- "Include the signature, schema, or a short example. Lower temperature can reduce variation, but it may increase repetition and does not guarantee correct code.")- tipSection("If it does not answer",- "Turn the question into an answer prefix. For example, use “The reason this happens is” instead of “Why does this happen?”")+ tipSection("Ask for a clear task",+ "Say what you want the model to create, explain, plan, or transform. Put the essential context in the same prompt.")+ tipSection("Shape the answer",+ "Specify a useful length, sections, tone, or output format. Concrete constraints work better than a long list of vague preferences.")+ tipSection("Anchor important facts",+ "Include facts the answer must preserve and say what should be checked. Generated factual claims can still be wrong or outdated.")+ tipSection("For code and calculations",+ "Provide types, dimensions, interfaces, edge cases, or a small scaffold. Compile or run the result before relying on it.")+ tipSection("Try a focused revision",+ "If the answer drifts, shorten the task and make the missing requirement explicit. The default temperature is 0.20 for steadier responses.")}.font(.callout).frame(width: 390, alignment: .leading)diff --git a/Sources/TurboFieldfareApp/Mac/Generation/PromptExamplesView.swift b/Sources/TurboFieldfareApp/Mac/Generation/PromptExamplesView.swiftindex d5d637ba..854390be 100644--- a/Sources/TurboFieldfareApp/Mac/Generation/PromptExamplesView.swift+++ b/Sources/TurboFieldfareApp/Mac/Generation/PromptExamplesView.swift@@ -8,9 +8,9 @@ struct PromptExamplesView: View {VStack(alignment: .leading, spacing: 12) {HStack(alignment: .firstTextBaseline) {VStack(alignment: .leading, spacing: 2) {- Text("Continue an example")+ Text("Try an example").font(.headline)- Text("Gemma continues the text you select.")+ Text("Choose a prompt, edit it, or write your own.").font(.caption).foregroundStyle(.secondary)}@@ -46,7 +46,7 @@ struct PromptExamplesView: View {.font(.caption.weight(.semibold)).foregroundStyle(.primary).lineLimit(2)- Text(preset.prefix)+ Text(preset.prompt).font(.caption2).foregroundStyle(.secondary).multilineTextAlignment(.leading)@@ -64,8 +64,8 @@ struct PromptExamplesView: View {.stroke(.separator.opacity(0.35), lineWidth: 0.5)}.accessibilityLabel(preset.title)- .accessibilityValue(preset.prefix)- .accessibilityHint("Copies this beginning into the prompt editor")+ .accessibilityValue(preset.prompt)+ .accessibilityHint("Copies this prompt into the prompt editor")}}@@ -81,13 +81,13 @@ struct PromptExamplesView: View {} label: {VStack(alignment: .leading) {Text(preset.title)- Text(preset.prefix)+ Text(preset.prompt)}}}}.menuStyle(.borderlessButton).fixedSize()- .accessibilityHint("Shows additional text beginnings")+ .accessibilityHint("Shows additional prompts")}}diff --git a/Sources/TurboFieldfareApp/Mac/Installation/ModelInstallView.swift b/Sources/TurboFieldfareApp/Mac/Installation/ModelInstallView.swiftindex 73b6c3bd..bef34e91 100644--- a/Sources/TurboFieldfareApp/Mac/Installation/ModelInstallView.swift+++ b/Sources/TurboFieldfareApp/Mac/Installation/ModelInstallView.swift@@ -1,4 +1,5 @@import TurboFieldfareAppCore+import TurboFieldfareMacPresentationimport SwiftUIstruct ModelInstallView: View {@@ -23,7 +24,7 @@ struct ModelInstallView: View {VStack(spacing: 10) {Image(systemName: "externaldrive.badge.plus").font(.system(.largeTitle, design: .rounded))- .foregroundStyle(.indigo)+ .foregroundStyle(TurboFieldfareMacTheme.accentColor).accessibilityHidden(true)Text("Model required").font(.title.bold())@@ -133,7 +134,7 @@ struct ModelInstallView: View {.keyboardShortcut(.cancelAction).disabled(!model.canCancelInstall)} else {- Button("Check Again", action: model.refreshInstallReadiness)+ Button("Check Again", action: model.recheckModelAtCurrentLocation).buttonStyle(.bordered).disabled(model.isInstallingModel)diff --git a/Sources/TurboFieldfareApp/MacPresentation/InstructionTranscriptDocumentController.swift b/Sources/TurboFieldfareApp/MacPresentation/InstructionTranscriptDocumentController.swiftnew file mode 100644index 00000000..2bf0b467--- /dev/null+++ b/Sources/TurboFieldfareApp/MacPresentation/InstructionTranscriptDocumentController.swift@@ -0,0 +1,227 @@+import AppKit+import Foundation++@MainActor+public final class InstructionTranscriptDocumentController {+ public enum Mutation: Equatable {+ case none+ case rebuilt+ case appended+ case finalized+ }++ public struct UpdateResult {+ public let mutation: Mutation+ public let assistantRange: NSRange++ public init(mutation: Mutation, assistantRange: NSRange) {+ self.mutation = mutation+ self.assistantRange = assistantRange+ }+ }++ public private(set) var prompt = ""+ public private(set) var response = ""+ public private(set) var isFinalized = false+ public private(set) var showsPrefillPlaceholder = false+ public private(set) var assistantRange = NSRange(location: 0, length: 0)+ private var prefillPlaceholderRange: NSRange?+ private var prefillDotCount = 0++ private let renderer: ResponseMarkdownRenderer++ public init(renderer: ResponseMarkdownRenderer = ResponseMarkdownRenderer()) {+ self.renderer = renderer+ }++ public static func clampedRanges(+ _ ranges: [NSRange],+ toLength length: Int+ ) -> [NSRange] {+ ranges.map { range in+ let location = min(max(range.location, 0), length)+ let available = max(0, length - location)+ return NSRange(location: location, length: min(max(range.length, 0), available))+ }+ }++ public static func shouldScrollToBottom(+ wasAtBottom: Bool,+ mutation: Mutation+ ) -> Bool {+ wasAtBottom || mutation == .finalized+ }++ public static func shouldRunPrefillAnimation(+ response: String,+ isTerminal: Bool,+ requested: Bool+ ) -> Bool {+ requested && response.isEmpty && !isTerminal+ }++ @discardableResult+ public func synchronize(+ storage: NSMutableAttributedString,+ prompt: String,+ response: String,+ isTerminal: Bool,+ showsPrefillPlaceholder: Bool = false+ ) -> UpdateResult {+ let responseChanged = response != self.response+ let displaysPrefillPlaceholder = Self.shouldRunPrefillAnimation(+ response: response,+ isTerminal: isTerminal,+ requested: showsPrefillPlaceholder)+ let needsRebuild = prompt != self.prompt+ || !response.hasPrefix(self.response)+ || (isFinalized && !isTerminal)+ || displaysPrefillPlaceholder != self.showsPrefillPlaceholder++ var mutation: Mutation = .none+ if needsRebuild+ || storage.length == 0+ && (!prompt.isEmpty || !response.isEmpty || displaysPrefillPlaceholder) {+ rebuild(+ storage: storage,+ prompt: prompt,+ response: response,+ showsPrefillPlaceholder: displaysPrefillPlaceholder)+ mutation = .rebuilt+ } else if response.count > self.response.count {+ let delta = String(response.dropFirst(self.response.count))+ storage.append(NSAttributedString(+ string: delta,+ attributes: Self.responseAttributes()))+ assistantRange.length += (delta as NSString).length+ mutation = .appended+ }++ self.prompt = prompt+ self.response = response+ self.showsPrefillPlaceholder = displaysPrefillPlaceholder++ if isTerminal && (!isFinalized || responseChanged) {+ let rendered = renderer.render(response).attributedString+ storage.replaceCharacters(in: assistantRange, with: rendered)+ assistantRange.length = rendered.length+ isFinalized = true+ mutation = .finalized+ } else if !isTerminal {+ isFinalized = false+ }++ return UpdateResult(mutation: mutation, assistantRange: assistantRange)+ }++ @discardableResult+ public func advancePrefillAnimation(+ storage: NSMutableAttributedString+ ) -> Bool {+ guard showsPrefillPlaceholder, var range = prefillPlaceholderRange else {+ return false+ }+ prefillDotCount = (prefillDotCount + 1) % 4+ let replacement = NSAttributedString(+ string: Self.prefillPlaceholder(dotCount: prefillDotCount),+ attributes: Self.prefillPlaceholderAttributes())+ storage.replaceCharacters(in: range, with: replacement)+ range.length = replacement.length+ prefillPlaceholderRange = range+ return true+ }++ private func rebuild(+ storage: NSMutableAttributedString,+ prompt: String,+ response: String,+ showsPrefillPlaceholder: Bool+ ) {+ let document = NSMutableAttributedString()+ if !prompt.isEmpty {+ document.append(NSAttributedString(+ string: "You\n",+ attributes: Self.userLabelAttributes()))+ document.append(NSAttributedString(+ string: prompt,+ attributes: Self.promptAttributes()))+ document.append(NSAttributedString(+ string: "\n\n",+ attributes: Self.promptAttributes()))+ }+ document.append(NSAttributedString(+ string: "Answer\n",+ attributes: Self.assistantLabelAttributes()))+ assistantRange = NSRange(location: document.length, length: 0)+ document.append(NSAttributedString(+ string: response,+ attributes: Self.responseAttributes()))+ assistantRange.length = (response as NSString).length+ prefillDotCount = 0+ prefillPlaceholderRange = nil+ if showsPrefillPlaceholder {+ let placeholder = NSAttributedString(+ string: Self.prefillPlaceholder(dotCount: prefillDotCount),+ attributes: Self.prefillPlaceholderAttributes())+ prefillPlaceholderRange = NSRange(+ location: document.length,+ length: placeholder.length)+ document.append(placeholder)+ }+ storage.setAttributedString(document)+ isFinalized = false+ }++ private static func userLabelAttributes() -> [NSAttributedString.Key: Any] {+ labelAttributes(color: .secondaryLabelColor)+ }++ private static func assistantLabelAttributes() -> [NSAttributedString.Key: Any] {+ labelAttributes(color: TurboFieldfareMacTheme.accentNSColor)+ }++ private static func labelAttributes(+ color: NSColor+ ) -> [NSAttributedString.Key: Any] {+ let style = NSMutableParagraphStyle()+ style.paragraphSpacing = 5+ return [+ .font: NSFont.systemFont(+ ofSize: NSFont.smallSystemFontSize,+ weight: .semibold),+ .foregroundColor: color,+ .paragraphStyle: style,+ ]+ }++ private static func promptAttributes() -> [NSAttributedString.Key: Any] {+ let style = NSMutableParagraphStyle()+ style.lineSpacing = 3+ return [+ .font: NSFont.systemFont(ofSize: NSFont.systemFontSize),+ .foregroundColor: NSColor.secondaryLabelColor,+ .paragraphStyle: style,+ ]+ }++ private static func responseAttributes() -> [NSAttributedString.Key: Any] {+ let style = NSMutableParagraphStyle()+ style.lineSpacing = 3+ style.paragraphSpacing = 6+ return [+ .font: NSFont.systemFont(ofSize: NSFont.systemFontSize),+ .foregroundColor: NSColor.labelColor,+ .paragraphStyle: style,+ ]+ }++ private static func prefillPlaceholderAttributes() -> [NSAttributedString.Key: Any] {+ var attributes = responseAttributes()+ attributes[.foregroundColor] = NSColor.secondaryLabelColor+ return attributes+ }++ private static func prefillPlaceholder(dotCount: Int) -> String {+ "Processing your prompt" + String(repeating: ".", count: dotCount)+ }+}diff --git a/Sources/TurboFieldfareApp/MacPresentation/ResponseMarkdownRenderer.swift b/Sources/TurboFieldfareApp/MacPresentation/ResponseMarkdownRenderer.swiftnew file mode 100644index 00000000..a6f13c05--- /dev/null+++ b/Sources/TurboFieldfareApp/MacPresentation/ResponseMarkdownRenderer.swift@@ -0,0 +1,317 @@+import AppKit+import Foundation++@MainActor+public struct ResponseMarkdownRenderer {+ public struct Result {+ public let attributedString: NSAttributedString+ public let usedFallback: Bool++ public init(attributedString: NSAttributedString, usedFallback: Bool) {+ self.attributedString = attributedString+ self.usedFallback = usedFallback+ }+ }++ private enum BlockKind: Equatable {+ case paragraph+ case heading(Int)+ case code+ case quote+ case unorderedList(indent: Int)+ case orderedList(ordinal: Int, indent: Int)+ case thematicBreak++ var isList: Bool {+ switch self {+ case .unorderedList, .orderedList: true+ default: false+ }+ }+ }++ private struct Block: Equatable {+ let identity: Int+ let kind: BlockKind+ }++ public init() {}++ public func render(_ source: String) -> Result {+ guard !source.isEmpty else {+ return Result(attributedString: NSAttributedString(), usedFallback: false)+ }+ guard !requiresRawFallback(source) else { return fallback(source) }+ let presentationSource = source.replacingOccurrences(+ of: #"(?m)^([ \t]*\*\*[^*\n]+\*\*[ \t]*)\n(?=\S)"#,+ with: "$1\n\n",+ options: .regularExpression)++ do {+ let parsed = try AttributedString(+ markdown: presentationSource,+ options: .init(+ interpretedSyntax: .full,+ failurePolicy: .returnPartiallyParsedIfPossible))+ guard !containsUnsupportedBlock(in: parsed) else { return fallback(source) }++ let output = NSMutableAttributedString()+ var previousBlock: Block?++ for run in parsed.runs {+ let block = block(for: run.presentationIntent)+ if block != previousBlock {+ appendSeparator(to: output, previous: previousBlock, next: block)+ appendPrefix(for: block.kind, to: output)+ if block.kind == .thematicBreak {+ output.append(NSAttributedString(+ string: "────────────────",+ attributes: attributes(+ inlineIntent: nil,+ link: nil,+ block: block.kind)))+ }+ previousBlock = block+ }++ guard block.kind != .thematicBreak else { continue }+ let text = String(parsed[run.range].characters)+ guard !text.isEmpty else { continue }+ output.append(NSAttributedString(+ string: text,+ attributes: attributes(+ inlineIntent: run.inlinePresentationIntent,+ link: run.link,+ block: block.kind)))+ }++ guard output.length > 0 else { return fallback(source) }+ return Result(attributedString: output, usedFallback: false)+ } catch {+ return fallback(source)+ }+ }++ public func plainText(_ source: String) -> String {+ render(source).attributedString.string+ }++ private func requiresRawFallback(_ source: String) -> Bool {+ let fenceCount = source.components(separatedBy: "```").count - 1+ if !fenceCount.isMultiple(of: 2) { return true }+ if source.range(+ of: #"</?[A-Za-z][^>]*>"#,+ options: .regularExpression) != nil {+ return true+ }+ return source.range(+ of: #"!\[[^\]]*\]\([^\)]*\)"#,+ options: .regularExpression) != nil+ }++ private func containsUnsupportedBlock(in parsed: AttributedString) -> Bool {+ parsed.runs.contains { run in+ run.presentationIntent?.components.contains { component in+ switch component.kind {+ case .table, .tableHeaderRow, .tableRow, .tableCell:+ return true+ default:+ return false+ }+ } == true+ }+ }++ private func block(for intent: PresentationIntent?) -> Block {+ guard let components = intent?.components, let leaf = components.first else {+ return Block(identity: 0, kind: .paragraph)+ }++ var headingLevel: Int?+ var code = false+ var quote = false+ var thematicBreak = false+ var ordinal: Int?+ var ordered = false+ var unordered = false+ var listDepth = 0++ for component in components {+ switch component.kind {+ case .header(let level): headingLevel = level+ case .codeBlock: code = true+ case .blockQuote: quote = true+ case .thematicBreak: thematicBreak = true+ case .listItem(let itemOrdinal): ordinal = itemOrdinal+ case .orderedList:+ ordered = true+ listDepth += 1+ case .unorderedList:+ unordered = true+ listDepth += 1+ default: break+ }+ }++ let kind: BlockKind+ if thematicBreak {+ kind = .thematicBreak+ } else if let headingLevel {+ kind = .heading(headingLevel)+ } else if code {+ kind = .code+ } else if ordered, let ordinal {+ kind = .orderedList(ordinal: ordinal, indent: max(0, listDepth - 1))+ } else if unordered {+ kind = .unorderedList(indent: max(0, listDepth - 1))+ } else if quote {+ kind = .quote+ } else {+ kind = .paragraph+ }+ return Block(identity: leaf.identity, kind: kind)+ }++ private func appendSeparator(+ to output: NSMutableAttributedString,+ previous: Block?,+ next: Block+ ) {+ guard let previous else { return }+ let adjacentListItems = previous.kind.isList && next.kind.isList+ let requiredNewlines = adjacentListItems ? 1 : 2+ let trailingNewlines = output.string.reversed().prefix { $0 == "\n" }.count+ guard trailingNewlines < requiredNewlines else { return }+ output.append(NSAttributedString(+ string: String(repeating: "\n", count: requiredNewlines - trailingNewlines),+ attributes: baseAttributes()))+ }++ private func appendPrefix(for block: BlockKind, to output: NSMutableAttributedString) {+ let prefix: String+ switch block {+ case .unorderedList:+ prefix = "•\t"+ case .orderedList(let ordinal, _):+ prefix = "\(ordinal).\t"+ case .quote:+ prefix = "│\t"+ default:+ return+ }+ output.append(NSAttributedString(+ string: prefix,+ attributes: attributes(inlineIntent: nil, link: nil, block: block)))+ }++ private func attributes(+ inlineIntent: InlinePresentationIntent?,+ link: URL?,+ block: BlockKind+ ) -> [NSAttributedString.Key: Any] {+ var values = baseAttributes()+ values[.paragraphStyle] = paragraphStyle(for: block)+ values[.font] = font(for: block, inlineIntent: inlineIntent)++ if block == .quote {+ values[.foregroundColor] = NSColor.secondaryLabelColor+ }+ if block == .code || inlineIntent?.contains(.code) == true {+ values[.backgroundColor] = NSColor.controlBackgroundColor+ }+ if inlineIntent?.contains(.strikethrough) == true {+ values[.strikethroughStyle] = NSUnderlineStyle.single.rawValue+ }+ if link != nil {+ values[.foregroundColor] = NSColor.linkColor+ values[.underlineStyle] = NSUnderlineStyle.single.rawValue+ }+ return values+ }++ private func baseAttributes() -> [NSAttributedString.Key: Any] {+ [+ .font: NSFont.systemFont(ofSize: NSFont.systemFontSize),+ .foregroundColor: NSColor.labelColor,+ .paragraphStyle: paragraphStyle(for: .paragraph),+ ]+ }++ private func font(+ for block: BlockKind,+ inlineIntent: InlinePresentationIntent?+ ) -> NSFont {+ if block == .code || inlineIntent?.contains(.code) == true {+ return NSFont.monospacedSystemFont(+ ofSize: NSFont.systemFontSize - 0.5,+ weight: .regular)+ }++ let size: CGFloat+ let baseWeight: NSFont.Weight+ switch block {+ case .heading(let level):+ size = max(NSFont.systemFontSize + 1, 22 - CGFloat(level - 1) * 2)+ baseWeight = .semibold+ default:+ size = NSFont.systemFontSize+ baseWeight = .regular+ }++ let stronglyEmphasized = inlineIntent?.contains(.stronglyEmphasized) == true+ let emphasized = inlineIntent?.contains(.emphasized) == true+ var font = NSFont.systemFont(+ ofSize: size,+ weight: stronglyEmphasized ? .semibold : baseWeight)+ if emphasized {+ let descriptor = font.fontDescriptor.withSymbolicTraits(.italic)+ font = NSFont(descriptor: descriptor, size: size) ?? font+ }+ return font+ }++ private func paragraphStyle(for block: BlockKind) -> NSParagraphStyle {+ let style = NSMutableParagraphStyle()+ style.lineSpacing = 3+ style.paragraphSpacing = 6++ switch block {+ case .heading:+ style.paragraphSpacingBefore = 8+ style.paragraphSpacing = 4+ case .code:+ style.firstLineHeadIndent = 10+ style.headIndent = 10+ style.tailIndent = -10+ style.paragraphSpacingBefore = 6+ style.paragraphSpacing = 6+ style.lineSpacing = 2+ case .quote:+ style.firstLineHeadIndent = 4+ style.headIndent = 20+ style.tailIndent = -8+ style.tabStops = [NSTextTab(textAlignment: .left, location: 16)]+ case .unorderedList(let indent), .orderedList(_, let indent):+ let base = CGFloat(22 + indent * 18)+ style.firstLineHeadIndent = CGFloat(indent * 18)+ style.headIndent = base+ style.tabStops = [NSTextTab(textAlignment: .left, location: base)]+ style.paragraphSpacing = 2+ case .thematicBreak:+ style.alignment = .center+ style.paragraphSpacingBefore = 8+ style.paragraphSpacing = 8+ case .paragraph:+ break+ }+ return style+ }++ private func fallback(_ source: String) -> Result {+ Result(+ attributedString: NSAttributedString(+ string: source,+ attributes: baseAttributes()),+ usedFallback: true)+ }+}diff --git a/Sources/TurboFieldfareApp/MacPresentation/TurboFieldfareMacTheme.swift b/Sources/TurboFieldfareApp/MacPresentation/TurboFieldfareMacTheme.swiftnew file mode 100644index 00000000..8bf98dd4--- /dev/null+++ b/Sources/TurboFieldfareApp/MacPresentation/TurboFieldfareMacTheme.swift@@ -0,0 +1,12 @@+import AppKit+import SwiftUI++public enum TurboFieldfareMacTheme {+ public static let accentNSColor = NSColor(+ srgbRed: 106.0 / 255.0,+ green: 186.0 / 255.0,+ blue: 113.0 / 255.0,+ alpha: 1)++ public static let accentColor = Color(nsColor: accentNSColor)+}diff --git a/Sources/TurboFieldfareCLI/Args.swift b/Sources/TurboFieldfareCLI/Args.swiftindex 53c3f3e5..6fb33094 100644--- a/Sources/TurboFieldfareCLI/Args.swift+++ b/Sources/TurboFieldfareCLI/Args.swift@@ -1,6 +1,7 @@public struct Args: Equatable, Sendable {public var model: String- public var prompt: String+ public var prompt: String?+ public var messagesFile: String?public var maxNew: Intpublic var maxContext: Intpublic var temperature: Float@@ -12,10 +13,11 @@ public struct Args: Equatable, Sendable {public var quiet: Boolpublic init(model: String,- prompt: String,+ prompt: String? = nil,+ messagesFile: String? = nil,maxNew: Int = 1_024,maxContext: Int = 4096,- temperature: Float = 1.0,+ temperature: Float = 0.2,topK: Int? = 64,topP: Float? = 0.95,repetitionPenalty: Float = 1.0,@@ -24,6 +26,7 @@ public struct Args: Equatable, Sendable {quiet: Bool = false) {self.model = modelself.prompt = prompt+ self.messagesFile = messagesFileself.maxNew = maxNewself.maxContext = maxContextself.temperature = temperature@@ -42,6 +45,8 @@ public enum ArgsError: Error, Equatable, CustomStringConvertible {case missingValue(flag: String)case invalidValue(flag: String, value: String)case requiredMissing(String)+ case mutuallyExclusive(String, String)+ case modeMissingpublic var description: String {switch self {@@ -50,24 +55,27 @@ public enum ArgsError: Error, Equatable, CustomStringConvertible {case .missingValue(let flag): return "missing value for \(flag)"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"}}}extension Args {public static let usage = """- TurboFieldfareCLI — text completion with Gemma 4 26B-A4B+ TurboFieldfareCLI — Gemma 4 26B-A4B text generation- usage: TurboFieldfareCLI --model <dir> --prompt <string> [options]+ usage: TurboFieldfareCLI --model <dir> (--prompt <string> | --messages-file <path>) [options]required:--model <dir> Path to a .gturbo model directory.--prompt <string> Raw-completion prompt.+ --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 1.0; 0 = greedy).+ --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).@@ -80,9 +88,10 @@ extension Args {public static func parse(_ argv: [String]) throws -> Args {var model: String?var prompt: String?+ var messagesFile: String?var maxNew = 1_024var maxContext = 4096- var temperature: Float = 1.0+ var temperature: Float = 0.2var topK: Int? = 64var topP: Float? = 0.95var repetitionPenalty: Float = 1.0@@ -103,6 +112,8 @@ extension Args {model = try takeValue(argv, &index, flag: flag)case "--prompt":prompt = try takeValue(argv, &index, flag: flag)+ case "--messages-file":+ messagesFile = try takeValue(argv, &index, flag: flag)case "--max-new":let value = try takeValue(argv, &index, flag: flag)guard let parsed = Int(value), parsed > 0 else {@@ -153,7 +164,10 @@ extension Args {}guard let model else { throw ArgsError.requiredMissing("--model") }- guard let prompt else { throw ArgsError.requiredMissing("--prompt") }+ if prompt != nil && messagesFile != nil {+ throw ArgsError.mutuallyExclusive("--prompt", "--messages-file")+ }+ if prompt == nil && messagesFile == nil { throw ArgsError.modeMissing }if temperature > 0, topK == nil, let topP, topP < 1 {throw ArgsError.invalidValue(flag: "--top-p",@@ -161,6 +175,7 @@ extension Args {}return Args(model: model,prompt: prompt,+ messagesFile: messagesFile,maxNew: maxNew,maxContext: maxContext,temperature: temperature,diff --git a/Sources/TurboFieldfareCLI/Run.swift b/Sources/TurboFieldfareCLI/Run.swiftindex 69b367f0..2a841b83 100644--- a/Sources/TurboFieldfareCLI/Run.swift+++ b/Sources/TurboFieldfareCLI/Run.swift@@ -2,6 +2,11 @@ import Foundationimport Metalimport TurboFieldfare+private struct MessageJSON: Decodable {+ let role: String+ let content: String+}+public struct RunResult: Equatable, Sendable {public let exitCode: Int32public init(exitCode: Int32) { self.exitCode = exitCode }@@ -11,8 +16,36 @@ public func run(args: Args,stdout: FileHandle = .standardOutput,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 rendered = try tokenizer.applyChatTemplate(messages)+ promptIds = tokenizer.encode(rendered, addBOS: false)+ } else {+ return errored(stderr, "one of --prompt or --messages-file is required", 2)+ }+ guard !promptIds.isEmpty else { return errored(stderr, "empty prompt", 2) }+ guard 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: args.maxNew,+ maxNewTokens: effectiveMaxNew,temperature: args.temperature,topK: args.topK,topP: args.topP,@@ -22,16 +55,6 @@ public func run(args: Args,extraStopTokens: [])let runtime = RuntimeConfiguration(forceLogitsHead: !config.isPureGreedy)- let modelURL = URL(fileURLWithPath: args.model)- let tokenizer = try await GFTokenizer.load(forModelDirectory: modelURL)- let promptIds = tokenizer.encode(args.prompt, addBOS: true)- guard !promptIds.isEmpty else { return errored(stderr, "empty prompt", 2) }- guard promptIds.count + args.maxNew <= args.maxContext else {- return errored(- stderr,- "context overflow: prompt \(promptIds.count) + maxNew \(args.maxNew) exceeds maxContext \(args.maxContext)",- 2)- }guard MTLCreateSystemDefaultDevice() != nil else {return errored(stderr, "no Metal device", 1)diff --git a/Sources/TurboFieldfareDecodeProtocol/DecodeProtocol.swift b/Sources/TurboFieldfareDecodeProtocol/DecodeProtocol.swiftindex 1501ac13..8276fb98 100644--- a/Sources/TurboFieldfareDecodeProtocol/DecodeProtocol.swift+++ b/Sources/TurboFieldfareDecodeProtocol/DecodeProtocol.swift@@ -5,7 +5,6 @@ public struct DecodeRuntimeOptions: Codable, Sendable, Equatable {public var expertCachePolicy: Stringpublic var prefillEnabled: Boolpublic var prefillChunkTokens: Int- public var turboQuantKVEnabled: Boolpublic var rdadvisePolicy: Stringpublic var modelVerification: String@@ -13,14 +12,12 @@ public struct DecodeRuntimeOptions: Codable, Sendable, Equatable {expertCachePolicy: String = "lfu",prefillEnabled: Bool = true,prefillChunkTokens: Int = 128,- turboQuantKVEnabled: Bool = false,rdadvisePolicy: String = "off",modelVerification: String = "full-sha256") {self.expertCacheSlots = expertCacheSlotsself.expertCachePolicy = expertCachePolicyself.prefillEnabled = prefillEnabledself.prefillChunkTokens = prefillChunkTokens- self.turboQuantKVEnabled = turboQuantKVEnabledself.rdadvisePolicy = rdadvisePolicyself.modelVerification = modelVerification}diff --git a/Sources/TurboFieldfareDecodeService/Entry.swift b/Sources/TurboFieldfareDecodeService/Entry.swiftindex 2d8b5f1f..202be99e 100644--- a/Sources/TurboFieldfareDecodeService/Entry.swift+++ b/Sources/TurboFieldfareDecodeService/Entry.swift@@ -168,7 +168,6 @@ import TurboFieldfareDecodeProtocolexpertCachePolicy: cachePolicy,prefillEnabled: options.prefillEnabled,prefillChunkTokens: options.prefillChunkTokens,- turboQuantKVEnabled: options.turboQuantKVEnabled,rdadvisePolicy: rdadvisePolicy,modelVerification: modelVerification)try resolved.validate()diff --git a/Sources/TurboFieldfareRepack/Core/Remote/RemoteStreamingRepacker.swift b/Sources/TurboFieldfareRepack/Core/Remote/RemoteStreamingRepacker.swiftindex f88eaa22..5fc40441 100644--- a/Sources/TurboFieldfareRepack/Core/Remote/RemoteStreamingRepacker.swift+++ b/Sources/TurboFieldfareRepack/Core/Remote/RemoteStreamingRepacker.swift@@ -263,6 +263,8 @@ public final class RemoteStreamingRepacker {("tokenizer.json", 64 * 1024 * 1024, true),("tokenizer_config.json", 4 * 1024 * 1024, true),("special_tokens_map.json", 1 * 1024 * 1024, false),+ ("chat_template.jinja", 4 * 1024 * 1024, false),+ ("chat_template.json", 4 * 1024 * 1024, false),]for file in tokenizerFiles {try Task.checkCancellation()diff --git a/Sources/TurboFieldfareRepack/Core/Remote/SupportedModelSource.swift b/Sources/TurboFieldfareRepack/Core/Remote/SupportedModelSource.swiftindex cde9f9e5..f9e35c30 100644--- a/Sources/TurboFieldfareRepack/Core/Remote/SupportedModelSource.swift+++ b/Sources/TurboFieldfareRepack/Core/Remote/SupportedModelSource.swift@@ -1,11 +1,13 @@import Foundationpublic enum SupportedModelSource {- public static let displayName = "gemma-4-26B-A4B-TurboQuant-MLX-4bit"- public static let repoID = "majentik/gemma-4-26B-A4B-TurboQuant-MLX-4bit"- public static let revision = "cc499c86a958ea7f05cffaa91c7e7243240dabbe"- public static let approximateDownloadBytes: UInt64 = 14_952_958_284- public static let installedBytes: UInt64 = 14_527_372_034+ public static let displayName = "Gemma 4 26B-A4B IT 4-bit"+ public static let repoID = "mlx-community/gemma-4-26b-a4b-it-4bit"+ public static let revision = "0d77464eeb233a2da68ebf9d7dc4edaac7db956d"+ public static let sourceIndexSHA256 =+ "bf198c9f5ea6462addca1966e5dd669c407537a876e82cf06db9084c5c850b13"+ public static let approximateDownloadBytes: UInt64 = 14_620_479_420+ public static let installedBytes: UInt64 = 14_291_921_884public static let reserveBytes: UInt64 = 1_073_741_824public static func installOptions(outputDirectory: URL,diff --git a/Sources/TurboFieldfareRepack/Core/Verification/SourceFingerprint.swift b/Sources/TurboFieldfareRepack/Core/Verification/SourceFingerprint.swiftindex 85dc9da3..a447ce73 100644--- a/Sources/TurboFieldfareRepack/Core/Verification/SourceFingerprint.swift+++ b/Sources/TurboFieldfareRepack/Core/Verification/SourceFingerprint.swift@@ -2,14 +2,13 @@ import Foundation/// Snapshot fingerprints pinned by the project. Adding a new entry means the/// importer has been validated against a fresh upload of the source.-enum SourceFingerprint {- static let knownFingerprints: [String: String] = [- "majentik/gemma-4-26B-A4B-TurboQuant-MLX-4bit":- "5455e83705bbdd4e3702c7d4f9d49d4900e84533036628f74500538075dd5c80"+public enum SourceFingerprint {+ public static let knownFingerprints: [String: String] = [+ SupportedModelSource.repoID: SupportedModelSource.sourceIndexSHA256,]/// Returns the recognised model ID for a given index.json SHA-256, or nil.- static func modelID(forIndexSha256 sha256Hex: String) -> String? {+ public static func modelID(forIndexSha256 sha256Hex: String) -> String? {for (id, sha) in knownFingerprints where sha == sha256Hex { return id }return nil}diff --git a/Sources/TurboFieldfareValidation/Support/Reference/KVCache/TurboQuantWht.swift b/Sources/TurboFieldfareValidation/Support/Reference/KVCache/TurboQuantWht.swiftdeleted file mode 100644index 0f0ce80c..00000000--- a/Sources/TurboFieldfareValidation/Support/Reference/KVCache/TurboQuantWht.swift+++ /dev/null@@ -1,106 +0,0 @@-import Foundation--/// Recursive Walsh-Hadamard transform (`/sqrt(2)` per stage). Implemented-/// divide-and-conquer style — splits the input into halves, recurses, then-/// combines. The kernel uses an iterative stride-doubling butterfly inside-/// SIMD threadgroups. Different control flow, different summation order.-public enum WhtRef {- public static func apply(_ x: [Float]) -> [Float] {- let d = x.count- precondition(d > 0 && (d & (d - 1)) == 0, "D must be a power of two")- if d == 1 { return x }- return walsh(x)- }-- private static func walsh(_ x: [Float]) -> [Float] {- let n = x.count- if n == 1 { return x }- let half = n / 2- // Split into low / high halves, recurse, then combine.- let lo = walsh(Array(x[0..<half]))- let hi = walsh(Array(x[half..<n]))- let invSqrt2: Float = 1.0 / Float(2.0).squareRoot()- var y = [Float](repeating: 0, count: n)- for i in 0..<half {- y[i] = (lo[i] + hi[i]) * invSqrt2- y[half + i] = (lo[i] - hi[i]) * invSqrt2- }- return y- }-}--public enum TurboQuantRef {- private static let codebook: [Float] = [- -2.7326, -2.0690, -1.6181, -1.2562,- -0.9424, -0.6568, -0.3881, -0.1284,- 0.1284, 0.3881, 0.6568, 0.9424,- 1.2562, 1.6181, 2.0690, 2.7326,- ]-- public static func materializePackedCache(- _ cache: [UInt8],- tokenCount: Int,- headDim: Int,- numHeads: Int,- bytesPerHead: Int,- bytesPerToken: Int,- packedOffset: Int,- scaleOffset: Int,- layer: UInt32 = 0,- rotationSeed: UInt32 = 0,- applyRotation: Bool = false- ) -> [Float] {- precondition(tokenCount >= 0 && headDim > 0 && numHeads > 0)- precondition(cache.count >= tokenCount * bytesPerToken)- var output = [Float](repeating: 0, count: tokenCount * numHeads * headDim)-- for token in 0..<tokenCount {- for head in 0..<numHeads {- let cacheBase = token * bytesPerToken + head * bytesPerHead- let scaleBits = UInt16(cache[cacheBase + scaleOffset])- | (UInt16(cache[cacheBase + scaleOffset + 1]) << 8)- let scale = Float(Float16(bitPattern: scaleBits))- var transformed = [Float](repeating: 0, count: headDim)- for dimension in 0..<headDim {- let byte = cache[cacheBase + packedOffset + dimension / 2]- let index = dimension.isMultiple(of: 2)- ? Int(byte & 0x0F)- : Int(byte >> 4)- transformed[dimension] = Float(Float16(codebook[index] * scale))- }-- let restored = WhtRef.apply(transformed)- let outputBase = (token * numHeads + head) * headDim- for dimension in 0..<headDim {- let value = applyRotation- && rotationSign(layer: layer,- head: UInt32(head),- dimension: UInt32(dimension),- seed: rotationSeed)- ? -restored[dimension]- : restored[dimension]- output[outputBase + dimension] = Float(Float16(value))- }- }- }- return output- }-- private static func rotationSign(layer: UInt32,- head: UInt32,- dimension: UInt32,- seed: UInt32) -> Bool {- var value = UInt64(seed)- value ^= UInt64(layer) &* 0x9E37_79B9_7F4A_7C15- value ^= UInt64(head) &* 0xBF58_476D_1CE4_E5B9- value ^= UInt64(dimension) &* 0x94D0_49BB_1331_11EB- return mix64(value) >> 63 != 0- }-- private static func mix64(_ input: UInt64) -> UInt64 {- var value = input- value = (value ^ (value >> 30)) &* 0xBF58_476D_1CE4_E5B9- value = (value ^ (value >> 27)) &* 0x94D0_49BB_1331_11EB- return value ^ (value >> 31)- }-}diff --git a/Sources/TurboFieldfareValidation/Support/Reference/Primitives/Wht.swift b/Sources/TurboFieldfareValidation/Support/Reference/Primitives/Wht.swiftnew file mode 100644index 00000000..c6ecc12e--- /dev/null+++ b/Sources/TurboFieldfareValidation/Support/Reference/Primitives/Wht.swift@@ -0,0 +1,25 @@+import Foundation++public enum WhtRef {+ public static func apply(_ x: [Float]) -> [Float] {+ let d = x.count+ precondition(d > 0 && (d & (d - 1)) == 0, "D must be a power of two")+ if d == 1 { return x }+ return walsh(x)+ }++ private static func walsh(_ x: [Float]) -> [Float] {+ let n = x.count+ if n == 1 { return x }+ let half = n / 2+ let lo = walsh(Array(x[0..<half]))+ let hi = walsh(Array(x[half..<n]))+ let invSqrt2: Float = 1.0 / Float(2.0).squareRoot()+ var y = [Float](repeating: 0, count: n)+ for i in 0..<half {+ y[i] = (lo[i] + hi[i]) * invSqrt2+ y[half + i] = (lo[i] - hi[i]) * invSqrt2+ }+ return y+ }+}diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdindex 15cacd51..b6607a3e 100644--- a/THIRD_PARTY_NOTICES.md+++ b/THIRD_PARTY_NOTICES.md@@ -12,12 +12,13 @@ versions included in that product.## Model weights-Model weights are not included in this repository. The installer downloads a-pinned revision of-[`majentik/gemma-4-26B-A4B-TurboQuant-MLX-4bit`](https://huggingface.co/majentik/gemma-4-26B-A4B-TurboQuant-MLX-4bit)-and repacks it locally. The model card labels that checkpoint Apache-2.0 and-identifies `google/gemma-4-26B-A4B` as its base model. Google publishes Gemma 4-under the+Model weights are not included in this repository. The installer downloads+the pinned revision+`0d77464eeb233a2da68ebf9d7dc4edaac7db956d` of+[`mlx-community/gemma-4-26b-a4b-it-4bit`](https://huggingface.co/mlx-community/gemma-4-26b-a4b-it-4bit)+and repacks it locally. Its model card describes it as an Apache-2.0+quantization of Google's Gemma 4 26B-A4B instruction checkpoint.+Google publishes Gemma 4 under the[Apache License 2.0](https://ai.google.dev/gemma/apache_2).Downloaded weights remain a separate work governed by their source terms. Dodiff --git a/Tests/TurboFieldfare/Core/CLI/CLIArgumentsTests.swift b/Tests/TurboFieldfare/Core/CLI/CLIArgumentsTests.swiftindex ce1e5600..4435cba3 100644--- a/Tests/TurboFieldfare/Core/CLI/CLIArgumentsTests.swift+++ b/Tests/TurboFieldfare/Core/CLI/CLIArgumentsTests.swift@@ -6,9 +6,10 @@ import Testinglet arguments = try Args.parse(["--model", "m.gturbo", "--prompt", "hi"])#expect(arguments.model == "m.gturbo")#expect(arguments.prompt == "hi")+ #expect(arguments.messagesFile == nil)#expect(arguments.maxNew == 1_024)#expect(arguments.maxContext == 4096)- #expect(arguments.temperature == 1.0)+ #expect(arguments.temperature == 0.2)#expect(arguments.topK == 64)#expect(arguments.topP == 0.95)#expect(arguments.repetitionPenalty == 1)@@ -61,7 +62,7 @@ import Testing@Test func helpListsExactlyThePublicOptions() {let expected: Set<String> = [- "--model", "--prompt", "--max-new", "--max-context",+ "--model", "--prompt", "--messages-file", "--max-new", "--max-context","--temperature", "--top-k", "--top-p", "--repetition-penalty","--seed", "--stop", "--quiet", "--help",]@@ -71,7 +72,7 @@ import Testing}@Test func unsupportedSelectorsAreRejected() {- for flag in ["--messages-file", "--runtime-profile", "--experiment-id", "-h"] {+ for flag in ["--runtime-profile", "--experiment-id", "-h"] {#expect(throws: ArgsError.unknownFlag(flag)) {_ = try Args.parse(["--model", "m.gturbo", "--prompt", "hi", flag])}@@ -82,8 +83,25 @@ import Testing#expect(throws: ArgsError.requiredMissing("--model")) {_ = try Args.parse(["--prompt", "hi"])}- #expect(throws: ArgsError.requiredMissing("--prompt")) {+ #expect(throws: ArgsError.modeMissing) {_ = try Args.parse(["--model", "m.gturbo"])}}++ @Test func messagesFileSelectsChatMode() throws {+ let arguments = try Args.parse([+ "--model", "m.gturbo", "--messages-file", "chat.json",+ ])+ #expect(arguments.prompt == nil)+ #expect(arguments.messagesFile == "chat.json")+ }++ @Test func promptAndMessagesFileAreMutuallyExclusive() {+ #expect(throws: ArgsError.mutuallyExclusive("--prompt", "--messages-file")) {+ _ = try Args.parse([+ "--model", "m.gturbo", "--prompt", "hi",+ "--messages-file", "chat.json",+ ])+ }+ }}diff --git a/Tests/TurboFieldfare/Core/Infrastructure/ModelIO/ManifestReaderTests.swift b/Tests/TurboFieldfare/Core/Infrastructure/ModelIO/ManifestReaderTests.swiftindex 1a55d0ff..8a66493e 100644--- a/Tests/TurboFieldfare/Core/Infrastructure/ModelIO/ManifestReaderTests.swift+++ b/Tests/TurboFieldfare/Core/Infrastructure/ModelIO/ManifestReaderTests.swift@@ -11,7 +11,8 @@ import Foundation"turboQuantKV": false,"aneSharedExpert": false],archOverrides: [String: Any] = [:],- filesOverride: [String: [String: Any]]? = nil) throws+ filesOverride: [String: [String: Any]]? = nil,+ config: ArchConfig = .gemma4Toy()) throws-> (URL, ArchConfig) {let dir = FileManager.default.temporaryDirectory.appendingPathComponent("gturbo-manifest-test-\(UUID().uuidString)")@@ -20,7 +21,7 @@ import Foundationat: dir.appendingPathComponent("packed_experts"),withIntermediateDirectories: true)- let toy = ArchConfig.gemma4Toy()+ let toy = configvar archDict: [String: Any] = ["hiddenSize": toy.hiddenSize,"ffnIntermediate": toy.intermediateSize,@@ -79,6 +80,26 @@ import Foundationreturn (dir, toy)}+ static func quant(sharedExpertBits: Int = 4,+ routerBits: Int = 8) -> [String: Any] {+ func slot(_ bits: Int) -> [String: Any] {+ [+ "weightBits": bits,+ "scheme": "affine",+ "scaleType": "bf16",+ "biasType": "bf16",+ "groupSize": Quantization.groupSize,+ ]+ }+ return [+ "embedding": slot(4),+ "attention": slot(4),+ "router": slot(routerBits),+ "sharedExpert": slot(sharedExpertBits),+ "routedExpert": slot(4),+ ]+ }+@Test func loadsValidManifest() throws {let (dir, toy) = try Self.writeToyManifest()defer { try? FileManager.default.removeItem(at: dir) }@@ -150,6 +171,61 @@ import Foundation}}+ @Test func removedTurboQuantFlagIsRejected() throws {+ let (dir, toy) = try Self.writeToyManifest(flags: ["streamingPresent": true,+ "turboQuantKV": true,+ "aneSharedExpert": false])+ defer { try? FileManager.default.removeItem(at: dir) }+ #expect {+ _ = try ManifestReader.load(directoryURL: dir, expecting: toy)+ } throws: { error in+ guard case ModelError.indexCorrupt(let detail) = error else { return false }+ return detail.contains("removed TurboQuant KV")+ }+ }++ @Test func productionManifestRequiresQuantMetadata() throws {+ let (dir, config) = try Self.writeToyManifest(config: .gemma4_26B_A4B)+ defer { try? FileManager.default.removeItem(at: dir) }+ #expect {+ _ = try ManifestReader.load(directoryURL: dir, expecting: config)+ } throws: { error in+ guard case ModelError.indexCorrupt(let detail) = error else { return false }+ return detail.contains("manifest.quant is required")+ }+ }++ @Test func productionManifestAcceptsInt4SharedExpert() throws {+ let (dir, config) = try Self.writeToyManifest(+ ["quant": Self.quant(sharedExpertBits: 4)],+ config: .gemma4_26B_A4B)+ defer { try? FileManager.default.removeItem(at: dir) }+ let manifest = try ManifestReader.load(directoryURL: dir, expecting: config)+ #expect(manifest.quant?.sharedExpert.weightBits == 4)+ }++ @Test func productionManifestAcceptsHistoricalInt8SharedExpert() throws {+ let (dir, config) = try Self.writeToyManifest(+ ["quant": Self.quant(sharedExpertBits: 8)],+ config: .gemma4_26B_A4B)+ defer { try? FileManager.default.removeItem(at: dir) }+ let manifest = try ManifestReader.load(directoryURL: dir, expecting: config)+ #expect(manifest.quant?.sharedExpert.weightBits == 8)+ }++ @Test func productionManifestRejectsUnsupportedQuantMetadata() throws {+ let (dir, config) = try Self.writeToyManifest(+ ["quant": Self.quant(sharedExpertBits: 3, routerBits: 4)],+ config: .gemma4_26B_A4B)+ defer { try? FileManager.default.removeItem(at: dir) }+ #expect {+ _ = try ManifestReader.load(directoryURL: dir, expecting: config)+ } throws: { error in+ guard case ModelError.indexCorrupt(let detail) = error else { return false }+ return detail.contains("unsupported quantization")+ }+ }+@Test func archMismatchThrowsArchMismatch() throws {let (dir, toy) = try Self.writeToyManifest(archOverrides: ["hiddenSize": 4096])defer { try? FileManager.default.removeItem(at: dir) }diff --git a/Tests/TurboFieldfare/Core/Kernels/Attention/AttentionTests.swift b/Tests/TurboFieldfare/Core/Kernels/Attention/AttentionTests.swiftindex b337b324..a782ca37 100644--- a/Tests/TurboFieldfare/Core/Kernels/Attention/AttentionTests.swift+++ b/Tests/TurboFieldfare/Core/Kernels/Attention/AttentionTests.swift@@ -357,157 +357,6 @@ import TurboFieldfareValidationSupport"ring SWA kernel vs linear SWA kernel rel=\(rel)")}- @Test func attentionSWA_turboQuantPackedKV_matchesMaterializedReference() throws {- try Self.runTurboQuantPackedKVAndCompare(- headDim: 256,- numQHeads: 4,- numKVHeads: 2,- seqLen: 16,- mode: .swa(window: 8),- seed: 0x178)- }-- private static func runTurboQuantPackedKVAndCompare(- headDim: Int,- numQHeads: Int,- numKVHeads: Int,- seqLen: Int,- mode: Mode,- seed: UInt64- ) throws {- let window: Int?- let kvStart: UInt32- switch mode {- case .swa(let w):- window = w- kvStart = UInt32(seqLen > w ? seqLen - w : 0)- case .full:- window = nil- kvStart = 0- }- let qCount = numQHeads * headDim- let kvCount = seqLen * numKVHeads * headDim- let pairs = seqLen * numKVHeads- let layer: UInt32 = 3- let rotationSeed: UInt32 = 0xC0FFEE-- var rng = SeedTree(seed).key("attn-tq-kv-\(mode)-d\(headDim)")- let qFp32 = (0..<qCount).map { _ in rng.uniform(-0.5, 0.5) }- let kFp32 = (0..<kvCount).map { _ in rng.uniform(-0.5, 0.5) }- let vFp32 = (0..<kvCount).map { _ in rng.uniform(-0.5, 0.5) }- let qFp16 = qFp32.map { Float16($0) }- let kFp16 = kFp32.map { Float16($0) }- let vFp16 = vFp32.map { Float16($0) }-- let keyLayout = TurboQuantKVLayout.role(mode: .k4v4NormCorrected,- headDim: headDim,- numKVHeads: numKVHeads)- let valueLayout = TurboQuantKVLayout.role(mode: .k4v4NormCorrected,- headDim: headDim,- numKVHeads: numKVHeads)-- let ctx = try MetalContext()- let quant = try TurboQuantQuant(context: ctx)- let attention = try Attention(context: ctx)-- guard let qBuf = Fp16Buffer.make(ctx.device, halves: qFp16),- let kBuf = Fp16Buffer.make(ctx.device, halves: kFp16),- let vBuf = Fp16Buffer.make(ctx.device, halves: vFp16),- let outPackedSplit = Fp16Buffer.make(ctx.device, count: qCount),- let keyCache = ctx.device.makeBuffer(length: keyLayout.bytesPerToken * seqLen,- options: .storageModeShared),- let valueCache = ctx.device.makeBuffer(length: valueLayout.bytesPerToken * seqLen,- options: .storageModeShared) else {- Issue.record("alloc failed"); return- }-- let whtParams = TurboQuantWHTParams(numHeads: UInt32(numKVHeads),- layer: layer,- rotationSeed: rotationSeed,- applyRotation: true)- let keyWrite = TurboQuantKVWriteParams(d: UInt32(headDim),- numHeads: UInt32(numKVHeads),- roleLayout: keyLayout)- let valueWrite = TurboQuantKVWriteParams(d: UInt32(headDim),- numHeads: UInt32(numKVHeads),- roleLayout: valueLayout)- let attentionParams = AttentionTurboQuantKVParams(- headDim: UInt32(headDim),- numQHeads: UInt32(numQHeads),- numKVHeads: UInt32(numKVHeads),- seqLen: UInt32(seqLen),- kvStart: kvStart,- scale: 1.0,- layer: layer,- rotationSeed: rotationSeed,- keyLayout: keyLayout,- valueLayout: valueLayout)-- let cb = ctx.queue.makeCommandBuffer()!- quant.encodeKVWriteWHT(commandBuffer: cb,- x: kBuf,- cache: keyCache,- params: keyWrite,- whtParams: whtParams,- pairs: pairs)- quant.encodeKVWriteWHT(commandBuffer: cb,- x: vBuf,- cache: valueCache,- params: valueWrite,- whtParams: whtParams,- pairs: pairs)- attention.encodeTurboQuantSplit(commandBuffer: cb,- q: qBuf,- keyCache: keyCache,- valueCache: valueCache,- out: outPackedSplit,- params: attentionParams)- cb.commit()- cb.waitUntilCompleted()-- let actualSplit = Fp16Buffer.read(outPackedSplit, count: qCount)- let keyBytes = Array(UnsafeBufferPointer(- start: keyCache.contents().assumingMemoryBound(to: UInt8.self),- count: keyCache.length))- let valueBytes = Array(UnsafeBufferPointer(- start: valueCache.contents().assumingMemoryBound(to: UInt8.self),- count: valueCache.length))- let materializedKey = TurboQuantRef.materializePackedCache(- keyBytes,- tokenCount: seqLen,- headDim: headDim,- numHeads: numKVHeads,- bytesPerHead: keyLayout.bytesPerHead,- bytesPerToken: keyLayout.bytesPerToken,- packedOffset: keyLayout.packedOffsetPerHead,- scaleOffset: keyLayout.scaleOffsetPerHead,- layer: layer,- rotationSeed: rotationSeed,- applyRotation: true)- let materializedValue = TurboQuantRef.materializePackedCache(- valueBytes,- tokenCount: seqLen,- headDim: headDim,- numHeads: numKVHeads,- bytesPerHead: valueLayout.bytesPerHead,- bytesPerToken: valueLayout.bytesPerToken,- packedOffset: valueLayout.packedOffsetPerHead,- scaleOffset: valueLayout.scaleOffsetPerHead,- layer: layer,- rotationSeed: rotationSeed,- applyRotation: true)- let ref = AttentionRef.apply(q: qFp16.map { Float($0) },- k: materializedKey,- v: materializedValue,- headDim: headDim,- numQHeads: numQHeads,- numKVHeads: numKVHeads,- seqLen: seqLen,- window: window,- scale: 1.0)- let splitRel = RelError.compute(actual: actualSplit, reference: ref)- #expect(splitRel < 0.02, "packed TurboQuant split attention rel=\(splitRel)")- }// Full --------------------------------------------------------------------@@ -521,83 +370,7 @@ import TurboFieldfareValidationSupportseqLen: 128, mode: .full, seed: 0x175)}- @Test func attentionFull_mlxGeometryV2_distinctKV_stripeBoundaries() throws {- let ctx = try MetalContext()- let kernel = try Attention(context: ctx)- let headDim = 512- let numQHeads = 16- let numKVHeads = 2- let qCount = numQHeads * headDim- for seqLen in [1, 31, 32, 33, 257] {- var rng = SeedTree(UInt64(0x5200 + seqLen)).key("mlx-v2-distinct-kv")- let q = (0..<qCount).map { _ in Float16(rng.uniform(-0.25, 0.25)) }- let kvCount = seqLen * numKVHeads * headDim- let k = (0..<kvCount).map { _ in Float16(rng.uniform(-0.25, 0.25)) }- let v = (0..<kvCount).map { _ in Float16(rng.uniform(-0.25, 0.25)) }- guard let qBuf = Fp16Buffer.make(ctx.device, halves: q),- let kBuf = Fp16Buffer.make(ctx.device, halves: k),- let vBuf = Fp16Buffer.make(ctx.device, halves: v),- let outA = Fp16Buffer.make(ctx.device, count: qCount),- let outB = Fp16Buffer.make(ctx.device, count: qCount) else {- Issue.record("allocation failed at seqLen=\(seqLen)")- return- }-- for output in [outA, outB] {- guard let cb = ctx.queue.makeCommandBuffer() else {- Issue.record("command buffer failed")- return- }- kernel.encodeFull(commandBuffer: cb,- q: qBuf, k: kBuf, v: vBuf, out: output,- headDim: UInt32(headDim),- numQHeads: UInt32(numQHeads),- numKVHeads: UInt32(numKVHeads),- seqLen: UInt32(seqLen),- scale: 1.0)- cb.commit()- cb.waitUntilCompleted()- if let error = cb.error { throw error }- }-- let actualA = Fp16Buffer.read(outA, count: qCount)- let actualB = Fp16Buffer.read(outB, count: qCount)- #expect(actualA == actualB, "candidate output changed at seqLen=\(seqLen)")- let reference = AttentionRef.apply(q: q.map(Float.init),- k: k.map(Float.init),- v: v.map(Float.init),- headDim: headDim,- numQHeads: numQHeads,- numKVHeads: numKVHeads,- seqLen: seqLen,- window: nil,- scale: 1.0)- let rel = RelError.compute(actual: actualA, reference: reference)- #expect(rel < Tolerance.fp16ChainedReduction,- "candidate rel=\(rel) at seqLen=\(seqLen)")- }- }-- @Test func attentionFull_turboQuantPackedKV_matchesMaterializedReference() throws {- try Self.runTurboQuantPackedKVAndCompare(- headDim: 512,- numQHeads: 8,- numKVHeads: 1,- seqLen: 16,- mode: .full,- seed: 0x179)- }-- @Test func attentionFull_turboQuantPackedKV_realHeadShape_matchesMaterializedReference() throws {- try Self.runTurboQuantPackedKVAndCompare(- headDim: 512,- numQHeads: 16,- numKVHeads: 2,- seqLen: 16,- mode: .full,- seed: 0x17A)- }/// Generic aliasing coverage. Gemma 4 runtime uses distinct post-norm K/V.@Test func attentionFull_kvShared_smallShape() throws {diff --git a/Tests/TurboFieldfare/Core/Kernels/Attention/PrefillAttentionTests.swift b/Tests/TurboFieldfare/Core/Kernels/Attention/PrefillAttentionTests.swiftindex 2b8db37b..f8db64c2 100644--- a/Tests/TurboFieldfare/Core/Kernels/Attention/PrefillAttentionTests.swift+++ b/Tests/TurboFieldfare/Core/Kernels/Attention/PrefillAttentionTests.swift@@ -130,9 +130,6 @@ import TurboFieldfareValidationSupport}}- @Test func prefillTurboQuantPackedAttentionMatchesMaterializedDefaultKV() throws {- try Self.runTurboQuantPackedAndCompare()- }private static func makeFixture(start: Int,chunk: Int,@@ -244,179 +241,7 @@ import TurboFieldfareValidationSupportreturn compact}- private static func runTurboQuantPackedAndCompare() throws {- let headDim = 256- let qHeads = 4- let kvHeads = 2- let start = 5- let chunk = 3- let kvValid = start + chunk- let window = 6- let qStride = qHeads * headDim- let kvStride = kvHeads * headDim- let oStride = qStride- let layer: UInt32 = 2- let rotationSeed: UInt32 = 0xA11CE-- var rng = SeedTree(0xA910).key("prefill-tq-k4v4")- let q = (0..<(chunk * qStride)).map { _ in rng.uniform(-0.35, 0.35) }- let k = (0..<(kvValid * kvStride)).map { _ in rng.uniform(-0.35, 0.35) }- let v = (0..<(kvValid * kvStride)).map { _ in rng.uniform(-0.35, 0.35) }-- let keyLayout = TurboQuantKVLayout.role(mode: .k4v4NormCorrected,- headDim: headDim,- numKVHeads: kvHeads)- let valueLayout = TurboQuantKVLayout.role(mode: .k4v4NormCorrected,- headDim: headDim,- numKVHeads: kvHeads)-- let ctx = try MetalContext()- let prefill = try PrefillAttention(context: ctx)- let quant = try TurboQuantQuant(context: ctx)- guard let qBuf = Fp16Buffer.make(ctx.device, values: q),- let kBuf = Fp16Buffer.make(ctx.device, values: k),- let vBuf = Fp16Buffer.make(ctx.device, values: v),- let outBuf = Fp16Buffer.make(ctx.device, count: chunk * oStride),- let keyCache = ctx.device.makeBuffer(length: kvValid * keyLayout.bytesPerToken,- options: .storageModeShared),- let valueCache = ctx.device.makeBuffer(length: kvValid * valueLayout.bytesPerToken,- options: .storageModeShared) else {- Issue.record("alloc failed")- return- }-- let whtParams = TurboQuantWHTParams(numHeads: UInt32(kvHeads),- layer: layer,- rotationSeed: rotationSeed,- applyRotation: true)- let keyWrite = TurboQuantKVWriteParams(d: UInt32(headDim),- numHeads: UInt32(kvHeads),- roleLayout: keyLayout)- let valueWrite = TurboQuantKVWriteParams(d: UInt32(headDim),- numHeads: UInt32(kvHeads),- roleLayout: valueLayout)- let keyBulk = TurboQuantKVBulkWriteParams(kv: keyWrite,- tokenCount: kvValid,- dstTokenBase: 0,- cacheTokenCapacity: kvValid,- sourceTokenStrideElements: kvStride)- let valueBulk = TurboQuantKVBulkWriteParams(kv: valueWrite,- tokenCount: kvValid,- dstTokenBase: 0,- cacheTokenCapacity: kvValid,- sourceTokenStrideElements: kvStride)- let prefillParams = PrefillAttentionParams(- startPosition: UInt32(start),- queryCount: UInt32(chunk),- headDim: UInt32(headDim),- numQHeads: UInt32(qHeads),- numKVHeads: UInt32(kvHeads),- kvValidCount: UInt32(kvValid),- slidingWindow: UInt32(window),- kvTokenStrideElements: UInt32(kvStride),- qTokenStrideElements: UInt32(qStride),- oTokenStrideElements: UInt32(oStride),- scale: 1.0)- let tqParams = PrefillTurboQuantAttentionParams(prefill: prefillParams,- layer: layer,- rotationSeed: rotationSeed,- keyLayout: keyLayout,- valueLayout: valueLayout)-- let cb = ctx.queue.makeCommandBuffer()!- try quant.encodeKVWriteWHTBulk(commandBuffer: cb,- x: kBuf,- cache: keyCache,- params: keyBulk,- whtParams: whtParams)- try quant.encodeKVWriteWHTBulk(commandBuffer: cb,- x: vBuf,- cache: valueCache,- params: valueBulk,- whtParams: whtParams)- prefill.encodeTurboQuantCausal(commandBuffer: cb,- q: qBuf,- keyCache: keyCache,- valueCache: valueCache,- out: outBuf,- params: tqParams)- cb.commit()- cb.waitUntilCompleted()-- let actual = Fp16Buffer.read(outBuf, count: chunk * oStride)- let keyBytes = Array(UnsafeBufferPointer(- start: keyCache.contents().assumingMemoryBound(to: UInt8.self),- count: keyCache.length))- let valueBytes = Array(UnsafeBufferPointer(- start: valueCache.contents().assumingMemoryBound(to: UInt8.self),- count: valueCache.length))- let materializedKey = TurboQuantRef.materializePackedCache(- keyBytes,- tokenCount: kvValid,- headDim: headDim,- numHeads: kvHeads,- bytesPerHead: keyLayout.bytesPerHead,- bytesPerToken: keyLayout.bytesPerToken,- packedOffset: keyLayout.packedOffsetPerHead,- scaleOffset: keyLayout.scaleOffsetPerHead,- layer: layer,- rotationSeed: rotationSeed,- applyRotation: true)- let materializedValue = TurboQuantRef.materializePackedCache(- valueBytes,- tokenCount: kvValid,- headDim: headDim,- numHeads: kvHeads,- bytesPerHead: valueLayout.bytesPerHead,- bytesPerToken: valueLayout.bytesPerToken,- packedOffset: valueLayout.packedOffsetPerHead,- scaleOffset: valueLayout.scaleOffsetPerHead,- layer: layer,- rotationSeed: rotationSeed,- applyRotation: true)- let refFixture = Fixture(q: q,- k: materializedKey,- v: materializedValue,- qStride: qStride,- kvStride: kvStride,- oStride: oStride,- headDim: headDim,- qHeads: qHeads,- kvHeads: kvHeads,- start: start,- chunk: chunk,- kvValid: kvValid,- window: window,- scale: 1.0)- let reference = Self.reference(refFixture)- let compact = Self.compactOutput(actual,- chunk: chunk,- qHeads: qHeads,- headDim: headDim,- oStride: oStride)- let maxAbs = RelError.maxAbsDiff(compact, reference)- let rel = RelError.compute(actual: compact, reference: reference)- #expect(maxAbs <= 3e-2, "k4v4 packed maxAbs=\(maxAbs) rel=\(rel)")- #expect(rel <= 3e-2, "k4v4 packed rel=\(rel) maxAbs=\(maxAbs)")- }-- private static func compactOutput(_ out: [Float],- chunk: Int,- qHeads: Int,- headDim: Int,- oStride: Int) -> [Float] {- var compact = [Float](repeating: 0, count: chunk * qHeads * headDim)- for t in 0..<chunk {- for h in 0..<qHeads {- for d in 0..<headDim {- compact[(t * qHeads + h) * headDim + d] =- out[t * oStride + h * headDim + d]- }- }- }- return compact- }private static func reference(_ fixture: Fixture) -> [Float] {var out = [Float](repeating: 0, count: fixture.chunk * fixture.qHeads * fixture.headDim)diff --git a/Tests/TurboFieldfare/Core/Kernels/KVCache/TurboQuantTests+BulkWrite.swift b/Tests/TurboFieldfare/Core/Kernels/KVCache/TurboQuantTests+BulkWrite.swiftdeleted file mode 100644index cd10fac8..00000000--- a/Tests/TurboFieldfare/Core/Kernels/KVCache/TurboQuantTests+BulkWrite.swift+++ /dev/null@@ -1,42 +0,0 @@-import Testing--@testable import TurboFieldfare--extension TurboQuantTests {- @Test func fusedBulkWriteMatchesRepeatedScalarWrites() throws {- try Self.runBulkWriteMatchesRepeatedScalarWrites()- }-- @Test func fusedBulkWriteUsesDestinationTokenBase() throws {- try Self.runBulkWriteMatchesRepeatedScalarWrites(dstTokenBase: 2)- }-- @Test func bulkWriteRejectsOutOfRangeTokenCount() throws {- let d = 256- let numHeads = 2- let layout = TurboQuantKVLayout.role(mode: .k4v4NormCorrected,- headDim: d,- numKVHeads: numHeads)- let context = try Self.makeContext()- let quant = try TurboQuantQuant(context: context)- let commandBuffer = context.queue.makeCommandBuffer()!- let input = Self.makeBuffer(context, count: numHeads * d, type: Float16.self)- let cache = Self.makeBuffer(context, count: layout.bytesPerToken, type: UInt8.self)- let write = TurboQuantKVWriteParams(d: UInt32(d),- numHeads: UInt32(numHeads),- roleLayout: layout)- let params = TurboQuantKVBulkWriteParams(kv: write,- tokenCount: 2,- dstTokenBase: 0,- cacheTokenCapacity: 1,- sourceTokenStrideElements: numHeads * d)-- #expect(throws: TurboQuantKVBulkWriteError.self) {- try quant.encodeKVWriteWHTBulk(commandBuffer: commandBuffer,- x: input,- cache: cache,- params: params,- whtParams: TurboQuantWHTParams())- }- }-}diff --git a/Tests/TurboFieldfare/Core/Kernels/KVCache/TurboQuantTests+Quantization.swift b/Tests/TurboFieldfare/Core/Kernels/KVCache/TurboQuantTests+Quantization.swiftdeleted file mode 100644index f6c761a1..00000000--- a/Tests/TurboFieldfare/Core/Kernels/KVCache/TurboQuantTests+Quantization.swift+++ /dev/null@@ -1,11 +0,0 @@-import Testing--extension TurboQuantTests {- @Test func packedRoundTripD256() throws {- try Self.runPackedRoundTrip(headDim: 256)- }-- @Test func packedRoundTripD512() throws {- try Self.runPackedRoundTrip(headDim: 512)- }-}diff --git a/Tests/TurboFieldfare/Core/Kernels/KVCache/TurboQuantTests.swift b/Tests/TurboFieldfare/Core/Kernels/KVCache/TurboQuantTests.swiftdeleted file mode 100644index cd6bc381..00000000--- a/Tests/TurboFieldfare/Core/Kernels/KVCache/TurboQuantTests.swift+++ /dev/null@@ -1,150 +0,0 @@-import Foundation-import Metal-import Testing-import TurboFieldfareValidationSupport--@testable import TurboFieldfare--@Suite struct TurboQuantTests {- static func makeContext() throws -> MetalContext {- try MetalContext()- }-- static func makeBuffer<T>(_ context: MetalContext, count: Int, type: T.Type) -> MTLBuffer {- context.device.makeBuffer(length: count * MemoryLayout<T>.stride,- options: .storageModeShared)!- }-- static func bufferWith<T>(_ context: MetalContext, _ values: [T]) -> MTLBuffer {- let buffer = makeBuffer(context, count: values.count, type: T.self)- values.withUnsafeBytes { source in- if let base = source.baseAddress {- memcpy(buffer.contents(), base, source.count)- }- }- return buffer- }-- static func runPackedRoundTrip(headDim: Int) throws {- let numHeads = headDim == 256 ? 8 : 2- let tokenCount = 2- let layer: UInt32 = 3- let rotationSeed: UInt32 = 0x51A7_1010- var random = SeedTree(0x51A7_1010).key("packed-round-trip-d\(headDim)")- let input = (0..<(tokenCount * numHeads * headDim)).map {- _ in Float16(random.uniform(-1, 1))- }- let layout = TurboQuantKVLayout.role(mode: .k4v4NormCorrected,- headDim: headDim,- numKVHeads: numHeads)- let context = try makeContext()- let quant = try TurboQuantQuant(context: context)- let inputBuffer = bufferWith(context, input)- let cache = makeBuffer(context,- count: tokenCount * layout.bytesPerToken,- type: UInt8.self)- let params = TurboQuantKVWriteParams(d: UInt32(headDim),- numHeads: UInt32(numHeads),- roleLayout: layout)- let transform = TurboQuantWHTParams(numHeads: UInt32(numHeads),- layer: layer,- rotationSeed: rotationSeed,- applyRotation: true)-- let commandBuffer = context.queue.makeCommandBuffer()!- quant.encodeKVWriteWHT(commandBuffer: commandBuffer,- x: inputBuffer,- cache: cache,- params: params,- whtParams: transform,- pairs: tokenCount * numHeads)- commandBuffer.commit()- commandBuffer.waitUntilCompleted()- if let error = commandBuffer.error { throw error }-- let pointer = cache.contents().bindMemory(to: UInt8.self, capacity: cache.length)- let cacheBytes = Array(UnsafeBufferPointer(start: pointer, count: cache.length))- let actual = TurboQuantRef.materializePackedCache(- cacheBytes,- tokenCount: tokenCount,- headDim: headDim,- numHeads: numHeads,- bytesPerHead: layout.bytesPerHead,- bytesPerToken: layout.bytesPerToken,- packedOffset: layout.packedOffsetPerHead,- scaleOffset: layout.scaleOffsetPerHead,- layer: layer,- rotationSeed: rotationSeed,- applyRotation: true)- let expected = input.map(Float.init)- let squaredError = zip(actual, expected).reduce(Float.zero) { result, pair in- let error = pair.0 - pair.1- return result + error * error- }- let squaredReference = expected.reduce(Float.zero) { $0 + $1 * $1 }- #expect((squaredError / squaredReference).squareRoot() < 0.16)- }-- static func runBulkWriteMatchesRepeatedScalarWrites(dstTokenBase: Int = 0) throws {- let d = 256- let numHeads = 2- let tokenCount = 3- let capacity = dstTokenBase + tokenCount + 1- let layout = TurboQuantKVLayout.role(mode: .k4v4NormCorrected,- headDim: d,- numKVHeads: numHeads)- var random = SeedTree(0xB117).key("tq-bulk-k4-base-\(dstTokenBase)")- let input = (0..<(tokenCount * numHeads * d)).map {- _ in Float16(random.uniform(-1, 1))- }- let context = try makeContext()- let quant = try TurboQuantQuant(context: context)- let inputBuffer = bufferWith(context, input)- let scalar = makeBuffer(context,- count: capacity * layout.bytesPerToken,- type: UInt8.self)- let bulk = makeBuffer(context,- count: capacity * layout.bytesPerToken,- type: UInt8.self)- memset(scalar.contents(), 0xA5, scalar.length)- memset(bulk.contents(), 0xA5, bulk.length)- let params = TurboQuantKVWriteParams(d: UInt32(d),- numHeads: UInt32(numHeads),- roleLayout: layout)- let bulkParams = TurboQuantKVBulkWriteParams(- kv: params,- tokenCount: tokenCount,- dstTokenBase: dstTokenBase,- cacheTokenCapacity: capacity,- sourceTokenStrideElements: numHeads * d)-- let commandBuffer = context.queue.makeCommandBuffer()!- for token in 0..<tokenCount {- var tokenParams = params- tokenParams.tokenBase = UInt32(dstTokenBase + token)- quant.encodeKVWriteWHT(- commandBuffer: commandBuffer,- x: inputBuffer,- xOffset: token * numHeads * d * MemoryLayout<Float16>.stride,- cache: scalar,- cacheOffset: (dstTokenBase + token) * layout.bytesPerToken,- params: tokenParams,- whtParams: TurboQuantWHTParams(),- pairs: numHeads)- }- try quant.encodeKVWriteWHTBulk(commandBuffer: commandBuffer,- x: inputBuffer,- cache: bulk,- params: bulkParams,- whtParams: TurboQuantWHTParams())- commandBuffer.commit()- commandBuffer.waitUntilCompleted()- if let error = commandBuffer.error { throw error }-- let lhs = scalar.contents().bindMemory(to: UInt8.self, capacity: scalar.length)- let rhs = bulk.contents().bindMemory(to: UInt8.self, capacity: bulk.length)- for index in 0..<scalar.length {- #expect(lhs[index] == rhs[index], "bulk cache byte \(index)")- }- }-}diff --git a/Tests/TurboFieldfare/Core/Kernels/MoE/SharedExpertInt4Tests.swift b/Tests/TurboFieldfare/Core/Kernels/MoE/SharedExpertInt4Tests.swiftnew file mode 100644index 00000000..6b14ea67--- /dev/null+++ b/Tests/TurboFieldfare/Core/Kernels/MoE/SharedExpertInt4Tests.swift@@ -0,0 +1,82 @@+import Foundation+import Metal+import Testing+@testable import TurboFieldfare+import TurboFieldfareValidationSupport++@Suite struct SharedExpertInt4Tests {+ private static let d = 128+ private static let f = 64++ @Test func sharedExpertInt4MatchesAffineReference() throws {+ var rng = SeedTree(0x604).key("shared-expert-int4")+ let x = (0..<Self.d).map { _ in rng.uniform(-0.4, 0.4) }+ let gate = (0..<Self.f).map { _ in (0..<Self.d).map { _ in rng.uniform(-0.4, 0.4) } }+ let up = (0..<Self.f).map { _ in (0..<Self.d).map { _ in rng.uniform(-0.4, 0.4) } }+ let down = (0..<Self.d).map { _ in (0..<Self.f).map { _ in rng.uniform(-0.4, 0.4) } }+ let gatePack = Self.pack(gate)+ let upPack = Self.pack(up)+ let downPack = Self.pack(down)+ let x16 = x.map { Float(Float16($0)) }+ let gateOut = DequantInt4GemvRef.apply(weightRows: gatePack.rows, x: x16, n: Self.d)+ let upOut = DequantInt4GemvRef.apply(weightRows: upPack.rows, x: x16, n: Self.d)+ let act = zip(gateOut, upOut).map { gateValue, upValue in+ let cube = gateValue * gateValue * gateValue+ let inner = 0.7978845608028654 * Double(gateValue + 0.044715 * cube)+ return Float(Float16(Float(0.5 * Double(gateValue) * (1 + tanh(inner))) * upValue))+ }+ let reference = DequantInt4GemvRef.apply(weightRows: downPack.rows, x: act, n: Self.f)++ let context = try MetalContext()+ let runtime = try SharedExpertInt4(context: context)+ let xBuffer = try #require(Fp16Buffer.make(context.device, values: x))+ let yBuffer = try #require(Fp16Buffer.make(context.device, count: Self.d))+ let gateScratch = try #require(Fp16Buffer.make(context.device, count: Self.f))+ let upScratch = try #require(Fp16Buffer.make(context.device, count: Self.f))+ let actScratch = try #require(Fp16Buffer.make(context.device, count: Self.f))+ let commandBuffer = try #require(context.queue.makeCommandBuffer())+ try runtime.encode(commandBuffer: commandBuffer,+ x: xBuffer,+ gate: Self.projection(context, gatePack, rows: Self.f, cols: Self.d),+ up: Self.projection(context, upPack, rows: Self.f, cols: Self.d),+ down: Self.projection(context, downPack, rows: Self.d, cols: Self.f),+ y: yBuffer,+ scratchGate: gateScratch,+ scratchUp: upScratch,+ scratchAct: actScratch)+ commandBuffer.commit()+ commandBuffer.waitUntilCompleted()+ #expect(commandBuffer.status == .completed)+ let actual = Fp16Buffer.read(yBuffer, count: Self.d)+ let error = RelError.compute(actual: actual, reference: reference)+ #expect(error < Tolerance.quantInt4 * 4, "shared-expert int4 rel=\(error)")+ }++ private static func pack(_ values: [[Float]]) ->+ (rows: [Quantization.Int4AffineRow], packed: [UInt8], scales: [UInt16], biases: [UInt16]) {+ let rows = values.map(Quantization.quantizeInt4Affine)+ return (rows,+ rows.flatMap(\.packed),+ rows.flatMap(\.scales),+ rows.flatMap(\.biases))+ }++ private static func projection(+ _ context: MetalContext,+ _ packed: (rows: [Quantization.Int4AffineRow], packed: [UInt8], scales: [UInt16], biases: [UInt16]),+ rows: Int,+ cols: Int+ ) -> SharedExpertProjection {+ SharedExpertProjection(+ weights: context.device.makeBuffer(bytes: packed.packed,+ length: packed.packed.count,+ options: .storageModeShared)!,+ scales: context.device.makeBuffer(bytes: packed.scales,+ length: packed.scales.count * 2,+ options: .storageModeShared)!,+ biases: context.device.makeBuffer(bytes: packed.biases,+ length: packed.biases.count * 2,+ options: .storageModeShared)!,+ rows: UInt32(rows), cols: UInt32(cols))+ }+}diff --git a/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillSharedExpertTests.swift b/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillSharedExpertTests.swiftindex 1461018f..55725b7b 100644--- a/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillSharedExpertTests.swift+++ b/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillSharedExpertTests.swift@@ -31,6 +31,8 @@ import TurboFieldfareValidationSupportguard let xBuf = Fp16Buffer.make(ctx.device, halves: x),let yRef = Fp16Buffer.make(ctx.device, halves: Array(repeating: Self.sentinel, count: yElements)),let ySplit = Fp16Buffer.make(ctx.device, halves: Array(repeating: Self.sentinel, count: yElements)),+ let scratchGate = Fp16Buffer.make(ctx.device, count: Self.f),+ let scratchUp = Fp16Buffer.make(ctx.device, count: Self.f),let scratchAct = Fp16Buffer.make(ctx.device, count: Self.rows * Self.f) else {Issue.record("buffer allocation failed")return@@ -48,6 +50,8 @@ import TurboFieldfareValidationSupportgate: gateProj,up: upProj,down: downProj,+ scratchGate: scratchGate,+ scratchUp: scratchUp,scratchAct: scratchAct,queryCount: Self.rows,d: Self.d,@@ -103,6 +107,8 @@ import TurboFieldfareValidationSupportguard let xBuf = Fp16Buffer.make(ctx.device, halves: x),let yRef = Fp16Buffer.make(ctx.device, halves: Array(repeating: Self.sentinel, count: yElements)),let yGot = Fp16Buffer.make(ctx.device, halves: Array(repeating: Self.sentinel, count: yElements)),+ let scratchGate = Fp16Buffer.make(ctx.device, count: Self.f),+ let scratchUp = Fp16Buffer.make(ctx.device, count: Self.f),let scratchAct = Fp16Buffer.make(ctx.device, count: Self.f),let postF1Buf = ctx.device.makeBuffer(bytes: postF1,length: postF1.count * MemoryLayout<UInt16>.stride,@@ -147,6 +153,8 @@ import TurboFieldfareValidationSupportgate: gateProj,up: upProj,down: downProj,+ scratchGate: scratchGate,+ scratchUp: scratchUp,scratchAct: scratchAct,queryCount: Self.rows,d: Self.d,@@ -183,6 +191,8 @@ import TurboFieldfareValidationSupportguard let xBuf = Fp16Buffer.make(ctx.device, halves: x),let yRef = Fp16Buffer.make(ctx.device, halves: Array(repeating: sentinel, count: rows * yStride)),let yGot = Fp16Buffer.make(ctx.device, halves: Array(repeating: sentinel, count: rows * yStride)),+ let scratchGate = Fp16Buffer.make(ctx.device, count: f),+ let scratchUp = Fp16Buffer.make(ctx.device, count: f),let scratchAct = Fp16Buffer.make(ctx.device, count: f) else {Issue.record("buffer allocation failed")return@@ -216,6 +226,8 @@ import TurboFieldfareValidationSupportgate: gateProj,up: upProj,down: downProj,+ scratchGate: scratchGate,+ scratchUp: scratchUp,scratchAct: scratchAct,queryCount: rows,d: d,diff --git a/Tests/TurboFieldfare/Core/Runtime/Configuration/RuntimeConfigurationTests.swift b/Tests/TurboFieldfare/Core/Runtime/Configuration/RuntimeConfigurationTests.swiftindex 9225a50c..7d044bb2 100644--- a/Tests/TurboFieldfare/Core/Runtime/Configuration/RuntimeConfigurationTests.swift+++ b/Tests/TurboFieldfare/Core/Runtime/Configuration/RuntimeConfigurationTests.swift@@ -4,7 +4,6 @@ import Testing@Suite struct RuntimeConfigurationTests {@Test func productionDefaultsAreStable() {let runtime = RuntimeConfiguration.production- #expect(runtime.kvStorage == .fp16)#expect(runtime.fp16RingEnabled)#expect(runtime.expertCacheSlots == 16)#expect(runtime.expertCachePolicy == .lfu)@@ -22,14 +21,11 @@ import TestingrdadvisePolicy: .adaptive,prefillEnabled: false,prefillChunkTokens: 64,- turboQuantKVEnabled: true,forceLogitsHead: true)#expect(runtime.expertCacheSlots == 32)#expect(runtime.modelExpertCachePolicy == .lru)#expect(runtime.rdadviseEnabled)#expect(runtime.prefillConfig == .off)- #expect(runtime.turboQuantKVEnabled)- #expect(runtime.kvStorage == .packedK4V4)#expect(runtime.headPath == .logits)}diff --git a/Tests/TurboFieldfare/Core/Runtime/KVCache/KVCacheManagerTests.swift b/Tests/TurboFieldfare/Core/Runtime/KVCache/KVCacheManagerTests.swiftindex 3b738da6..13a328c0 100644--- a/Tests/TurboFieldfare/Core/Runtime/KVCache/KVCacheManagerTests.swift+++ b/Tests/TurboFieldfare/Core/Runtime/KVCache/KVCacheManagerTests.swift@@ -3,21 +3,19 @@ import Foundationimport Metal@testable import TurboFieldfare-/// Tests `KVCacheManager` shape, growth, separate K/V storage, FP16 SWA ring,-/// packed storage, and reset semantics against the Gemma 4 config.+/// Tests `KVCacheManager` FP16 shape, growth, separate K/V storage, ring,+/// and reset semantics against the Gemma 4 config.@Suite struct KVCacheManagerTests {private let config = ArchConfig.gemma4_26B_A4Bprivate func makeManager(maxContext: Int,- storageMode: KVCacheStorageMode = .fp16,fp16RingEnabled: Bool = false,fp16RingCapacityOverride: Int? = nil) throws -> (MetalContext, KVCacheManager) {let ctx = try MetalContext()let kv = try KVCacheManager(device: ctx.device,config: config,maxContext: maxContext,- storageMode: storageMode,fp16RingEnabled: fp16RingEnabled,slidingWindow: config.slidingWindow,maxPrefillChunkTokens: 128,@@ -25,11 +23,6 @@ import Metalreturn (ctx, kv)}- @Test func defaultStorageMode_isFP16() throws {- let (_, kv) = try makeManager(maxContext: 16)- #expect(kv.storageMode == .fp16)- #expect(kv.turboQuantLayout(layer: 0) == nil)- }@Test func strideAndBufferSizes_matchConfig() throws {let (_, kv) = try makeManager(maxContext: 128)@@ -167,46 +160,4 @@ import Metal#expect(kv.position == 1)}- @Test func turboQuantStorage_usesPackedLayerLayouts() throws {- let (_, kv) = try makeManager(maxContext: 128,- storageMode: .turboQuant(.k4v4NormCorrected))-- #expect(kv.storageMode == .turboQuant(.k4v4NormCorrected))-- let swa = try #require(kv.turboQuantLayout(layer: 0))- #expect(swa.key.bytesPerToken == 1_040)- #expect(swa.value.bytesPerToken == 1_040)- #expect(kv.quantizedKeyBuffer(layer: 0, validTokenCount: 0).length == 128 * 1_040)- #expect(kv.quantizedValueBuffer(layer: 0, validTokenCount: 0).length == 128 * 1_040)-- let full = try #require(kv.turboQuantLayout(layer: 5))- #expect(full.key.bytesPerToken == 516)- #expect(full.value.bytesPerToken == 516)- #expect(kv.quantizedKeyBuffer(layer: 5, validTokenCount: 0).length == 128 * 516)- #expect(kv.quantizedValueBuffer(layer: 5, validTokenCount: 0).length == 128 * 516)- }-- @Test func turboQuantSlots_areLinearByRoleStride() throws {- let (_, kv) = try makeManager(maxContext: 128,- storageMode: .turboQuant(.k4v4NormCorrected))-- let swa = try #require(kv.turboQuantLayout(layer: 0))- #expect(swa.key.bytesPerToken == 1_040)- #expect(swa.value.bytesPerToken == 1_040)-- let k0 = kv.quantizedKeySlot(layer: 0, position: 3)- let v0 = kv.quantizedValueSlot(layer: 0, position: 3)- #expect(k0.offset == 3 * swa.key.bytesPerToken)- #expect(v0.offset == 3 * swa.value.bytesPerToken)- #expect(k0.buffer !== v0.buffer)- }-- @Test func turboQuantReset_clearsPosition() throws {- let (_, kv) = try makeManager(maxContext: 128,- storageMode: .turboQuant(.k4v4NormCorrected))- for _ in 0..<9 { kv.advance() }- #expect(kv.position == 9)- kv.reset()- #expect(kv.position == 0)- }}diff --git a/Tests/TurboFieldfare/Core/Runtime/KVCache/TurboQuantKVLayoutTests.swift b/Tests/TurboFieldfare/Core/Runtime/KVCache/TurboQuantKVLayoutTests.swiftdeleted file mode 100644index 5ecbe029..00000000--- a/Tests/TurboFieldfare/Core/Runtime/KVCache/TurboQuantKVLayoutTests.swift+++ /dev/null@@ -1,44 +0,0 @@-import Testing--@testable import TurboFieldfare--@Suite struct TurboQuantKVLayoutTests {- @Test func swaLayoutUsesPackedK4V4Storage() {- let layout = TurboQuantKVLayout.layer(mode: .k4v4NormCorrected,- headDim: 256,- numKVHeads: 8,- capacity: 4)-- #expect(layout.key.packedOffsetPerHead == 0)- #expect(layout.key.scaleOffsetPerHead == 128)- #expect(layout.key.bytesPerHead == 130)- #expect(layout.key.bytesPerToken == 1_040)- #expect(layout.key.bytesPerToken + layout.value.bytesPerToken == 2_080)- #expect(4 * (layout.key.bytesPerToken + layout.value.bytesPerToken) == 8_320)- }-- @Test func fullAttentionLayoutUsesPackedK4V4Storage() {- let layout = TurboQuantKVLayout.layer(mode: .k4v4NormCorrected,- headDim: 512,- numKVHeads: 2,- capacity: 4)-- #expect(layout.key.scaleOffsetPerHead == 256)- #expect(layout.key.bytesPerHead == 258)- #expect(layout.key.bytesPerToken == 516)- #expect(layout.value.bytesPerToken == 516)- #expect(layout.key.bytesPerToken + layout.value.bytesPerToken == 1_032)- #expect(4 * (layout.key.bytesPerToken + layout.value.bytesPerToken) == 4_128)- }-- @Test func offsetsFollowTokenAndHeadStrides() {- let layout = TurboQuantKVLayout.layer(mode: .k4v4NormCorrected,- headDim: 256,- numKVHeads: 8,- capacity: 8)- let headBase = 2 * 1_040 + 3 * 130-- #expect(headBase + layout.key.packedOffsetPerHead == headBase)- #expect(headBase + layout.key.scaleOffsetPerHead == headBase + 128)- }-}diff --git a/Tests/TurboFieldfare/Core/Runtime/Prefill/PrefillChunkScratchTests.swift b/Tests/TurboFieldfare/Core/Runtime/Prefill/PrefillChunkScratchTests.swiftindex d94a918f..d977ec46 100644--- a/Tests/TurboFieldfare/Core/Runtime/Prefill/PrefillChunkScratchTests.swift+++ b/Tests/TurboFieldfare/Core/Runtime/Prefill/PrefillChunkScratchTests.swift@@ -21,7 +21,7 @@ import Metal#expect(layout.routePartialElements == 32 * 8 * 2816)#expect(layout.routeIDElements == 32 * 8)#expect(layout.routeWeightElements == 32 * 8)- #expect(layout.sharedExpertActScratchElements == 2112)+ #expect(layout.sharedExpertScratchElements == 2112)#expect(layout.routedPairMicrobatchRows == 32)#expect(layout.routedGateUpActElements == 3 * 32 * 704)#expect(layout.routedDownOutputElements == 32 * 2816)diff --git a/Tests/TurboFieldfare/Core/Tokenization/ChatTemplateTests.swift b/Tests/TurboFieldfare/Core/Tokenization/ChatTemplateTests.swiftnew file mode 100644index 00000000..df1b07d8--- /dev/null+++ b/Tests/TurboFieldfare/Core/Tokenization/ChatTemplateTests.swift@@ -0,0 +1,110 @@+import Foundation+import Testing+@testable import TurboFieldfare++/// Hand-authored Gemma 4 chat template. Loads the IT tokenizer (cached after+/// first run). Verifies turn-marker structure as a string and that the prompt+/// encodes to the right special-token ids.+@Suite("ChatTemplate")+struct ChatTemplateTests {+ let tok: GFTokenizer++ init() async throws {+ self.tok = try await GFTokenizer.load()+ }++ private typealias Message = GFTokenizer.Message++ @Test("Single user turn has the documented marker structure")+ func singleUserTurn() throws {+ let p = try tok.applyChatTemplate([Message(role: .user, content: "Hi")])+ #expect(p.hasPrefix("<bos>"))+ #expect(p.contains("<|turn>user\nHi<turn|>\n"))+ #expect(p.hasSuffix("<|turn>model\n<|channel>thought\n<channel|>"))+ // Exactly one occurrence of the user content.+ #expect(p.components(separatedBy: "Hi").count - 1 == 1)+ }++ @Test("Multi-turn closes prior turns and leaves assistant open")+ func multiTurn() throws {+ let p = try tok.applyChatTemplate([+ Message(role: .user, content: "A"),+ Message(role: .assistant, content: "B"),+ Message(role: .user, content: "C"),+ ])+ // Contents appear in order.+ let ia = p.range(of: "<|turn>user\nA<turn|>")!+ let ib = p.range(of: "<|turn>model\nB<turn|>")!+ let ic = p.range(of: "<|turn>user\nC<turn|>")!+ #expect(ia.lowerBound < ib.lowerBound)+ #expect(ib.lowerBound < ic.lowerBound)+ // The assistant turn for "B" is closed; the trailing assistant turn is open.+ #expect(p.contains("<|turn>model\nB<turn|>"))+ #expect(p.hasSuffix("<|turn>model\n<|channel>thought\n<channel|>"))+ }++ @Test("System message renders as a leading turn")+ func systemTurn() throws {+ let p = try tok.applyChatTemplate([+ Message(role: .system, content: "Be terse."),+ Message(role: .user, content: "Hi"),+ ])+ let sys = p.range(of: "<|turn>system\nBe terse.<turn|>")!+ let usr = p.range(of: "<|turn>user\nHi<turn|>")!+ #expect(sys.lowerBound < usr.lowerBound)+ }++ @Test("System message after a user turn is rejected")+ func misplacedSystemTurn() {+ #expect(throws: GFTokenizerError.self) {+ _ = try tok.applyChatTemplate([+ Message(role: .user, content: "Hi"),+ Message(role: .system, content: "Too late"),+ ])+ }+ }++ @Test("No Gemma 2/3 turn markers leak in")+ func noLegacyMarkers() throws {+ let p = try tok.applyChatTemplate([Message(role: .user, content: "x")])+ #expect(!p.contains("<start_of_turn>"))+ #expect(!p.contains("<end_of_turn>"))+ }++ @Test("Prompt encodes to BOS-first with the turn-close special id")+ func encodesToSpecialIDs() throws {+ let p = try tok.applyChatTemplate([Message(role: .user, content: "Hi")])+ let ids = tok.encode(p, addBOS: false)+ #expect(ids.first == tok.bosID, "expected BOS \(tok.bosID) first, got \(String(describing: ids.first))")+ #expect(ids.contains(tok.endOfTurnID), "encoded prompt missing <turn|> id \(tok.endOfTurnID)")+ }++ @Test("Single-turn token IDs match the pinned upstream template")+ func tokenIDsMatchPinnedUpstream() throws {+ let prompt = try tok.applyChatTemplate([Message(role: .user, content: "Hi")])+ #expect(tok.encode(prompt, addBOS: false) == [+ 2, 105, 2364, 107, 10979, 106, 107, 105, 4368, 107, 100, 45518, 107, 101,+ ])+ }++ /// Control-token spoofing: a user typing the literal open-turn marker must+ /// not inject an extra turn-CLOSE id (the marker that would end the turn).+ /// The legitimate template contributes exactly one `<turn|>` per message.+ ///+ /// Note: HF tokenizers do recognize special-token text, so a user writing+ /// the verbatim close marker can still inject it. That trusted-input+ /// limitation is accepted for this private research runtime.+ @Test("Open-turn marker in user content does not add a turn-close id")+ func spoofingDoesNotInjectTurnClose() throws {+ let p = try tok.applyChatTemplate([Message(role: .user, content: "<|turn> spoofing attempt")])+ let ids = tok.encode(p, addBOS: false)+ let closes = ids.filter { $0 == tok.endOfTurnID }.count+ #expect(closes == 1, "expected exactly one <turn|>, got \(closes)")+ }++ @Test("Empty messages yields BOS plus an open assistant turn")+ func emptyMessages() throws {+ let p = try tok.applyChatTemplate([])+ #expect(p == "<bos><|turn>model\n<|channel>thought\n<channel|>")+ }+}diff --git a/Tests/TurboFieldfare/Core/Tokenization/TokenizerTests.swift b/Tests/TurboFieldfare/Core/Tokenization/TokenizerTests.swiftindex efe364b8..d22cba64 100644--- a/Tests/TurboFieldfare/Core/Tokenization/TokenizerTests.swift+++ b/Tests/TurboFieldfare/Core/Tokenization/TokenizerTests.swift@@ -24,11 +24,12 @@ struct TokenizerTests {}}- @Test("Stop-token set covers EOS and end-of-turn")+ @Test("Stop-token set covers EOS, end-of-turn, and tool response")func stopTokens() {#expect(tok.stopTokenIDs.contains(tok.eosID))#expect(tok.stopTokenIDs.contains(tok.endOfTurnID))- #expect(tok.stopTokenIDs.count == 2)+ #expect(tok.stopTokenIDs.contains(tok.toolResponseID))+ #expect(tok.stopTokenIDs.count == 3)}// MARK: - Encode / decodediff --git a/Tests/TurboFieldfareApp/Core/Configuration/AppContextLengthOptionTests.swift b/Tests/TurboFieldfareApp/Core/Configuration/AppContextLengthOptionTests.swiftnew file mode 100644index 00000000..ae6dc41b--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/Configuration/AppContextLengthOptionTests.swift@@ -0,0 +1,23 @@+import Testing+@testable import TurboFieldfareAppCore++@Suite struct AppContextLengthOptionTests {+ @Test func optionsUseSupportedContextLengthsInAscendingOrder() {+ #expect(AppContextLengthOption.allCases.map(\.tokens)+ == [4_096, 8_192, 16_384, 32_768, 65_536])+ }++ @Test func optionsReportProductionFP16KVAllocation() {+ let mebibytes = AppContextLengthOption.allCases.map {+ $0.fp16KVBytes / 1_048_576+ }+ #expect(mebibytes == [305, 385, 545, 865, 1_505])+ #expect(AppContextLengthOption.allCases.map(\.menuLabel) == [+ "4K, Default",+ "8K, +85 MB",+ "16K, +250 MB",+ "32K, +590 MB",+ "64K, +1.26 GB",+ ])+ }+}diff --git a/Tests/TurboFieldfareApp/Core/Configuration/AppPromptPresetTests.swift b/Tests/TurboFieldfareApp/Core/Configuration/AppPromptPresetTests.swiftindex d9abd241..acfa083e 100644--- a/Tests/TurboFieldfareApp/Core/Configuration/AppPromptPresetTests.swift+++ b/Tests/TurboFieldfareApp/Core/Configuration/AppPromptPresetTests.swift@@ -1,84 +1,70 @@+import CryptoKit+import Foundationimport TurboFieldfareAppCoreimport Testing@Suite("App prompt presets")struct AppPromptPresetTests {- @Test("Catalog has unique nonempty identifiers and titles")+ @Test("Catalog has exactly seven unique prompts in the approved order")func catalogIdentity() {let presets = AppPromptPreset.all- #expect(Set(presets.map(\.id)).count == presets.count)- #expect(Set(presets.map(\.title)).count == presets.count)- #expect(presets.allSatisfy { !$0.prefix.isEmpty })- #expect(presets.count == 6)+ #expect(presets.map(\.id) == [+ "paris",+ "fibonacci",+ "fieldfare",+ "cosine-similarity",+ "recommendation-systems",+ "matrix-multiplication",+ "metal-matmul",+ ])+ #expect(Set(presets.map(\.id)).count == 7)+ #expect(Set(presets.map(\.title)).count == 7)+ #expect(Set(presets.map(\.prompt)).count == 7)+ #expect(presets.allSatisfy { !$0.prompt.isEmpty })#expect(AppPromptPreset.primary.count == 3)- #expect(AppPromptPreset.secondary.count == 3)+ #expect(AppPromptPreset.secondary.count == 4)}- @Test("Primary presets are exact raw-completion prefixes")- func exactPrimaryPrefixes() {- #expect(AppPromptPreset.primary[0].prefix ==- "Paris is the capital and largest city of France. Situated on the River Seine, the city is known for")- #expect(AppPromptPreset.primary[1].prefix == """- An iterative Python function can return the first n Fibonacci numbers without recursion. It returns an empty list when n is zero, uses O(n) time, and includes a small correctness check:-- ```python- def fibonacci(n: int) -> list[int]:- """)- #expect(AppPromptPreset.primary[2].prefix ==- "The fieldfare (Turdus pilaris) is a grey-headed, chestnut-backed thrush that reaches Britain and Ireland from northern Europe each autumn. Its noisy winter flocks roam the countryside in search of berries, and")- #expect(AppPromptPreset.primary[2].id == "fieldfare")- #expect(AppPromptPreset.primary[2].title == "Meet the fieldfare")- #expect(!AppPromptPreset.all.contains { $0.id == "metal-gemv" })- }-- @Test("Presets contain no chat wrappers or imperative requests")- func rawCompletionContract() {- let forbiddenOpenings = ["Write ", "Explain ", "Give me ", "Rewrite "]- let forbiddenMarkers = ["<start_of_turn>", "<end_of_turn>", "user\n", "assistant\n"]+ @Test("Prompt bytes match the accepted catalog")+ func exactPromptHashes() {+ let expected = [+ "paris": "7d977c14f3236c90d02e3ac77ce3f5864ee0c4a95e68ed2afca05e98db0f5e11",+ "cosine-similarity": "b0b3a392029aa32aea6d392ef738501b69eba55f5fbc46702e01265897f477d0",+ "fieldfare": "d4f955dbf02cca9e05302d50fbe9dcf03aa27076534f1ed29f0fdea681fa58cc",+ "fibonacci": "8ba84822675c09fb7c68a66701ff2c6fe58db84daf05a9458430b9604ceb3631",+ "recommendation-systems": "d46fa2cee4f50216afd3601e8957c782d7b3955f23e5a3588d1011bf7789ee27",+ "matrix-multiplication": "308d3d062ba6a93b38fc950b6282a0f313f0042caa109224e09f925829738609",+ "metal-matmul": "582a1286e387789ddc4351552bed2aef939649aff74d56c711ccf0d2c677d932",+ ]for preset in AppPromptPreset.all {- #expect(!forbiddenOpenings.contains { preset.prefix.hasPrefix($0) })- #expect(!forbiddenMarkers.contains { preset.prefix.contains($0) })+ let digest = SHA256.hash(data: Data(preset.prompt.utf8))+ .map { String(format: "%02x", $0) }+ .joined()+ #expect(digest == expected[preset.id])}}- @Test("Primary presets include the Fieldfare easter egg")- func fieldfarePreset() {- let preset = AppPromptPreset.primary.first { $0.id == "fieldfare" }-- #expect(preset?.title == "Meet the fieldfare")- #expect(preset?.prefix ==- "The fieldfare (Turdus pilaris) is a grey-headed, chestnut-backed thrush that reaches Britain and Ireland from northern Europe each autumn. Its noisy winter flocks roam the countryside in search of berries, and")- #expect(!AppPromptPreset.all.contains { $0.id == "software" })- #expect(!AppPromptPreset.all.contains { $0.id == "lighthouse" })- }-- @Test("Secondary presets include cosine similarity")- func cosineSimilarityPreset() {- let preset = AppPromptPreset.secondary.first { $0.id == "cosine-similarity" }-- #expect(preset?.title == "Dot product and cosine similarity")- #expect(preset?.prefix == """- The unit vectors u = [1, 0] and v = [0, 1] are orthogonal. Their dot product is 0, both lengths are 1, and their cosine similarity is exactly 0. A compact check is:+ @Test("Presets contain no embedded chat wrappers")+ func chatTemplateContract() {+ let forbiddenMarkers = [+ "<|turn>", "<turn|>", "<|channel>", "<channel|>",+ "<start_of_turn>", "<end_of_turn>",+ ]- ```python- assert dot([1, 0], [0, 1]) == 0- assert cosine_similarity([1, 0], [0, 1]) ==- """)- #expect(!AppPromptPreset.all.contains { $0.id == "solar-system" })+ for preset in AppPromptPreset.all {+ #expect(!forbiddenMarkers.contains { preset.prompt.contains($0) })+ }}- @Test("Secondary presets include recommendation systems and matrix multiplication")- func substantialExplanationPresets() {- let recommendations = AppPromptPreset.secondary.first { $0.id == "recommendation-systems" }- let matrix = AppPromptPreset.secondary.first { $0.id == "matrix-multiplication" }-- #expect(recommendations?.title == "How recommendations learn")- #expect(recommendations?.prefix.contains("Matrix factorization learns a low-dimensional vector") == true)- #expect(recommendations?.prefix.hasSuffix("## The sparse interaction matrix") == true)- #expect(matrix?.title == "Matrix multiplication")- #expect(matrix?.prefix.contains("C[2,2] = 3 x 6 + 4 x 8 = 50") == true)- #expect(matrix?.prefix.hasSuffix("## Why the inner dimensions match") == true)+ @Test("Historical first three prompts occupy primary showcase slots")+ func primaryShowcase() {+ #expect(AppPromptPreset.primary.map(\.id) == [+ "paris", "fibonacci", "fieldfare",+ ])+ #expect(AppPromptPreset.secondary[0].id == "cosine-similarity")+ #expect(AppPromptPreset.secondary.last?.id == "metal-matmul")+ #expect(AppPromptPreset.primary[2].prompt.contains("winter migration to Britain"))}}diff --git a/Tests/TurboFieldfareApp/Core/Configuration/AppRuntimeOptionsTests.swift b/Tests/TurboFieldfareApp/Core/Configuration/AppRuntimeOptionsTests.swiftindex 21dae813..691fb4b1 100644--- a/Tests/TurboFieldfareApp/Core/Configuration/AppRuntimeOptionsTests.swift+++ b/Tests/TurboFieldfareApp/Core/Configuration/AppRuntimeOptionsTests.swift@@ -10,7 +10,6 @@ import TurboFieldfare#expect(options.expertCachePolicy == .lfu)#expect(options.prefillEnabled)#expect(options.prefillChunkTokens == 128)- #expect(!options.turboQuantKVEnabled)#expect(options.rdadvisePolicy == .off)#expect(options.modelVerification == .fullSha256)@@ -38,19 +37,17 @@ import TurboFieldfare}}- @Test func experimentalAndTrustChoicesAreExplicit() throws {+ @Test func runtimeAndTrustChoicesAreExplicit() throws {let options = AppRuntimeOptions(expertCacheSlots: 32,expertCachePolicy: .lru,prefillEnabled: false,prefillChunkTokens: 64,- turboQuantKVEnabled: true,rdadvisePolicy: .adaptive,modelVerification: .trustedInstall)let runtime = try options.resolvedRuntimeConfiguration(forceLogitsHead: true)#expect(runtime.modelExpertCachePolicy == .lru)#expect(runtime.prefillConfig == .off)- #expect(runtime.turboQuantKVEnabled)#expect(runtime.rdadvisePolicy == .adaptive)#expect(runtime.headPath == .logits)#expect(options.modelVerification.runtimeValue == .sizeCheckTrustedReceipt)@@ -65,7 +62,7 @@ import TurboFieldfare}}- @Test func loadedRuntimeKeyTracksEveryRuntimeChoice() {+ @Test func loadedRuntimeKeyTracksOnlyLoadTimeChoices() {let directory = URL(fileURLWithPath: "/tmp/model.gturbo")let base = AppRuntimeOptions()let baseline = AppLoadedRuntimeKey(@@ -75,9 +72,6 @@ import TurboFieldfarevar value = basevalue.expertCacheSlots = 24; variants.append(value)value = base; value.expertCachePolicy = .lru; variants.append(value)- value = base; value.prefillEnabled = false; variants.append(value)- value = base; value.prefillChunkTokens = 64; variants.append(value)- value = base; value.turboQuantKVEnabled = true; variants.append(value)value = base; value.rdadvisePolicy = .bounded; variants.append(value)value = base; value.modelVerification = .trustedInstall; variants.append(value)@@ -92,5 +86,16 @@ import TurboFieldfaremaxContextTokens: 4096,options: base,forceLogitsHead: true) != baseline)++ value = base; value.prefillEnabled = false+ #expect(AppLoadedRuntimeKey(+ modelDirectory: directory,+ maxContextTokens: 4096,+ options: value) == baseline)+ value = base; value.prefillChunkTokens = 64+ #expect(AppLoadedRuntimeKey(+ modelDirectory: directory,+ maxContextTokens: 4096,+ options: value) == baseline)}}diff --git a/Tests/TurboFieldfareApp/Core/Configuration/MacAppSettingsTests.swift b/Tests/TurboFieldfareApp/Core/Configuration/MacAppSettingsTests.swiftnew file mode 100644index 00000000..1bc66aaf--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/Configuration/MacAppSettingsTests.swift@@ -0,0 +1,116 @@+import Foundation+import Testing+@testable import TurboFieldfareAppCore++@Suite struct MacAppSettingsTests {+ @Test func settingsFileLivesBesideModelDirectory() {+ let model = URL(fileURLWithPath: "/tmp/TurboFieldfare/gemma4.gturbo",+ isDirectory: true)+ #expect(MacAppSettingsFileStore.fileURL(forModelDirectory: model).path+ == "/tmp/TurboFieldfare/mac-app-settings.json")+ }++ @Test func missingFileCreatesReadableDefaults() throws {+ let root = try makeTemporaryRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let model = root.appendingPathComponent("gemma4.gturbo", isDirectory: true)++ let settings = MacAppSettingsFileStore.loadOrCreate(forModelDirectory: model)+ let fileURL = MacAppSettingsFileStore.fileURL(forModelDirectory: model)++ #expect(settings == MacAppSettings())+ #expect(FileManager.default.fileExists(atPath: fileURL.path))+ let decoded = try JSONDecoder().decode(+ MacAppSettings.self,+ from: Data(contentsOf: fileURL))+ #expect(decoded == MacAppSettings())+ }++ @Test func malformedFileIsReplacedWithDefaults() throws {+ let root = try makeTemporaryRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let model = root.appendingPathComponent("gemma4.gturbo", isDirectory: true)+ let fileURL = MacAppSettingsFileStore.fileURL(forModelDirectory: model)+ try Data("not json".utf8).write(to: fileURL)++ let settings = MacAppSettingsFileStore.loadOrCreate(forModelDirectory: model)++ #expect(settings == MacAppSettings())+ let decoded = try JSONDecoder().decode(+ MacAppSettings.self,+ from: Data(contentsOf: fileURL))+ #expect(decoded == MacAppSettings())+ }++ @Test func invalidValuesAreReplacedWithDefaults() throws {+ let root = try makeTemporaryRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let model = root.appendingPathComponent("gemma4.gturbo", isDirectory: true)+ let invalid = MacAppSettings(contextTokens: 123)+ let fileURL = MacAppSettingsFileStore.fileURL(forModelDirectory: model)+ try JSONEncoder().encode(invalid).write(to: fileURL)++ let settings = MacAppSettingsFileStore.loadOrCreate(forModelDirectory: model)++ #expect(settings == MacAppSettings())+ }++ @MainActor+ @Test func appModelLoadsAndSavesPersistedSettings() throws {+ let root = try makeTemporaryRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let modelDirectory = root.appendingPathComponent("gemma4.gturbo", isDirectory: true)+ try FileManager.default.createDirectory(+ at: modelDirectory,+ withIntermediateDirectories: true)+ let initial = MacAppSettings(+ contextTokens: 8_192,+ expertCacheSlots: 24,+ temperature: 0.4,+ topKEnabled: false,+ topK: 32,+ topPEnabled: false,+ topP: 0.8,+ prefillEnabled: false)+ try MacAppSettingsFileStore.save(initial, forModelDirectory: modelDirectory)++ let model = AppModel(+ modelDirectory: modelDirectory,+ settingsPersistenceEnabled: true)+ #expect(model.maxContextTokens == 8_192)+ #expect(model.runtimeOptions.expertCacheSlots == 24)+ #expect(model.temperature == 0.4)+ #expect(!model.topKEnabled)+ #expect(model.topK == 32)+ #expect(!model.topPEnabled)+ #expect(model.topP == 0.8)+ #expect(!model.runtimeOptions.prefillEnabled)++ model.temperature = 0.6+ model.runtimeOptions.expertCacheSlots = 32+ model.runtimeOptions.prefillEnabled = true+ let beforeGenerate = MacAppSettingsFileStore.loadOrCreate(+ forModelDirectory: modelDirectory)+ #expect(beforeGenerate == initial)++ model.loadState = .ready(modelDirectory: modelDirectory, loadSeconds: 0)+ model.promptText = "Save these settings"+ model.run()+ let saved = MacAppSettingsFileStore.loadOrCreate(+ forModelDirectory: modelDirectory)+ #expect(saved.temperature == 0.6)+ #expect(saved.expertCacheSlots == 32)+ #expect(saved.prefillEnabled)+ model.cancel()+ }++ private func makeTemporaryRoot() throws -> URL {+ let root = FileManager.default.temporaryDirectory+ .appendingPathComponent("MacAppSettingsTests-\(UUID().uuidString)",+ isDirectory: true)+ try FileManager.default.createDirectory(+ at: root,+ withIntermediateDirectories: true)+ return root+ }+}diff --git a/Tests/TurboFieldfareApp/Core/Inference/AppGenerationRequestTests.swift b/Tests/TurboFieldfareApp/Core/Inference/AppGenerationRequestTests.swiftindex e8452116..643574d2 100644--- a/Tests/TurboFieldfareApp/Core/Inference/AppGenerationRequestTests.swift+++ b/Tests/TurboFieldfareApp/Core/Inference/AppGenerationRequestTests.swift@@ -7,8 +7,8 @@ import Testing@Test func defaultRequestUsesDocumentedSamplingPolicy() {let request = AppGenerationRequest(modelDirectory: existingDirectory, prompt: "hello")- #expect(request.maxNewTokens == 1_024)- #expect(request.temperature == 1.0)+ #expect(request.maxNewTokens == 4_096)+ #expect(request.temperature == 0.2)#expect(request.topK == 64)#expect(request.topP == 0.95)#expect(request.repetitionPenalty == 1)diff --git a/Tests/TurboFieldfareApp/Core/Inference/DecodeProtocolTests.swift b/Tests/TurboFieldfareApp/Core/Inference/DecodeProtocolTests.swiftindex 006f1159..f8a1cfc7 100644--- a/Tests/TurboFieldfareApp/Core/Inference/DecodeProtocolTests.swift+++ b/Tests/TurboFieldfareApp/Core/Inference/DecodeProtocolTests.swift@@ -9,7 +9,6 @@ import TurboFieldfareDecodeProtocolexpertCachePolicy: "lru",prefillEnabled: false,prefillChunkTokens: 64,- turboQuantKVEnabled: true,rdadvisePolicy: "adaptive",modelVerification: "trusted-install")let request = DecodeLoadRequest(diff --git a/Tests/TurboFieldfareApp/Core/Inference/RealInferenceClientStateTests.swift b/Tests/TurboFieldfareApp/Core/Inference/RealInferenceClientStateTests.swiftindex f67fffbe..fe179ad4 100644--- a/Tests/TurboFieldfareApp/Core/Inference/RealInferenceClientStateTests.swift+++ b/Tests/TurboFieldfareApp/Core/Inference/RealInferenceClientStateTests.swift@@ -79,7 +79,7 @@ import TurboFieldfareprompt: "hello")let config = RealInferenceSession.generationConfig(for: request)- #expect(config.temperature == 1.0)+ #expect(config.temperature == 0.2)#expect(config.topK == 64)#expect(config.topP == 0.95)#expect(config.repetitionPenalty == 1)@@ -108,8 +108,7 @@ import TurboFieldfarelet request = AppGenerationRequest(modelDirectory: modelDirectory,prompt: "hello",- runtimeOptions: AppRuntimeOptions(prefillEnabled: false,- turboQuantKVEnabled: true))+ runtimeOptions: AppRuntimeOptions(prefillEnabled: false))var failure: AppInferenceError?var partial: AppDiagnostics?diff --git a/Tests/TurboFieldfareApp/Core/Installation/AppModelInstallFixture.swift b/Tests/TurboFieldfareApp/Core/Installation/AppModelInstallFixture.swiftindex 92a77e3a..1de55a10 100644--- a/Tests/TurboFieldfareApp/Core/Installation/AppModelInstallFixture.swift+++ b/Tests/TurboFieldfareApp/Core/Installation/AppModelInstallFixture.swift@@ -1,6 +1,7 @@import Darwinimport Foundationimport TurboFieldfare+@testable import TurboFieldfareAppCorefunc makeCompleteModelInstall(_ tag: String) throws -> URL {let directory = FileManager.default.temporaryDirectory@@ -26,6 +27,14 @@ func makeCompleteModelInstall(_ tag: String) throws -> URL {"versionMinor": 0,"flags": ["streamingPresent": true],"modelID": "test/gemma-4-26b-a4b",+ "sourceSnapshotHash": "sha256:" + AppModelInstallDescriptor.default.sourceIndexSHA256,+ "quant": [+ "embedding": quantSlot(4),+ "attention": quantSlot(4),+ "router": quantSlot(8),+ "sharedExpert": quantSlot(4),+ "routedExpert": quantSlot(4),+ ],"arch": ["hiddenSize": arch.hiddenSize,"ffnIntermediate": arch.intermediateSize,@@ -70,3 +79,13 @@ func makeCompleteModelInstall(_ tag: String) throws -> URL {try receiptData.write(to: directory.appendingPathComponent("verified-install.json"))return directory}++private func quantSlot(_ weightBits: Int) -> [String: Any] {+ [+ "weightBits": weightBits,+ "scheme": "affine",+ "scaleType": "bf16",+ "biasType": "bf16",+ "groupSize": Quantization.groupSize,+ ]+}diff --git a/Tests/TurboFieldfareApp/Core/Installation/AppModelInstallTests.swift b/Tests/TurboFieldfareApp/Core/Installation/AppModelInstallTests.swiftindex e59f19d9..bba3194d 100644--- a/Tests/TurboFieldfareApp/Core/Installation/AppModelInstallTests.swift+++ b/Tests/TurboFieldfareApp/Core/Installation/AppModelInstallTests.swift@@ -35,20 +35,62 @@ import TurboFieldfareRepackCore#expect(model.canLoadModel)}+ @MainActor+ @Test func checkAgainDetectsModelInstalledAfterLaunch() throws {+ let directory = try makeCompleteModelInstall("external-install")+ let stagedDirectory = directory.deletingLastPathComponent()+ .appendingPathComponent("staged-\(UUID().uuidString).gturbo")+ try FileManager.default.moveItem(at: directory, to: stagedDirectory)+ let model = AppModel(+ modelDirectory: directory,+ client: MockLifecycleInferenceClient(),+ installer: MockModelInstallerClient())++ #expect(model.requiresModelInstallation)+ defer { try? FileManager.default.removeItem(at: directory) }+ try FileManager.default.moveItem(at: stagedDirectory, to: directory)++ model.refreshInstallReadiness()++ #expect(model.isModelInstalled)+ #expect(!model.requiresModelInstallation)+ #expect(model.canLoadModel)+ }++ @MainActor+ @Test func checkAgainUsesCurrentModelLocation() throws {+ let initialDirectory = temporaryInstallPath("initial-location")+ let currentDirectory = try makeCompleteModelInstall("current-location")+ defer { try? FileManager.default.removeItem(at: currentDirectory) }+ let model = AppModel(+ modelDirectory: initialDirectory,+ client: MockLifecycleInferenceClient(),+ installer: MockModelInstallerClient())++ model.modelPathText = currentDirectory.path+ model.recheckModelAtCurrentLocation()++ #expect(model.modelPathText == currentDirectory.standardizedFileURL.path)+ #expect(model.isModelInstalled)+ #expect(model.canLoadModel)+ }+@MainActor@Test func defaultInstallDescriptorMatchesPinnedAudit() {let descriptor = AppModelInstallDescriptor.default- #expect(descriptor.displayName == "gemma-4-26B-A4B-TurboQuant-MLX-4bit")- #expect(descriptor.repoID == "majentik/gemma-4-26B-A4B-TurboQuant-MLX-4bit")- #expect(descriptor.revision == "cc499c86a958ea7f05cffaa91c7e7243240dabbe")- #expect(descriptor.approximateDownloadBytes == 14_952_958_284)- #expect(descriptor.installedBytes == 14_527_372_034)- #expect(descriptor.requiredFreeBytes == 15_668_222_722)+ #expect(descriptor.displayName == "Gemma 4 26B-A4B IT 4-bit")+ #expect(descriptor.repoID == "mlx-community/gemma-4-26b-a4b-it-4bit")+ #expect(descriptor.revision == "0d77464eeb233a2da68ebf9d7dc4edaac7db956d")+ #expect(descriptor.sourceIndexSHA256 == "bf198c9f5ea6462addca1966e5dd669c407537a876e82cf06db9084c5c850b13")+ #expect(descriptor.approximateDownloadBytes == 14_620_479_420)+ #expect(descriptor.installedBytes == 14_291_921_884)+ #expect(descriptor.requiredFreeBytes == 15_432_772_572)}@MainActor@Test func insufficientSpaceDisablesInstallAndExposesShortfall() {let requirement = AppModelInstallRequirement(+ probePath: "/volume",requiredBytes: 100,availableBytes: 40)let installer = MockModelInstallerClient(requirement: requirement)@@ -147,6 +189,7 @@ import TurboFieldfareRepackCore}let expected = AppModelInstallRequirement(+ probePath: "/volume",requiredBytes: 120,availableBytes: 45)#expect(model.installReadiness == .insufficientSpace(expected))diff --git a/Tests/TurboFieldfareApp/Core/Installation/AppModelInstallationProbeTests.swift b/Tests/TurboFieldfareApp/Core/Installation/AppModelInstallationProbeTests.swiftindex 877a6ac7..d039efd3 100644--- a/Tests/TurboFieldfareApp/Core/Installation/AppModelInstallationProbeTests.swift+++ b/Tests/TurboFieldfareApp/Core/Installation/AppModelInstallationProbeTests.swift@@ -39,4 +39,22 @@ import Testingreturn}}++ @Test func differentCheckpointIsPartial() throws {+ let url = try makeCompleteModelInstall("wrong-checkpoint")+ defer { try? FileManager.default.removeItem(at: url) }+ let descriptor = AppModelInstallDescriptor(+ displayName: "different",+ repoID: "example/different",+ revision: "revision",+ sourceIndexSHA256: String(repeating: "f", count: 64),+ approximateDownloadBytes: 1,+ installedBytes: 1,+ rangeStagingBytes: 1,+ reserveBytes: 1)+ guard case .partial = AppModelInstallationProbe.status(at: url, descriptor: descriptor) else {+ Issue.record("expected checkpoint mismatch to be partial")+ return+ }+ }}diff --git a/Tests/TurboFieldfareApp/Core/State/AppModelLoadStateTests.swift b/Tests/TurboFieldfareApp/Core/State/AppModelLoadStateTests.swiftindex 6f2ff6c2..0e49b676 100644--- a/Tests/TurboFieldfareApp/Core/State/AppModelLoadStateTests.swift+++ b/Tests/TurboFieldfareApp/Core/State/AppModelLoadStateTests.swift@@ -56,7 +56,7 @@ import Testing#expect(!model.canLoadModel)#expect(model.canUnloadModel)- model.runtimeOptions.turboQuantKVEnabled.toggle()+ model.runtimeOptions.rdadvisePolicy = .bounded#expect(model.canReloadModel)#expect(model.canUnloadModel)#expect(!model.canRun)@@ -155,7 +155,7 @@ import Testing@MainActor@Test func applyLoadStateUpdatesPresentation() throws {- let directory = try makeCompleteModelInstall("presentation")+ let directory = try makeCompleteModelInstall("load-presentation")defer { try? FileManager.default.removeItem(at: directory) }let model = AppModel(modelDirectory: directory)model.applyLoadState(.loading(.verifyingWeights))diff --git a/Tests/TurboFieldfareApp/Core/State/AppModelServiceReportingTests.swift b/Tests/TurboFieldfareApp/Core/State/AppModelServiceReportingTests.swiftindex 2829809b..48fd1883 100644--- a/Tests/TurboFieldfareApp/Core/State/AppModelServiceReportingTests.swift+++ b/Tests/TurboFieldfareApp/Core/State/AppModelServiceReportingTests.swift@@ -13,10 +13,13 @@ import Testingclient.generationTranscriptMailbox.append("lossless output")#expect(model.currentProcessMemoryBytes == 2_100_000_000)- #expect(model.outputPlainText == "lossless output")+ #expect(model.outputResponsePlainText == "lossless output")+ #expect(model.outputConversationPlainText == "Answer:\nlossless output")model.clearOutput()#expect(client.generationTranscriptMailbox.completeText.isEmpty)+ #expect(model.outputResponsePlainText.isEmpty)+ #expect(model.outputConversationPlainText.isEmpty)}@MainActor@@ -33,7 +36,8 @@ import Testing#expect(client.generationTranscriptMailbox.completeText.isEmpty)#expect(model.outputPromptText == "new prompt")- #expect(model.outputPlainText == "new prompt")+ #expect(model.outputResponsePlainText.isEmpty)+ #expect(model.outputConversationPlainText == "You:\nnew prompt")}}diff --git a/Tests/TurboFieldfareApp/Core/State/AppModelTests.swift b/Tests/TurboFieldfareApp/Core/State/AppModelTests.swiftindex aa615e14..197c373b 100644--- a/Tests/TurboFieldfareApp/Core/State/AppModelTests.swift+++ b/Tests/TurboFieldfareApp/Core/State/AppModelTests.swift@@ -10,19 +10,16 @@ import Testingmodel.promptText = "go"let request = try model.makeRequest()- #expect(request.temperature == 1.0)+ #expect(request.temperature == 0.2)#expect(request.topK == 64)#expect(request.topP == 0.95)- #expect(request.maxNewTokens == 1_024)+ #expect(request.maxNewTokens == 4_096)#expect(request.repetitionPenalty == 1)#expect(!request.isPureGreedy)#expect(request.runtimeOptions.expertCacheSlots == 16)#expect(request.runtimeOptions.expertCachePolicy == .lfu)#expect(request.runtimeOptions.rdadvisePolicy == .off)- #expect(!request.runtimeOptions.turboQuantKVEnabled)#expect(request.runtimeOptions.prefillEnabled)- #expect(request.runtimeOptions.prefillChunkTokens == 128)- #expect(request.runtimeOptions.modelVerification == .fullSha256)}@MainActor@@ -40,19 +37,6 @@ import Testing#expect(!model.canRun)}- @MainActor- @Test func disabledRepetitionPenaltyNeutralizesRequest() throws {- let model = AppModel()- model.modelPathText = FileManager.default.temporaryDirectory.path- model.promptText = "go"- model.repetitionPenalty = 1.4-- model.repetitionPenaltyEnabled = true- #expect(try model.makeRequest().repetitionPenalty == 1.4)- model.repetitionPenaltyEnabled = false- #expect(try model.makeRequest().repetitionPenalty == 1.0)- }-@MainActor@Test func disablingTopKNeutralizesBothTruncationControls() throws {let model = AppModel()@@ -98,12 +82,34 @@ import Testingmodel.applyLoadState(.ready(modelDirectory: directory, loadSeconds: 0))#expect(!model.hasStaleLoadedRuntime)- model.runtimeOptions.turboQuantKVEnabled = true+ model.runtimeOptions.rdadvisePolicy = .bounded+ #expect(model.hasStaleLoadedRuntime)+ }++ @MainActor+ @Test func contextChangeMarksReadySessionStale() {+ let model = AppModel(client: MockLifecycleInferenceClient())+ let directory = FileManager.default.temporaryDirectory+ model.modelPathText = directory.path+ model.applyLoadState(.ready(modelDirectory: directory, loadSeconds: 0))++ #expect(!model.hasStaleLoadedRuntime)+ model.maxContextTokens = AppContextLengthOption.eightK.tokens#expect(model.hasStaleLoadedRuntime)}@MainActor- @Test func prefillChangeMarksReadySessionStale() {+ @Test func appResponseLimitUsesSelectedContext() throws {+ let model = AppModel()+ model.modelPathText = FileManager.default.temporaryDirectory.path+ model.promptText = "go"+ model.maxContextTokens = AppContextLengthOption.sixtyFourK.tokens++ #expect(try model.makeRequest().maxNewTokens == AppContextLengthOption.sixtyFourK.tokens)+ }++ @MainActor+ @Test func requestTimePrefillChangeDoesNotMarkReadySessionStale() {let model = AppModel(client: MockLifecycleInferenceClient())let directory = FileManager.default.temporaryDirectorymodel.modelPathText = directory.path@@ -111,7 +117,7 @@ import Testingmodel.runtimeOptions.prefillEnabled = false- #expect(model.hasStaleLoadedRuntime)+ #expect(!model.hasStaleLoadedRuntime)}@MainActor@@ -121,7 +127,7 @@ import Testingmodel.modelPathText = FileManager.default.temporaryDirectory.pathmodel.loadState = .ready(modelDirectory: FileManager.default.temporaryDirectory, loadSeconds: 1)model.promptText = "go"- model.maxNewTokens = 4+ model.maxNewTokensOverride = 4model.run()for _ in 0..<200 where model.isRunning {@@ -139,20 +145,22 @@ import Testinglet client = MockInferenceClient(response: "answer", tokenDelayNanos: 1)let model = readyModel(client: client)model.promptText = "original prompt"- model.maxNewTokens = 1+ model.maxNewTokensOverride = 1model.run()#expect(model.outputPromptText == "original prompt")#expect(model.hasOutputTranscript)- #expect(model.outputPlainText == "original prompt")+ #expect(model.outputResponsePlainText.isEmpty)+ #expect(model.outputConversationPlainText == "You:\noriginal prompt")model.promptText = "edited prompt"await waitForIdle(model)#expect(model.outputPromptText == "original prompt")- #expect(model.outputPlainText == "original promptanswer")- #expect(model.outputPlainText.contains("original prompt"))- #expect(!model.outputPlainText.contains("edited prompt"))+ #expect(model.outputResponsePlainText == "answer")+ #expect(model.outputConversationPlainText+ == "You:\noriginal prompt\n\nAnswer:\nanswer")+ #expect(!model.outputConversationPlainText.contains("edited prompt"))}@MainActor@@ -165,7 +173,7 @@ import Testingmodel.applyLoadState(.ready(modelDirectory: directory, loadSeconds: 0))#expect(model.canRun)- model.runtimeOptions.turboQuantKVEnabled = true+ model.runtimeOptions.rdadvisePolicy = .bounded#expect(model.hasStaleLoadedRuntime)#expect(!model.canRun)#expect(model.canReloadModel)@@ -178,7 +186,7 @@ import Testingclient.prefillSteps = 0let model = readyModel(client: client)model.promptText = "stop after token"- model.maxNewTokens = 10+ model.maxNewTokensOverride = 10model.run()for _ in 0..<200 where model.liveTokenCount == 0 {@@ -194,11 +202,16 @@ import Testing#expect(!model.isCancellationPending)#expect(model.error == .cancelled)#expect(model.hasOutputTranscript)+ #expect(!model.outputResponsePlainText.isEmpty)+ #expect(model.outputConversationPlainText.hasPrefix(+ "You:\nstop after token\n\nAnswer:\n"))model.clearOutput()#expect(!model.hasOutputTranscript)#expect(model.outputPromptText.isEmpty)#expect(model.outputText.isEmpty)+ #expect(model.outputResponsePlainText.isEmpty)+ #expect(model.outputConversationPlainText.isEmpty)#expect(model.error == nil)}@@ -221,6 +234,8 @@ import Testing#expect(!model.isRunning)#expect(model.outputPromptText == "prefill prompt")#expect(model.outputText.isEmpty)+ #expect(model.outputResponsePlainText.isEmpty)+ #expect(model.outputConversationPlainText == "You:\nprefill prompt")#expect(model.hasOutputTranscript)model.clearOutput()diff --git a/Tests/TurboFieldfareApp/MacPresentation/ResponseMarkdownRendererTests.swift b/Tests/TurboFieldfareApp/MacPresentation/ResponseMarkdownRendererTests.swiftnew file mode 100644index 00000000..4cebe1ca--- /dev/null+++ b/Tests/TurboFieldfareApp/MacPresentation/ResponseMarkdownRendererTests.swift@@ -0,0 +1,313 @@+import AppKit+import Foundation+import Testing+@testable import TurboFieldfareMacPresentation++@MainActor+@Suite struct ResponseMarkdownRendererTests {+ @Test func rendersSupportedMarkdownWithNativeAttributes() throws {+ let source = """+ # Heading++ A **bold** and *italic* sentence with ~~obsolete~~ text, `inlineCode`, and a [link](https://example.com).++ - first+ - second++ > quoted text++ ```swift+ let answer = 42+ ```++ ---+ """++ let result = ResponseMarkdownRenderer().render(source)+ let text = result.attributedString.string++ #expect(!result.usedFallback)+ #expect(text.contains("Heading"))+ #expect(text.contains("bold"))+ #expect(text.contains("italic"))+ #expect(text.contains("•\tfirst\n•\tsecond"))+ #expect(text.contains("│\tquoted text"))+ #expect(text.contains("let answer = 42"))+ #expect(text.contains("────────────────"))+ #expect(!text.contains("**"))+ #expect(!text.contains("```"))++ let linkRange = (text as NSString).range(of: "link")+ #expect(result.attributedString.attribute(.link, at: linkRange.location,+ effectiveRange: nil) == nil)+ let linkColor = result.attributedString.attribute(+ .foregroundColor, at: linkRange.location, effectiveRange: nil) as? NSColor+ #expect(linkColor?.isEqual(NSColor.linkColor) == true)+ #expect(result.attributedString.attribute(.underlineStyle,+ at: linkRange.location,+ effectiveRange: nil) as? Int+ == NSUnderlineStyle.single.rawValue)++ let codeRange = (text as NSString).range(of: "inlineCode")+ let codeFont = try #require(result.attributedString.attribute(+ .font, at: codeRange.location, effectiveRange: nil) as? NSFont)+ #expect(codeFont.fontDescriptor.symbolicTraits.contains(.monoSpace))+ #expect(result.attributedString.attribute(+ .backgroundColor, at: codeRange.location, effectiveRange: nil) != nil)++ let strikeRange = (text as NSString).range(of: "obsolete")+ #expect(result.attributedString.attribute(+ .strikethroughStyle, at: strikeRange.location, effectiveRange: nil) != nil)+ }++ @Test func unfinishedFenceFallsBackToExactRawText() {+ let source = "Before\n\n```python\nprint('unfinished')"+ let result = ResponseMarkdownRenderer().render(source)++ #expect(result.usedFallback)+ #expect(result.attributedString.string == source)+ }++ @Test func unsupportedHTMLTableAndImageStayReadableAsRawText() {+ let renderer = ResponseMarkdownRenderer()+ let samples = [+ "<div>Never execute this</div>",+ "| A | B |\n|---|---|\n| 1 | 2 |",+ "",+ ]++ for source in samples {+ let result = renderer.render(source)+ #expect(result.usedFallback)+ #expect(result.attributedString.string == source)+ }+ }++ @Test func latexRemainsReadableText() {+ let source = "Cosine is $\\frac{u \\cdot v}{||u|| ||v||}$."+ let result = ResponseMarkdownRenderer().render(source)++ #expect(!result.usedFallback)+ #expect(result.attributedString.string.contains("\\frac"))+ #expect(result.attributedString.string.contains("\\cdot"))+ }++ @Test func boldOnlyModelHeadingStaysOnItsOwnLine() {+ let source = "**Origins**\nFieldfares arrive from northern Europe."+ let result = ResponseMarkdownRenderer().render(source)++ #expect(!result.usedFallback)+ #expect(result.attributedString.string+ == "Origins\n\nFieldfares arrive from northern Europe.")+ }+}++@MainActor+@Suite struct InstructionTranscriptDocumentControllerTests {+ @Test func appAccentMatchesProductRGB() {+ let color = TurboFieldfareMacTheme.accentNSColor+ .usingColorSpace(.sRGB)+ #expect(color != nil)+ #expect(abs((color?.redComponent ?? 0) - 106.0 / 255.0) < 0.000_001)+ #expect(abs((color?.greenComponent ?? 0) - 186.0 / 255.0) < 0.000_001)+ #expect(abs((color?.blueComponent ?? 0) - 113.0 / 255.0) < 0.000_001)+ }++ @Test func rebuildsThenAppendsOnlyNewResponseSuffix() {+ let storage = NSMutableAttributedString()+ let controller = InstructionTranscriptDocumentController()++ let first = controller.synchronize(+ storage: storage,+ prompt: "Explain this",+ response: "Hel",+ isTerminal: false)+ let second = controller.synchronize(+ storage: storage,+ prompt: "Explain this",+ response: "Hello",+ isTerminal: false)++ #expect(first.mutation == .rebuilt)+ #expect(second.mutation == .appended)+ #expect(storage.string == "You\nExplain this\n\nAnswer\nHello")+ #expect(storage.string.components(separatedBy: "Answer").count == 2)+ let answerRange = (storage.string as NSString).range(of: "Answer")+ let answerColor = storage.attribute(+ .foregroundColor,+ at: answerRange.location,+ effectiveRange: nil) as? NSColor+ #expect(answerColor?.isEqual(TurboFieldfareMacTheme.accentNSColor) == true)+ #expect(controller.response == "Hello")+ }++ @Test func animatedPrefillPlaceholderIsPresentationOnlyAndFirstResponseRemovesIt() {+ let storage = NSMutableAttributedString()+ let controller = InstructionTranscriptDocumentController()++ let prefilling = controller.synchronize(+ storage: storage,+ prompt: "Explain this",+ response: "",+ isTerminal: false,+ showsPrefillPlaceholder: true)++ #expect(prefilling.mutation == .rebuilt)+ #expect(controller.showsPrefillPlaceholder)+ #expect(storage.string == "You\nExplain this\n\nAnswer\nProcessing your prompt")+ #expect(controller.response.isEmpty)+ #expect(controller.assistantRange.length == 0)++ #expect(controller.advancePrefillAnimation(storage: storage))+ #expect(storage.string.hasSuffix("Processing your prompt."))+ #expect(controller.advancePrefillAnimation(storage: storage))+ #expect(storage.string.hasSuffix("Processing your prompt.."))+ #expect(controller.advancePrefillAnimation(storage: storage))+ #expect(storage.string.hasSuffix("Processing your prompt..."))+ #expect(controller.advancePrefillAnimation(storage: storage))+ #expect(storage.string.hasSuffix("Processing your prompt"))++ let responding = controller.synchronize(+ storage: storage,+ prompt: "Explain this",+ response: "Hello",+ isTerminal: false,+ showsPrefillPlaceholder: true)++ #expect(responding.mutation == .rebuilt)+ #expect(!controller.showsPrefillPlaceholder)+ #expect(storage.string == "You\nExplain this\n\nAnswer\nHello")+ #expect(!storage.string.contains("Processing your prompt"))+ #expect((storage.string as NSString).substring(with: responding.assistantRange)+ == "Hello")+ }++ @Test func processingAnimationPolicyStopsForTextAndTerminalStates() {+ #expect(InstructionTranscriptDocumentController.shouldRunPrefillAnimation(+ response: "", isTerminal: false, requested: true))+ #expect(!InstructionTranscriptDocumentController.shouldRunPrefillAnimation(+ response: "First token", isTerminal: false, requested: true))+ #expect(!InstructionTranscriptDocumentController.shouldRunPrefillAnimation(+ response: "", isTerminal: true, requested: true))+ #expect(!InstructionTranscriptDocumentController.shouldRunPrefillAnimation(+ response: "", isTerminal: false, requested: false))+ }++ @Test func promptChangeOrResponseResetRebuildsWithoutStaleBytes() {+ let storage = NSMutableAttributedString()+ let controller = InstructionTranscriptDocumentController()+ _ = controller.synchronize(+ storage: storage, prompt: "Old", response: "Long response", isTerminal: false)++ let result = controller.synchronize(+ storage: storage, prompt: "New", response: "Short", isTerminal: false)++ #expect(result.mutation == .rebuilt)+ #expect(storage.string == "You\nNew\n\nAnswer\nShort")+ #expect(!storage.string.contains("Old"))+ #expect(!storage.string.contains("Long response"))+ }++ @Test func terminalUpdateFormatsOnlyAssistantRangeAndKeepsRawResponse() {+ let storage = NSMutableAttributedString()+ let controller = InstructionTranscriptDocumentController()+ _ = controller.synchronize(+ storage: storage,+ prompt: "Question",+ response: "**Bold answer**",+ isTerminal: false)++ let result = controller.synchronize(+ storage: storage,+ prompt: "Question",+ response: "**Bold answer**",+ isTerminal: true)++ #expect(result.mutation == .finalized)+ #expect(controller.isFinalized)+ #expect(controller.response == "**Bold answer**")+ #expect(storage.string == "You\nQuestion\n\nAnswer\nBold answer")+ #expect((storage.string as NSString).substring(with: result.assistantRange)+ == "Bold answer")++ let unchanged = storage.copy() as! NSAttributedString+ let repeated = controller.synchronize(+ storage: storage,+ prompt: "Question",+ response: "**Bold answer**",+ isTerminal: true)+ #expect(repeated.mutation == .none)+ #expect(storage.isEqual(to: unchanged))+ }++ @Test func terminalPartialOutputIsReadableAndNextRunRestoresStreamingSource() {+ let storage = NSMutableAttributedString()+ let controller = InstructionTranscriptDocumentController()+ _ = controller.synchronize(+ storage: storage,+ prompt: "Question",+ response: "Partial **answer**",+ isTerminal: true)+ #expect(storage.string.hasSuffix("Partial answer"))++ let result = controller.synchronize(+ storage: storage,+ prompt: "Question",+ response: "Partial **answer**",+ isTerminal: false)+ #expect(result.mutation == .rebuilt)+ #expect(!controller.isFinalized)+ #expect(storage.string.hasSuffix("Partial **answer**"))+ }++ @Test func terminalResponseRendersAgainWhenClosingFenceArrivesLate() {+ let storage = NSMutableAttributedString()+ let controller = InstructionTranscriptDocumentController()+ let partial = "```cpp\nkernel void matmul() {}"+ let complete = partial + "\n```"++ let first = controller.synchronize(+ storage: storage,+ prompt: "Write a Metal kernel",+ response: partial,+ isTerminal: true)+ #expect(first.mutation == .finalized)+ #expect(storage.string.hasSuffix(partial))++ let updated = controller.synchronize(+ storage: storage,+ prompt: "Write a Metal kernel",+ response: complete,+ isTerminal: true)++ #expect(updated.mutation == .finalized)+ #expect(controller.response == complete)+ #expect((storage.string as NSString).substring(with: updated.assistantRange)+ == "kernel void matmul() {}\n")+ #expect(!storage.string.contains("```"))+ }++ @Test func selectionRangesClampToCurrentStorage() {+ let ranges = InstructionTranscriptDocumentController.clampedRanges([+ NSRange(location: 3, length: 20),+ NSRange(location: 50, length: 2),+ ], toLength: 10)++ #expect(ranges == [+ NSRange(location: 3, length: 7),+ NSRange(location: 10, length: 0),+ ])+ }++ @Test func terminalFormattingAlwaysScrollsToBottom() {+ #expect(InstructionTranscriptDocumentController.shouldScrollToBottom(+ wasAtBottom: false,+ mutation: .finalized))+ #expect(InstructionTranscriptDocumentController.shouldScrollToBottom(+ wasAtBottom: true,+ mutation: .appended))+ #expect(!InstructionTranscriptDocumentController.shouldScrollToBottom(+ wasAtBottom: false,+ mutation: .appended))+ }+}diff --git a/Tests/TurboFieldfareRepack/Core/Remote/RemotePayloadCopyTests.swift b/Tests/TurboFieldfareRepack/Core/Remote/RemotePayloadCopyTests.swiftindex 79463e2a..dda8528d 100644--- a/Tests/TurboFieldfareRepack/Core/Remote/RemotePayloadCopyTests.swift+++ b/Tests/TurboFieldfareRepack/Core/Remote/RemotePayloadCopyTests.swift@@ -5,7 +5,7 @@ import Testingfinal class FakeHFURLProtocol: URLProtocol, @unchecked Sendable {nonisolated(unsafe) static var files: [String: Data] = [:]- nonisolated(unsafe) static var commit = "cc499c86a958ea7f05cffaa91c7e7243240dabbe"+ nonisolated(unsafe) static var commit = String(repeating: "a", count: 40)nonisolated(unsafe) static var failures: [String: [FakeFailure]] = [:]nonisolated(unsafe) static var requestCounts: [String: Int] = [:]@@ -153,6 +153,8 @@ enum FakeFailure: Equatable {let remoteTokenizerJSON = Data(#"{"model":{"type":"BPE"}}"#.utf8)let remoteTokenizerConfigJSON = Data(#"{"tokenizer_class":"PreTrainedTokenizerFast"}"#.utf8)let remoteSpecialTokensMapJSON = Data(#"{"eos_token":"<eos>"}"#.utf8)+let remoteChatTemplateJinja = Data("{{ bos_token }}".utf8)+let remoteChatTemplateJSON = Data(#"{"chat_template":"{{ bos_token }}"}"#.utf8)@Suite(.serialized)struct RemotePayloadCopyTests {@@ -176,6 +178,8 @@ func remoteFiles(snapshotDir: String,}if includeOptionalTokenizer {files["special_tokens_map.json"] = remoteSpecialTokensMapJSON+ files["chat_template.jinja"] = remoteChatTemplateJinja+ files["chat_template.json"] = remoteChatTemplateJSON}return files}@@ -226,6 +230,10 @@ func assertRemoteTokenizerFilesRecorded(outputDir: String,(tokenizerDir as NSString).appendingPathComponent("tokenizer_config.json"))) == remoteTokenizerConfigJSON)let specialTokensPath = (tokenizerDir as NSString).appendingPathComponent("special_tokens_map.json")#expect(FileManager.default.fileExists(atPath: specialTokensPath) == expectsOptionalSpecialTokens)+ let chatTemplateJinjaPath = (tokenizerDir as NSString).appendingPathComponent("chat_template.jinja")+ #expect(FileManager.default.fileExists(atPath: chatTemplateJinjaPath) == expectsOptionalSpecialTokens)+ let chatTemplateJSONPath = (tokenizerDir as NSString).appendingPathComponent("chat_template.json")+ #expect(FileManager.default.fileExists(atPath: chatTemplateJSONPath) == expectsOptionalSpecialTokens)let manifestData = try Data(contentsOf: URL(fileURLWithPath:(outputDir as NSString).appendingPathComponent("manifest.json")))@@ -235,6 +243,8 @@ func assertRemoteTokenizerFilesRecorded(outputDir: String,#expect(manifestFiles["tokenizer/tokenizer.json"] != nil)#expect(manifestFiles["tokenizer/tokenizer_config.json"] != nil)#expect((manifestFiles["tokenizer/special_tokens_map.json"] != nil) == expectsOptionalSpecialTokens)+ #expect((manifestFiles["tokenizer/chat_template.jinja"] != nil) == expectsOptionalSpecialTokens)+ #expect((manifestFiles["tokenizer/chat_template.json"] != nil) == expectsOptionalSpecialTokens)let receiptData = try Data(contentsOf: URL(fileURLWithPath:(outputDir as NSString).appendingPathComponent(VerifiedInstallReceiptWriter.fileName)))@@ -244,6 +254,8 @@ func assertRemoteTokenizerFilesRecorded(outputDir: String,#expect(receiptFiles["tokenizer/tokenizer.json"] != nil)#expect(receiptFiles["tokenizer/tokenizer_config.json"] != nil)#expect((receiptFiles["tokenizer/special_tokens_map.json"] != nil) == expectsOptionalSpecialTokens)+ #expect((receiptFiles["tokenizer/chat_template.jinja"] != nil) == expectsOptionalSpecialTokens)+ #expect((receiptFiles["tokenizer/chat_template.json"] != nil) == expectsOptionalSpecialTokens)}func assertNoInternalRemoteDirs(outputDir: String) throws {diff --git a/docs/BENCHMARKS.md b/docs/BENCHMARKS.mdindex c51a1d56..d6cca009 100644--- a/docs/BENCHMARKS.md+++ b/docs/BENCHMARKS.md@@ -5,17 +5,16 @@ This page records TurboFieldfare measurements on an 8 GB M2 MacBook Air and agenerated length, cache state, and hardware all change throughput, so rangesacross workloads are not run-to-run variation.-All rows use greedy decoding and the same source checkpoint. TurboFieldfare-uses the model installed by the-[command-line instructions](../README.md#command-line-interface). Decode rate-excludes model installation, model loading, and prompt prefill.+Each table states its workload and decoding settings. TurboFieldfare uses the+model installed by the [command-line instructions](../README.md#command-line-interface).+Decode rate excludes model installation, model loading, and prompt prefill.## Results at a glance| Host and runtime | Decode rate | Reported memory || --- | ---: | ---: || 8 GB M2, TurboFieldfare | 5.10-6.30 tok/s | ~1.9-2.1 GB footprint |-| 24 GB M5 Pro, TurboFieldfare | 31.96-36.08 tok/s | ~2.0-2.2 GB footprint |+| 24 GB M5 Pro, TurboFieldfare | 31-35 tok/s | ~2.1 GB footprint || 24 GB M5 Pro, mlx-lm | 76.33-82.07 tok/s | 8.3-9.8 GB RSS; 14.7-15.3 GB GPU allocation |## M2 measured decode@@ -54,17 +53,24 @@ spent time; it does not describe independent speedups or a performance bound.## M5 measured decode-These rows ran on 2026-07-16 on a 24 GB M5 Pro (`Mac17,8`) with macOS 26.5.1,+These rows ran on 2026-07-20 on a 24 GB M5 Pro (`Mac17,8`) with macOS 26.5.1,Xcode 26.6, and Swift 6.3.3. No profiler or trace mode was active.-One warmup preceded three measured rows per workload. The table reports-medians; the file cache was warm but uncontrolled.+The benchmark uses chat-framed prompts and fixed, non-repeating natural+continuations. This keeps the generated text and expert-routing workload stable+without rewarding a model repetition loop. The complete production sampling+and decode path still runs for every token.++One warmup preceded three fresh-process measurements per workload. The table+reports medians; the file cache was warm but uncontrolled. A separate+free-generation smoke reached the end of each model turn without a repetition+loop.| Prompt / generated tokens | Prefill / TTFT | Decode | Peak RSS / footprint || --- | ---: | ---: | ---: |-| 121 / 64 | 4,980 / 5,606 ms | 31.96 tok/s | 1,764 / 1,893 MiB |-| 527 / 64 | 7,297 / 7,922 ms | 36.08 tok/s | 1,792 / 1,991 MiB |-| 1,017 / 128 | 10,134 / 10,767 ms | 33.96 tok/s | 1,810 / 2,088 MiB |+| 61 / 256 | 5,096 / 5,668 ms | 35.17 tok/s | 1,834 / 2,126 MiB |+| 430 / 256 | 6,762 / 7,325 ms | 34.72 tok/s | 1,851 / 2,142 MiB |+| 3,015 / 256 | 23,038 / 23,610 ms | 31.01 tok/s | 1,835 / 2,126 MiB |## Same-host MLX comparison@@ -87,15 +93,15 @@ deployment path.## Reproduce and contribute a result-The [community benchmark guide](COMMUNITY_BENCHMARKS.md) uses the established-1,017-token prefill fixture followed by 256 greedy decode tokens. It provides-the release CLI command, machine-preparation checklist, three-run policy, and-issue template. The public CLI's timing footer reports the production decode-rate without requiring a separate research benchmark harness.+The [community benchmark guide](COMMUNITY_BENCHMARKS.md) uses short, medium,+and long chat-framed prompts with fixed seeds. It requires coherent output and+a normal end of turn, so a repetition loop cannot become a published speed+result. The public CLI's timing footer reports decode-only throughput without a+separate research harness.-The community workload extends the historical 1,017 / 128 row above to 256-generated tokens. Compare community submissions with other runs of the same-protocol rather than treating them as direct reproductions of that row.+Community runs generate their own output, while the reference table uses fixed+non-repeating continuations for token-for-token stability. Compare community+submissions only when their prompt and generated token counts match.A current checkout may not reproduce a historical number after the runtime,compiler, or operating system changes. Report the commit and all three rowsdiff --git a/docs/COMMUNITY_BENCHMARKS.md b/docs/COMMUNITY_BENCHMARKS.mdindex d3eaf03d..ab60368b 100644--- a/docs/COMMUNITY_BENCHMARKS.md+++ b/docs/COMMUNITY_BENCHMARKS.md@@ -1,56 +1,38 @@# Contribute a benchmark result-Results from other Apple Silicon Macs help show where TurboFieldfare runs well-and where it needs more work. This guide uses the-[canonical 1K prompt](benchmark-prompts/prefill-1024.txt) from the project's-prefill and decode benchmarks. It contains 1,017 model tokens including BOS.-Each run generates 256 greedy tokens so reports from different machines remain-comparable.+TurboFieldfare's community benchmark uses three chat-framed generation cases:+a short explanation, a medium design review, and a long document synthesis.+They exercise different prompt lengths and require coherent text that reaches+the end of the model turn. A repeating calibration prompt is not a valid speed+result because repeated expert choices can make decode artificially fast.-This is an explicit reproducibility workload, not the interactive product-default. The app and CLI normally allow up to 1,024 new tokens and sample with-temperature `1.0`, Top-K `64`, and Top-P `0.95`; the commands below override-those values with a fixed 256-token greedy decode.+The frozen prompts are in+[`benchmark-prompts/real-generation-v1/`](benchmark-prompts/real-generation-v1/).+Runs use the app sampling defaults with fixed seeds: temperature `0.2`, Top-K+`64`, Top-P `0.95`, a 4,096-token context, and up to 1,024 generated tokens.-The public package uses `TurboFieldfareCLI` for this measurement. Its timing-footer runs the production defaults and reports decode-only tokens per second.-It excludes model installation, model loading, and prompt prefill.--## Before you run+## Prepare the MacInstall the model with the [README instructions](../README.md#command-line-interface),-then prepare the Mac:--1. Connect a laptop to power and turn off Low Power Mode. Use the normal- Automatic energy mode unless you clearly report another mode.-2. Build the release executable before measuring:+connect a laptop to power, turn off Low Power Mode, quit other demanding apps,+and build the release CLI:- ```bash- swift build -c release --product TurboFieldfareCLI- ```--3. Quit every app you can, leaving only Terminal. In particular, close the- TurboFieldfare Mac app, Xcode, browsers, video calls, games, screen recorders,- local model runners, downloads, backups, and file indexing that you started.-4. Let background CPU activity and the Mac's temperature settle.-5. Check for another model process:+```bash+swift build -c release --product TurboFieldfareCLI+```- ```bash- pgrep -fl 'TurboFieldfareMac|TurboFieldfareDecodeService|TurboFieldfareCLI|TurboFieldfarePackageTests|swiftpm-testing-helper|mlx_lm|mlx-lm'- ```+Confirm that no other model process is running:- Continue only when this prints nothing. Quit a listed app normally; do not- start two model runs at once.+```bash+pgrep -fl 'TurboFieldfareMac|TurboFieldfareDecodeService|TurboFieldfareCLI|TurboFieldfarePackageTests|swiftpm-testing-helper|mlx_lm|mlx-lm'+```-Do not change the prompt, token count, temperature, or public runtime defaults-for the standard result.+Continue only when that command prints nothing.## Record the machine-From the repository root, collect a privacy-safe system summary:-```bash-mkdir -p benchmark-results+mkdir -p benchmark-results/system benchmark-results/warmup benchmark-results/measured{git status --shortgit rev-parse HEAD@@ -59,105 +41,81 @@ mkdir -p benchmark-resultssystem_profiler SPHardwareDataType |awk -F': ' '/Model Name|Model Identifier|Chip|Total Number of Cores|Memory/ { print $1 ": " $2 }'shasum -a 256 scratch/gemma4.gturbo/manifest.json- shasum -a 256 docs/benchmark-prompts/prefill-1024.txt-} 2>&1 | tee benchmark-results/system.txt+ shasum -a 256 docs/benchmark-prompts/real-generation-v1/*.json+} 2>&1 | tee benchmark-results/system/system.txt```-An empty first line from `git status --short` means the checkout is clean. If it-prints changes, either use a clean checkout or describe those changes in the-report. The filtered hardware command omits the serial number and hardware UUID,-but review `benchmark-results/system.txt` before sharing it.+Review the system file before sharing it. The filtered hardware command omits+the serial number and hardware UUID.-## Run the fixed workload+## Run the cases-First run one warmup. It also confirms that the model loads and the prompt-completes:+Run one discarded warmup for each case:```bash-.build/release/TurboFieldfareCLI \- --model scratch/gemma4.gturbo \- --prompt "$(cat docs/benchmark-prompts/prefill-1024.txt)" \- --max-new 256 \- --max-context 4096 \- --temperature 0 \- > benchmark-results/warmup.txt 2>&1--tail -n 2 benchmark-results/warmup.txt+for case_seed in \+ short-explanation:20260721 \+ medium-review:20260722 \+ long-synthesis:20260723; do+ case_id="${case_seed%%:*}"+ seed="${case_seed##*:}"+ .build/release/TurboFieldfareCLI \+ --model scratch/gemma4.gturbo \+ --messages-file "docs/benchmark-prompts/real-generation-v1/${case_id}.json" \+ --max-new 1024 \+ --max-context 4096 \+ --temperature 0.2 \+ --top-k 64 \+ --top-p 0.95 \+ --seed "$seed" \+ > "benchmark-results/warmup/${case_id}.stdout" \+ 2> "benchmark-results/warmup/${case_id}.stderr"+done```-Then run three measured rows, sequentially:+Then run the three measured cases in fresh processes:```bash-for run in 1 2 3; do- output="benchmark-results/run-${run}.txt"+for case_seed in \+ short-explanation:20260721 \+ medium-review:20260722 \+ long-synthesis:20260723; do+ case_id="${case_seed%%:*}"+ seed="${case_seed##*:}".build/release/TurboFieldfareCLI \--model scratch/gemma4.gturbo \- --prompt "$(cat docs/benchmark-prompts/prefill-1024.txt)" \- --max-new 256 \+ --messages-file "docs/benchmark-prompts/real-generation-v1/${case_id}.json" \+ --max-new 1024 \--max-context 4096 \- --temperature 0 \- > "$output" 2>&1 || break- tail -n 2 "$output"+ --temperature 0.2 \+ --top-k 64 \+ --top-p 0.95 \+ --seed "$seed" \+ > "benchmark-results/measured/${case_id}.stdout" \+ 2> "benchmark-results/measured/${case_id}.stderr"done-```--Each successful file ends with a timing footer. Confirm that it contains this-workload shape:-```text-prefill=1017tok new=256tok-```--Collect the three timing lines for easy copy and paste:--```bash-grep -h '^\[stop=' benchmark-results/run-*.txt |+grep -h '^\[stop=' benchmark-results/measured/*.stderr |tee benchmark-results/summary.txt```-This protocol uses one warmup followed by three fresh CLI processes. The file-cache is warm but uncontrolled. Do not purge caches or average these rows with-runs made under different conditions.+Every measured footer must say `stop=endOfTurn`. Read the three output files as+well: reject the result if an answer loops, repeats a block, or ends incomplete.+Report the prompt and generated token counts from each footer because different+output tokens create a different routing workload.## Report the result-Open an issue in this repository with the title-`Benchmark: <chip>, <memory>, <macOS version>`. Paste this template:--````markdown-## TurboFieldfare benchmark--- Energy mode: Automatic / High Power / other-- Connected to power: yes / no-- Other apps: quit / list anything left open-- Thermal state before run: settled / uncertain-- Protocol changes: none / describe every change--### System--```text-Paste benchmark-results/system.txt here.-```--### Results--```text-Paste benchmark-results/summary.txt here.-```--### Notes--Add unexpected output, errors, throttling, or other observations.-````--Attach the three `run-*.txt` files when possible. They contain the generated-completion and timing footer, which helps us spot incomplete or non-equivalent-runs.+Open an issue titled `Benchmark: <chip>, <memory>, <macOS version>` and include:-If you want to test a different app setting or code change, submit the standard-result first. Then change one thing, repeat the same warmup and three-run policy,-and label the follow-up as experimental. Never combine rows from different-settings into one standard result.+- `benchmark-results/system/system.txt`;+- `benchmark-results/summary.txt`;+- the three measured stdout and stderr files;+- energy mode, whether the Mac was connected to power, and any other active+ workload; and+- any output-quality problem or protocol change.-See [Benchmarks](BENCHMARKS.md) for the current reference measurements and how-to interpret comparisons.+Compare rows only when the case, prompt tokens, generated tokens, settings, and+stop reason match. The [reference M5 range](BENCHMARKS.md#m5-measured-decode)+uses controlled non-repeating continuations for stable token-for-token+measurement, while this public protocol checks autonomous product generation.diff --git a/docs/IMPLEMENTATION_REFERENCES.md b/docs/IMPLEMENTATION_REFERENCES.mdindex 91c99bcf..7781adce 100644--- a/docs/IMPLEMENTATION_REFERENCES.md+++ b/docs/IMPLEMENTATION_REFERENCES.md@@ -23,10 +23,12 @@ included for broader design context rather than a line-level claim.and [MLX-VLM Gemma 4](https://github.com/Blaizzy/mlx-vlm/blob/84f43753380355c0455a2bafb291d4b7cbcf81d1/mlx_vlm/models/gemma4/language.py)supplied independent implementation checks. MLX-LM also served as thebounded logit and quality reference.-- The [Majentik Gemma 4 MLX 4-bit checkpoint](https://huggingface.co/majentik/gemma-4-26B-A4B-TurboQuant-MLX-4bit),- pinned at [`cc499c86`](https://huggingface.co/majentik/gemma-4-26B-A4B-TurboQuant-MLX-4bit/tree/cc499c86a958ea7f05cffaa91c7e7243240dabbe),- is the source of the weights, configuration, and tokenizer. The repacker- preserves its group-64 MLX affine values rather than requantizing them.+- [`mlx-community/gemma-4-26b-a4b-it-4bit`](https://huggingface.co/mlx-community/gemma-4-26b-a4b-it-4bit),+ pinned at+ [`0d77464e`](https://huggingface.co/mlx-community/gemma-4-26b-a4b-it-4bit/tree/0d77464eeb233a2da68ebf9d7dc4edaac7db956d),+ is the source of the weights, configuration, tokenizer, and chat-template+ sidecars. The repacker preserves its group-64 MLX affine values rather than+ requantizing them.- [Hugging Face swift-transformers](https://github.com/huggingface/swift-transformers)is the direct tokenizer dependency. TurboFieldfare adds bounded streamingdetokenization around it.@@ -86,7 +88,6 @@ included for broader design context rather than a line-level claim.and [vLLM Metal kernels v2](https://github.com/vllm-project/vllm-metal/tree/11f1b453b74c60d113d67f9a5e7fda41500fd5b5/vllm_metal/metal/kernels_v2)were implementation references for transformed and quantized KV caches,fused dequantization, and online-softmax reduction.-- [TurboQuant](https://arxiv.org/abs/2504.19874) informed the transformed and- quantized K4/V4 cache experiments.-- [Open-TQ-Metal](https://arxiv.org/abs/2604.16957) informed the per-group- asymmetric INT4 KV and `affine4g32` experiment.+- [TurboQuant](https://arxiv.org/abs/2504.19874) and+ [Open-TQ-Metal](https://arxiv.org/abs/2604.16957) informed the rejected K4/V4+ KV-cache experiments.diff --git a/docs/OPTIMIZATION_JOURNEY.md b/docs/OPTIMIZATION_JOURNEY.mdindex a12d02a0..1b2699ac 100644--- a/docs/OPTIMIZATION_JOURNEY.md+++ b/docs/OPTIMIZATION_JOURNEY.md@@ -1,13 +1,11 @@-# Optimizing a 14.4 GB model for an 8 GB machine+# Optimizing a 14.3 GB model for an 8 GB machine-TurboFieldfare runs Gemma 4 26B-A4B with about 14.4 GB of packed text-only-weight payload on an 8 GB Apple Silicon machine. The completed installation is-about 14.5 GB after its manifest, expert layout, and tokenizer files. The model-cannot remain resident in memory, so the runtime keeps roughly 1.58 GB of-common weights resident and streams the roughly 11.6 GB routed-expert payload-from NVMe. This constraint shaped the useful optimizations: reduce demand I/O,-expose enough GPU parallelism, and never buy speed by loading the model into-RAM.+TurboFieldfare runs Gemma 4 26B-A4B with a text-only installation of about+14.3 GB on an 8 GB Apple Silicon machine. The model cannot remain resident in+memory, so the runtime keeps the 1.35 GB common model available to Metal and+streams the 12.9 GB routed-expert pool from NVMe. This constraint shaped the+useful optimizations: reduce demand I/O, expose enough GPU parallelism, and+never buy speed by loading the model into RAM.This article covers the experiments that materially changed the runtime. The[experiment inventory](experiments/EXPERIMENT_INVENTORY.md) retains the complete record,@@ -31,8 +29,10 @@ the number of row streams but starved the GPU. Progressive expert overlapadded synchronization and regressed decode. Simple Darwin read hints wereneutral; RDADVISE reversed at longer contexts; and `F_SPECULATIVE_READ`, readreordering, grouped `preadv`, and MTLIO won narrow probes but not broader-runtime gates. Packed K4/V4 saved 82 MiB against the final FP16 ring but failed-the quality gate. A monolithic fusion removed dispatches yet lost throughput.+runtime gates. Packed K4/V4 failed the quality gate and used more memory at+longer contexts than Gemma 4's exact FP16 layout. FP16 uses a fixed circular+cache for 25 sliding-window layers and grows only for the five full-attention+layers.The sections below pair these wins with the nearby failures that clarifiedthem. Changes that claim identical math must preserve exact output; changes@@ -133,12 +133,6 @@ attention by about 3.3x and full 4K attention by about 4.1x. Short-contextdecode stayed nearly flat, whereas long-context GPU time in that phase fellabout 28% as attention's share of the step grew.-A later MLX-style geometry reduced isolated full-attention time by roughly-71–74%, yet complete decode improved only 1.30–1.59%. The measurements did not-conflict. Only five of thirty layers use full attention, and attention occupied-a small fraction of these token steps. The microbenchmark proved that the-geometry worked; the full pass measured how often that faster work mattered.-Chunked prefill replaced scalar prompt replay. Increasing the bounded chunkfrom 32 to 128 reduced a 1,017-token prefill from 92.89 to 52.35 seconds.Staged affine MPP then dequantized a small FP16 tile, ran the hardware matrix@@ -190,13 +184,11 @@ also failed to beat bounded parallel `pread`, which remained the productionpath. [The expert I/O record](experiments/summaries/01-model-install-and-expert-io.md)keeps the individual controls and outcomes.-Packed K4/V4 KV storage also looked stronger against an obsolete control. It-used about 223 MiB at 4K versus roughly 880 MiB for the old linear FP16 cache.-An exact FP16 ring then exploited the model's 25 sliding-window layers and-required only about 305 MiB, reducing K4/V4's incremental saving to 82 MiB.-The packed path subsequently lost 5.0781 top-1 percentage points and worsened-mean negative log-likelihood. It remains an explicit experiment; exact FP16 is-the default.+At 4K, packed K4/V4 saved only about 82 MiB compared with exact FP16. That+small advantage disappeared as context grew: the packed cache grew across all+30 attention layers, while FP16 used a fixed circular cache for 25 of them.+Packed K4/V4 became larger at roughly 6.4K and also produced worse results+across the full quality evaluation. It was rejected and removed.Fusion produced three different outcomes. Targeted QKV, layer-tail, androw-based head fusions reached production after parity checks and whole-stepdiff --git a/docs/RUNTIME_CONTROLS.md b/docs/RUNTIME_CONTROLS.mdindex 270927d0..8dc08b4e 100644--- a/docs/RUNTIME_CONTROLS.md+++ b/docs/RUNTIME_CONTROLS.md@@ -1,22 +1,20 @@# Runtime controls-The Mac app exposes a small set of runtime controls in its fixed right settings-pane. The defaults are the supported production configuration. Change one-control at a time, reload the model, and restore the defaults before normal-use.+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.## Generation controls-The Mac app and CLI share these interactive defaults:+The Mac app and CLI expose these generation controls:| Control | Mac values | CLI flag | Default | Effect || --- | --- | --- | --- | --- |-| Maximum response | 1...4,096 tokens | `--max-new` | 1,024 | Caps newly generated tokens. It does not include prompt tokens. |-| Maximum context | 256...8,192 tokens | `--max-context` | 4,096 | Sets the prompt plus generation KV-cache budget. |-| Temperature | 0...2 in 0.05 steps | `--temperature` | 1.0 | `0` selects deterministic greedy decoding; positive values sample. |-| Top-K | Off or 1...256 | `--top-k` | 64 | Keeps at most K candidates. The CLI value `0` turns it off. |-| Top-P | Off or 0.01...1 | `--top-p` | 0.95 | Keeps candidates within the selected probability mass before Top-K. It is effective only while Top-K is enabled. |-| Repetition penalty | Off or 1...1.8 | `--repetition-penalty` | Off (`1.0`) | Values above `1.0` penalize tokens already present in the sequence. |+| 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. |+| 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. |With positive temperature, a CLI Top-P below `1` requires Top-K between `1`and `256`. To disable both truncation controls, pass `--top-k 0 --top-p 1`.@@ -29,20 +27,17 @@ benchmark protocol.| 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. |-| Expert-cache policy | LFU, LRU | LFU | Selects which resident expert is evicted when a new expert needs a slot. || Prompt prefill | On, off | On | On processes known prompt tokens through the chunked prefill path. Off disables that path. |-| Prefill chunk | 32, 64, 128 tokens | 128 | Sets the number of prompt tokens processed per prefill chunk. It has no effect when prefill is off. |-| KV cache | FP16, TurboQuant K4/V4 | FP16 | K4/V4 reduces KV storage, but it is experimental and failed the full quality gate. || 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. |-| Model verification | Full SHA-256, Trust verified install | Full SHA-256 | Full SHA-256 hashes the model files. Trust verified install checks the bounded install receipt and file sizes instead of hashing every model byte again. |-Changing a runtime control marks the loaded configuration as stale. Reload the-model before generating with the new setting.+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.## Run an experiment-1. Start from 16 LFU slots, prefill on with a 128-token chunk, FP16 KV,- RDADVISE off, and Full SHA-256 verification.+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.@@ -66,8 +61,7 @@ name the changed setting.- **Advanced** shows decode duration and per-token cb1, cb2, and output-headtime. When RDADVISE runs, it also shows time, calls, data, and skipped advice.-During chunked prefill, the phase label reports the latest exact progress, for-example `Prefill (128/514)`. The app reports prefill mismatches, unsupported-paths, and RDADVISE failures only when they occur. Treat K4/V4 and RDADVISE as measured-experiments, not replacements for the production defaults. A result is a data-point, not a performance ceiling.+During chunked prefill, the phase label reports exact progress, for example+`Prefill (128/514)`. Errors and unsupported configurations appear only when+they occur. RDADVISE remains experimental and is off by default. A measured+result is a data point, not a performance ceiling.diff --git a/docs/SYSTEM_DESIGN.md b/docs/SYSTEM_DESIGN.mdindex 5ab0e3d3..e266ad55 100644--- a/docs/SYSTEM_DESIGN.md+++ b/docs/SYSTEM_DESIGN.md@@ -2,7 +2,7 @@TurboFieldfare is a model-specific Swift and Metal runtime for text generationwith Gemma 4 26B-A4B on Apple Silicon. Its defining constraint is an 8 GB-machine running a text-only model installation of about 14.5 GB. The runtime+machine running a text-only model installation of about 14.3 GB. The runtimetherefore cannot treat the checkpoint as one resident allocation. It keeps thecommon language-model weights and working state available to Metal, stores therouted experts in per-layer files, and reads only the experts selected for the@@ -14,7 +14,7 @@ TurboFieldfare](OPTIMIZATION_JOURNEY.md).Prefill and decode are the two execution modes used below. Prefill processesknown prompt tokens in bounded chunks; decode generates one new token at a-time. Both use the same mapped common weights, mixed KV cache, and per-layer+time. Both use the same mapped common weights, FP16 KV cache, and per-layerstreamed-expert cache.## Why the runtime has this shape@@ -27,9 +27,9 @@ Only a few properties of Gemma 4 determine most of the system design:- A dense shared expert runs in parallel with the routed branch and is addedwithout a routing weight.- The embedding and language-model head share the same quantized weights.-- The source checkpoint already uses MLX affine quantization: packed 4-bit+- The pinned instruction checkpoint uses MLX affine quantization: packed 4-bitvalues with a BF16 scale and BF16 bias for each group of 64 weights. Router- and shared-expert projections use 8-bit overrides.+ projections use 8-bit weights; shared and routed experts use 4-bit weights.The production FP16 KV cache uses a mixed per-layer layout. The 25sliding-window layers attend to the latest 1,024 tokens and store K/V in bounded@@ -44,13 +44,23 @@ The runtime also preserves Gemma-specific details that affect correctness:NeoX RoPE, attention scale `1.0`, no router-logit softcap, parallel shared androuted FFNs, a learned layer scalar, and a final logit softcap of `30.0`.+## Instruction framing++The Mac app and CLI `--messages-file` mode format user, model, and optional+leading system messages with the pinned text-only Gemma 4 chat format. The+runtime stops generation on `<eos>` (token 1), `<turn|>` (token 106), or+`<|tool_response>` (token 50). The third token is a defensive boundary; tool+calling itself is not supported. CLI `--prompt` bypasses this framing for raw+completion and reproducible comparisons.+## Source weights and bounded repack-The installer reads the pinned-[`majentik/gemma-4-26B-A4B-TurboQuant-MLX-4bit`](https://huggingface.co/majentik/gemma-4-26B-A4B-TurboQuant-MLX-4bit)-checkpoint at revision-`cc499c86a958ea7f05cffaa91c7e7243240dabbe`. It does not download a complete-Hugging Face snapshot or materialize a safetensors shard.+The installer reads+[`mlx-community/gemma-4-26b-a4b-it-4bit`](https://huggingface.co/mlx-community/gemma-4-26b-a4b-it-4bit)+at revision `0d77464eeb233a2da68ebf9d7dc4edaac7db956d`. The accepted source index has+SHA-256 `bf198c9f5ea6462addca1966e5dd669c407537a876e82cf06db9084c5c850b13`.+The installer does not download a complete Hugging Face snapshot or+materialize a safetensors shard.Instead, the repacker:@@ -83,6 +93,8 @@ gemma4.gturbo/tokenizer.jsontokenizer_config.jsonspecial_tokens_map.json # optional+ chat_template.jinja # optional source sidecar+ chat_template.json # optional source sidecarpacked_experts/layout.jsonlayer_00.bin@@ -97,6 +109,12 @@ describes the packed subregions within each blob. The expert stride is pagealigned, and each sub-tensor carries its own offset; Metal kernels bindsubregions of an existing buffer rather than creating one buffer per tensor.+Production manifests must describe the model's group-64 affine quantization:+4-bit embedding and attention weights, an 8-bit router, 4-bit routed experts,+and a 4-bit or historical 8-bit shared expert. The instruction checkpoint uses+4-bit shared experts. A production manifest with missing or incompatible+quantization metadata is rejected.+The final manifest is both the install commit marker and the runtime contract.It records architecture fields, file sizes, and SHA-256 hashes; a missingmanifest means a partial install. `verified-install.json` separately binds a@@ -114,17 +132,16 @@ alignment, or a failed integrity check.## Resource splitThe tables distinguish file size, virtual allocation, and physical residency.-They are not interchangeable. The common-model file is 1.51 GiB (1.62 GB in-decimal units). Its hot pages form the roughly 1.58 GB common resident working-set in the memory budget. Slot pages also consume physical memory when filled,-while macOS may keep a separate, opportunistic file-cache copy of recently read+They are not interchangeable. The common-model file is about 1.35 GB in+decimal units. Slot pages also consume physical memory when filled, while+macOS may keep a separate, opportunistic file-cache copy of recently readexpert data.Resident and reusable app-owned resources:| Resource | Current size or capacity | Ownership and behavior || --- | ---: | --- |-| Common model file | 1,621,403,708 bytes (1.51 GiB) | Read-only file mapping wrapped by Metal buffers; hot pages form the common resident working set. |+| Common model file | 1,353,771,068 bytes | Read-only file mapping wrapped by Metal buffers. || FP16 KV cache at 4K | About 305 MiB | App-owned. The 25 sliding-window layers use bounded 1,152-row rings; the 5 full-attention layers use linear storage sized for the requested context. || Reusable runtime scratch | 15.8 MiB for the production 128-token prefill arena, plus about 2 MiB of split-attention scratch and smaller decode buffers | App-owned and reused across layers or chunks. |@@ -140,12 +157,12 @@ The default 16-slot capacity is per layer, not a promise that every slot pageis resident immediately after load. Process RSS and physical footprint dependon which layers and experts have been touched, file-cache state, and memorypressure. For that reason, the table does not turn static byte counts into an-unmeasured peak-RSS claim.+RSS claim.-The production FP16 KV cache is distinct from the experimental packed K4/V4-cache. At 4K, packed K4/V4 uses about 223 MiB and saves about 82 MiB relative-to the current FP16 cache, but it failed the full quality gate. It remains an-explicit experiment and does not fund a larger production expert cache.+The runtime stores KV data in FP16. Its 25 sliding-window layers use a fixed+1,152-row circular cache: 1,024 rows for the attention window and 128 extra+rows for chunked writes. Only the five full-attention layers grow with the+selected context length.## Load and ownership@@ -352,10 +369,11 @@ helpers and tests.[`ModelExpertIO`](../Sources/TurboFieldfare/Runtime/Inference/ModelExpertIO.swift),and [`PreadExpertStreamer`](../Sources/TurboFieldfare/Infrastructure/Streaming/PreadExpertStreamer.swift)own common weights, expert-cache planning, slots, and parallel bounded reads.-- **KV cache and attention.** [`KVCacheManager`](../Sources/TurboFieldfare/Runtime/KVCache/KVCacheManager.swift),- [`Attention`](../Sources/TurboFieldfare/Kernels/Attention/Attention.swift), and- [`TurboQuantKVLayout`](../Sources/TurboFieldfare/Runtime/KVCache/TurboQuantKVLayout.swift)- cover the mixed FP16 cache, SWA/full dispatch, and experimental packed layout.+- **KV cache and attention.** [`KVCacheManager`](../Sources/TurboFieldfare/Runtime/KVCache/KVCacheManager.swift)+ owns bounded circular SWA storage and linear full-attention storage.+ [`Attention`](../Sources/TurboFieldfare/Kernels/Attention/Attention.swift) and+ [`PrefillAttention`](../Sources/TurboFieldfare/Kernels/Attention/PrefillAttention.swift)+ consume distinct FP16 K/V ranges.- **Prompt and decode orchestration.** [`runRawCompletion`](../Sources/TurboFieldfare/Runtime/Generation/RawCompletion.swift)owns the outer generation loop; [`RealForwardRunner`](../Sources/TurboFieldfare/Runtime/Inference/RealForwardRunner.swift)owns the per-layer prefill and decode graph.@@ -390,14 +408,14 @@ helpers and tests.## Scope and limitations-The current runtime supports text-only, single-prompt generation with the-pinned Gemma 4 26B-A4B checkpoint. The validated context envelope is through-4K. Vision, audio, training, fine-tuning, server batching, and general model-support are outside the current scope.+The current runtime supports text-only generation with the pinned Gemma 4+26B-A4B instruction checkpoint. The Mac app offers 4K, 8K, 16K, 32K, and 64K+context lengths. Vision, audio, training, fine-tuning, server batching, and+general model support are outside the current scope.TurboFieldfare is a research system. The Mac app exposes a small set of typed-runtime controls. The production path uses FP16 KV, a 16-slot LFU expert cache,-chunked prefill, MLX attention geometry v2, staged affine MPP prefill, and+runtime controls. The production path uses FP16 KV, exact split-K/V attention,+a 16-slot LFU expert cache, chunked prefill, staged affine MPP prefill, andbatched routed MoE prefill, with RDADVISE off.## Read nextdiff --git a/docs/assets/turbofieldfare-app.webp b/docs/assets/turbofieldfare-app.webpindex 73797d92..984d6e50 100644Binary files a/docs/assets/turbofieldfare-app.webp and b/docs/assets/turbofieldfare-app.webp differdiff --git a/docs/benchmark-prompts/real-generation-v1/long-synthesis.json b/docs/benchmark-prompts/real-generation-v1/long-synthesis.jsonnew file mode 100644index 00000000..3796ba1e--- /dev/null+++ b/docs/benchmark-prompts/real-generation-v1/long-synthesis.json@@ -0,0 +1,6 @@+[+ {+ "role": "user",+ "content": "Read the frozen project document below. Write a concise technical assessment for an engineer who has not seen the project. Explain the central resource constraint, how the runtime divides resident and streamed data, why prefill and decode behave differently, and which limitations matter when interpreting benchmark numbers. End with three practical rules for evaluating future changes. Do not copy headings or sentences from the source, and keep the answer under 500 words.\n\n\n--- BEGIN DOCUMENT ---\n\n<p align=\"center\">\n <img src=\"docs/assets/turbofieldfare-logo-rounded.png\" alt=\"TurboFieldfare logo: a fieldfare inside a segmented cache ring\" width=\"280\">\n</p>\n\n<h1 align=\"center\">TurboFieldfare</h1>\n\n<p align=\"center\">\n <strong>Gemma 4 26B-A4B inference in about 2 GB of RAM</strong><br>\n A custom Swift + Metal runtime for any Apple Silicon Mac, even the 8 GB ones.\n</p>\n\n<p align=\"center\">\n <img alt=\"Swift 6.2\" src=\"https://img.shields.io/badge/Swift-6.2-F05138?logo=swift&logoColor=white\">\n <img alt=\"Metal 4\" src=\"https://img.shields.io/badge/Metal-4-5E5CE6\">\n <img alt=\"macOS 26 or later\" src=\"https://img.shields.io/badge/macOS-26%2B-000000?logo=apple&logoColor=white\">\n <a href=\"LICENSE\"><img alt=\"Apache 2.0 license\" src=\"https://img.shields.io/badge/License-Apache%202.0-2ea44f\"></a>\n</p>\n\n<p align=\"center\">\n <a href=\"#try-it\">Quick start</a> ·\n <a href=\"docs/BENCHMARKS.md\">Benchmarks</a> ·\n <a href=\"docs/COMMUNITY_BENCHMARKS.md\">Contribute results</a> ·\n <a href=\"docs/SYSTEM_DESIGN.md\">How it works</a> ·\n <a href=\"docs/OPTIMIZATION_JOURNEY.md\">Experiments</a> ·\n <a href=\"docs/IMPLEMENTATION_REFERENCES.md\">References</a>\n</p>\n\n\n\nMemory got expensive. So I gave a 26-billion-parameter model a ~2 GB budget.\n\nTurboFieldfare runs the instruction-tuned\n**[Gemma 4 26B-A4B](https://ai.google.dev/gemma/docs/core/model_card_4)**\nwithout loading the entire 14.3 GB model into memory. It keeps the shared\n1.35 GB core and FP16 KV cache in memory, then streams only the experts needed\nfor each token from SSD. This is what lets the model run on Macs with 8 GB of\nRAM.\n\nThe runtime, streaming installer, CLI, and native Mac app are written in Swift\nand Metal. TurboFieldfare is model-specific rather than a wrapper around MLX or\nllama.cpp. The curated [experiment record](docs/experiments/EXPERIMENT_INVENTORY.md)\nsummarizes 102 measured results across kernels, caching, I/O, prefill, and\ndecode.\n\n## Try it\n\n```bash\ngit clone https://github.com/drumih/turbo-fieldfare.git\ncd turbo-fieldfare\nswift build -c release\n.build/release/TurboFieldfareMac\n```\n\nOn the first run, Swift Package Manager downloads and builds the Swift packages\nrequired by the tokenizer. The complete release build includes the foreground\nMac app and its sibling decode-service executable.\n\nWhen the app opens, choose **Install** and let TurboFieldfare fetch and repack\nthe pinned model (about 15 GB). Once it is ready, choose **Load Model**, type\nyour prompt, and press **Generate**.\n\n## At a glance\n\n| Metric | Value |\n| --------------- | ------------------------------------------------------------------------------------------------------------------------ |\n| Model | Gemma 4 26B-A4B IT, 26B total parameters, about 3.88B active per token |\n| Weights | MLX affine 4-bit, group 64; 8-bit router; 4-bit shared and routed experts |\n| Memory | ~2 GB of weights and 4K KV cache |\n| Storage | About 14.3 GB for the installed text-only model |\n| Hardware | Apple Silicon Mac; 8 GB of RAM |\n| Platform | macOS 26, Metal 4, Swift 6.2 |\n| M2 measured decode | [5.1-6.3 tok/s](docs/BENCHMARKS.md#m2-measured-decode) on an 8 GB M2 MacBook Air |\n| M5 measured decode | [32.0-36.1 tok/s](docs/BENCHMARKS.md#m5-measured-decode) on a 24 GB M5 Pro |\n\nThe measured result is a reference point, not a performance ceiling. Prompt\nlength, generated length, page-cache state, and hardware all affect throughput.\nTo help measure another Apple Silicon Mac, follow the\n[community benchmark guide](docs/COMMUNITY_BENCHMARKS.md).\n\n## Using TurboFieldfare\n\nTurboFieldfare provides a native Mac app and a command-line interface. Both\nuse the same `.gturbo` model directory. Start with the Mac app; use the CLI for\nscripts, reproducible runs, and direct control over generation settings.\n\nThe Swift package exposes five products:\n\n| Product | Purpose |\n| --- | --- |\n| `TurboFieldfare` | Swift library containing the runtime and Metal kernels |\n| `TurboFieldfareMac` | Native Mac app for installation and generation |\n| `TurboFieldfareDecodeService` | One-shot local model and Metal owner used by the Mac app |\n| `TurboFieldfareCLI` | Command-line instruction chat and raw completion |\n| `TurboFieldfareRepack` | Streaming model installer and install verifier |\n\n### Requirements\n\n- An Apple Silicon Mac; the validated target is an 8 GB M2 MacBook Air\n- macOS 26 with Metal 4\n- Xcode 26 and Swift 6.2 or newer\n- Enough free storage for the ~14.3 GB model installation\n- An internet connection for the first model install\n\nThe package is arm64-only. Older macOS and Metal versions are not supported.\n\n### Prompting the model\n\nThe Mac app treats what you type as an instruction and handles Gemma's chat\nformatting automatically. Just describe the task and include any context the\nmodel needs.\n\nGeneration defaults to temperature `0.2`, Top-K `64`, and Top-P `0.95`. Set\ntemperature to `0` for deterministic greedy output. The model can still repeat\nitself or give incorrect answers, so check important results.\n\nTurboFieldfare is text-only. It supports user and model messages, plus an\noptional system message at the start of a conversation. Tool calling, images,\nand audio are not supported.\n\n### Mac app\n\nClone the repository, then run the app from its root:\n\n```bash\nswift build -c release\n.build/release/TurboFieldfareMac\n```\n\nBuild the complete package so the app and its sibling decode service are both\navailable. When launched from this checkout, the app stores the model in\n`scratch/gemma4.gturbo`.\n\n#### Install the model\n\nOn first launch, the app checks the available storage and shows the download\nand installed sizes. Choose **Install** to begin.\n\nThe installer never materializes the full source checkpoint. It streams the\nrequired byte ranges from the pinned Hugging Face revision and repacks them\ndirectly into the `.gturbo` layout as they arrive. This avoids a second full\ncheckpoint on disk and keeps scratch memory bounded.\n\nThe first installation transfers about 15 GB through bounded Hugging Face\nrange requests. Network speed and Hugging Face response times vary, so it can\ntake a while. The completed `.gturbo` installation occupies about 14.3 GB and\nis accepted only after its manifest and file hashes have been validated.\nInstallation does not load the model into memory.\n\n#### Load and generate\n\nAfter installation:\n\n1. Choose **Load Model**.\n2. Enter a prompt in the composer.\n3. Choose **Generate**, or press <kbd>Command</kbd>+<kbd>Return</kbd>.\n4. Use the stop button or <kbd>Escape</kbd> to end generation early.\n\nThe status bar reports the current phase, generated tokens, decode rate, and\ndecode-service memory use. The fixed right settings pane controls sampling,\ncontext length, the expert cache, and runtime options. Settings that affect the\nloaded runtime require a reload before the next generation. During chunked\nprefill, the app reports exact progress such as `Prefill (128/514)`. See\n[Runtime controls](docs/RUNTIME_CONTROLS.md) for the allowed values, defaults,\nand result metrics.\n\n### Command-line interface\n\nThe CLI uses an existing `.gturbo` installation. If you installed the model\nthrough the Mac app, it is already available at `scratch/gemma4.gturbo`.\nOtherwise, install it from the command line:\n\n```bash\nswift run -c release TurboFieldfareRepack \\\n --output scratch/gemma4.gturbo \\\n --overwrite\n```\n\nThe runtime accepts only a completed `.gturbo` directory with a final\n`manifest.json`.\n\nVerify an existing installation without loading the model:\n\n```bash\nswift run -c release TurboFieldfareRepack \\\n --verify-install \\\n --input-gturbo scratch/gemma4.gturbo\n```\n\n#### Instruction chat\n\nPut chat messages in a JSON array and pass it with `--messages-file`:\n\n```json\n[\n {\"role\": \"user\", \"content\": \"Explain why chunked prefill reduces time to first token while keeping memory bounded.\"}\n]\n```\n\n```bash\nswift run -c release TurboFieldfareCLI \\\n --model scratch/gemma4.gturbo \\\n --messages-file messages.json\n```\n\nThis formats messages in the same way as the Mac app. The CLI response limit\nis set with `--max-new`, which defaults to 1,024 tokens. The Mac app can\ngenerate until the selected context window is full.\n\n#### Raw completion\n\n`--prompt` is available for raw completion and reproducible comparisons. It\npasses the text directly to the model without chat formatting. Use\n`--messages-file` for instruction-response conversations.\n\n```bash\nswift run -c release TurboFieldfareCLI \\\n --model scratch/gemma4.gturbo \\\n --prompt \"The capital of France is\" \\\n --max-new 64 \\\n --temperature 0\n```\n\nThis example deliberately requests a short greedy completion.\n\nCommon generation options include `--max-context`, `--temperature`, `--top-k`,\n`--top-p`, `--repetition-penalty`, `--seed`, and repeatable `--stop` strings.\nThe public CLI uses production runtime defaults. Run the following command for\nthe complete option list:\n\n```bash\nswift run -c release TurboFieldfareCLI --help\n```\n\nGenerated text goes to standard output. Timing statistics go to standard error;\nadd `--quiet` to suppress that footer in scripts.\n\n## Test and contribute\n\nRun the public test suite serially:\n\n```bash\nScripts/test.sh\n```\n\nBefore starting a model run, close memory-heavy apps and check\n`memory_pressure -Q`. If it reports little free memory, postpone the run. Run\nonly one TurboFieldfare or local-model process at a time.\n\nTo contribute a comparable performance result, follow the\n[community benchmark guide](docs/COMMUNITY_BENCHMARKS.md).\n\n## How the inference engine works\n\nAt each transformer layer, Metal computes attention and the router from\nresident weights. The CPU uses the router's top-8 expert IDs to plan against\nthe layer's 16-slot LFU cache, then fills misses with bounded parallel `pread`\ncalls into Metal-visible buffers. Metal computes the resident shared-expert\nbranch while those reads run, then combines the shared and routed outputs.\n\nPrompt prefill uses chunks of up to 128 tokens so one fetched expert can serve\nmultiple rows. Generation repeats the routed layer loop one token at a time.\nThe installer applies the same bounded-memory rule: it repacks remote ranges\ndirectly into `.gturbo` without staging a full shard or tensor.\n\nFor a visual introduction to the model architecture, see Maarten Grootendorst's\n[A Visual Guide to Gemma 4](https://newsletter.maartengrootendorst.com/p/a-visual-guide-to-gemma-4).\n\n[System design](docs/SYSTEM_DESIGN.md) explains the `.gturbo` layout, memory\nownership, prefill, router handoff, `cb1`/`io`/`cb2` phases, Metal kernels, and\ncorrectness invariants.\n\n## Status and scope\n\nTurboFieldfare currently includes:\n\n\n\n--- END DOCUMENT ---"+ }+]diff --git a/docs/benchmark-prompts/real-generation-v1/medium-review.json b/docs/benchmark-prompts/real-generation-v1/medium-review.jsonnew file mode 100644index 00000000..3077bcc7--- /dev/null+++ b/docs/benchmark-prompts/real-generation-v1/medium-review.json@@ -0,0 +1,6 @@+[+ {+ "role": "user",+ "content": "Review the following design for an asynchronous file-backed cache. Identify the most important correctness and performance risks, then propose a safer design. Keep the review concrete, prioritize issues rather than listing every possible improvement, and stay under 500 words.\n\nThe service stores immutable objects in files. Each request supplies an object key. A dictionary maps keys to slots, and every slot owns a reusable byte buffer. On a hit, the service returns a view into the slot buffer. On a miss, it chooses the slot with the oldest timestamp, updates the dictionary immediately, and starts an asynchronous read into that slot. Reads run on a global concurrent executor. The caller awaits the read future and then uses the returned view.\n\nTo reduce lock contention, the dictionary is protected only while a key is looked up or inserted. Slot timestamps, in-flight state, and buffer contents are not protected. Two misses may therefore choose the same oldest slot. The implementation assumes this is harmless because both callers await their own reads. A hit is allowed while a replacement read is in flight, because the new dictionary entry already points to the selected slot. Failed reads leave the new key in the dictionary so a later request can retry using the same slot.\n\nThe file format begins with a fixed header containing payload length and checksum. The read task reads the header, resizes the reusable buffer if necessary, then reads the payload. It verifies the checksum after publishing completion. There is no upper bound on payload length beyond the integer type. Cancellation stops waiting in the caller but does not cancel the executor task. Metrics count a cache hit whenever the dictionary lookup succeeds, including in-flight and failed entries.\n\nThe service is expected to handle many concurrent requests, repeated keys, occasional I/O failures, and memory pressure. Objects are immutable after they are written, but files can be replaced atomically by another process. Returned views may be retained briefly after the request finishes. The design goal is bounded memory, no corrupted reads, deduplicated work for the same key, and useful hit-rate and latency metrics.\n"+ }+]diff --git a/docs/benchmark-prompts/real-generation-v1/short-explanation.json b/docs/benchmark-prompts/real-generation-v1/short-explanation.jsonnew file mode 100644index 00000000..6b38a717--- /dev/null+++ b/docs/benchmark-prompts/real-generation-v1/short-explanation.json@@ -0,0 +1,6 @@+[+ {+ "role": "user",+ "content": "Explain how coastal wetlands can reduce flood damage during storms. Describe the physical mechanisms, give two important limits, and distinguish risk reduction from complete protection. Write for an informed reader without specialist training and keep the answer under 450 words.\n"+ }+]diff --git a/docs/experiments/EXPERIMENT_INVENTORY.md b/docs/experiments/EXPERIMENT_INVENTORY.mdindex 0fff28d7..b7861456 100644--- a/docs/experiments/EXPERIMENT_INVENTORY.md+++ b/docs/experiments/EXPERIMENT_INVENTORY.md@@ -1,6 +1,6 @@# Experiment inventory-This is the curated experiment and decision index behind [Optimizing a 14.4 GB+This is the curated experiment and decision index behind [Optimizing a 14.3 GBmodel for an 8 GB machine](../OPTIMIZATION_JOURNEY.md). It records what shipped,what worked only under a named condition, what failed, what a stronger gatelater reversed, and what the project never attempted.@@ -8,8 +8,8 @@ later reversed, and what the project never attempted.Most readers should start with the article above. Use this inventory to findthe variants, controls, measurements, and final disposition of a specificexperiment. The entries are design archaeology, not an independent reproduction-package: they are curated from a larger private research record, while raw logs,-traces, internal plans, and project-state documents are intentionally excluded.+package. Raw logs, traces, working plans, and project-state documents are not+part of this curated record.The companion [implementation reference ledger](../IMPLEMENTATION_REFERENCES.md)records the external model implementations, papers, kernels, and systems that@@ -92,7 +92,7 @@ resident set size; and **NLL** is negative log-likelihood. See| [DEC-12](summaries/02-decode-moe-int4-and-router.md#dec-12) — Phase-1 paired rows | 207-212 versus 194-196 microseconds. | Rejected. || [DEC-13](summaries/02-decode-moe-int4-and-router.md#dec-13) — Phase-1 `u16` loads | 5.961 to 5.973 tok/s. | Production; small win. || [DEC-14](summaries/02-decode-moe-int4-and-router.md#dec-14) — Phase-2 d2/d2p/d4 | Mixed end to end; target only 5.70 ms/token. | Rejected; default unchanged. |-| [DEC-15](summaries/02-decode-moe-int4-and-router.md#dec-15) — Group-sum reuse | Private 454.05 to 420.53 microseconds reversed to 309.98 versus 348.83 in the wrapper. | Rejected. |+| [DEC-15](summaries/02-decode-moe-int4-and-router.md#dec-15) — Group-sum reuse | An early 454.05 to 420.53 microsecond result reversed to 309.98 versus 348.83 in the wrapper. | Rejected. || [DEC-16](summaries/02-decode-moe-int4-and-router.md#dec-16) — Adaptive geometry | One synthetic state won; real rows mixed. | Rejected. || [DEC-17](summaries/02-decode-moe-int4-and-router.md#dec-17) — Progressive execution | Corrected 1K/256 fell 4.799 to 4.648 tok/s. | Rejected. || [DEC-18](summaries/02-decode-moe-int4-and-router.md#dec-18) — Hit-first split | 5.169 versus 4.518 tok/s with forced identical IDs. | Production. |@@ -131,11 +131,11 @@ resident set size; and **NLL** is negative log-likelihood. See| [KV-02](summaries/05-attention-and-kv-cache.md#kv-02) — GQA-aware SWA | Isolated SWA win. | Production. || [KV-03](summaries/05-attention-and-kv-cache.md#kv-03) — Full-GQA A3 | +21.2% at 1024, -54.6% at 4096. | Rejected. || [KV-04](summaries/05-attention-and-kv-cache.md#kv-04) — A4 local variants | Three 1024 wins became neutral/slower at 4096; TG widths lost. | Rejected. |-| [KV-05](summaries/05-attention-and-kv-cache.md#kv-05) — MLX geometry v1 | 65-68% isolated win, then forced-prefix failure and removal. | Rejected; corrected v2 reopened the geometry family. |-| [KV-06](summaries/05-attention-and-kv-cache.md#kv-06) — MLX geometry v2 | 71-74% isolated; quality passed; +1.30-1.59% end to end. | Production. |-| [KV-07](summaries/05-attention-and-kv-cache.md#kv-07) — Packed K4/V4 attention | Split beat packed single-pass but stayed slower than FP16. | Conditional; experiment only. |+| [KV-05](summaries/05-attention-and-kv-cache.md#kv-05) — MLX geometry v1 | 65-68% isolated win, then forced-prefix failure and removal. | Rejected; exact split remains production. |+| [KV-06](summaries/05-attention-and-kv-cache.md#kv-06) — MLX geometry v2 | 71-74% isolated and +1.30-1.59% on the earlier path; the instruction-checkpoint quality gate failed. | Rejected for the instruction checkpoint; exact split is production. |+| [KV-07](summaries/05-attention-and-kv-cache.md#kv-07) — Packed K4/V4 attention | Split beat packed single-pass but stayed slower than FP16. | Rejected and removed. || [KV-08](summaries/05-attention-and-kv-cache.md#kv-08) — Alternative codecs | Faster writers, much slower attention. | Rejected. |-| [KV-09](summaries/05-attention-and-kv-cache.md#kv-09) — K4/V4 quality | Mean delta-NLL +0.015197; top-1 -5.0781 points. | Rejected; production default remains FP16. |+| [KV-09](summaries/05-attention-and-kv-cache.md#kv-09) — K4/V4 quality | Mean delta-NLL +0.015197; top-1 -5.0781 points. | Rejected and removed; FP16 remains production. || [KV-10](summaries/05-attention-and-kv-cache.md#kv-10) — FP16 full-attention island | Small sample looked better; 256-row top-k gates failed. | Rejected. || [KV-11](summaries/05-attention-and-kv-cache.md#kv-11) — Packed chunk 32 | 5.42-6.30% isolated win; holdout quality failed. | Rejected. || [KV-12](summaries/05-attention-and-kv-cache.md#kv-12) — FP16 KV ring | About 575-591 MiB saved; speed neutral/mixed; parity retained. | Production. |@@ -219,10 +219,9 @@ These boundaries are not failed performance work:## How these summaries were prepared-Each public ID has a private claim map that names the dated source records used-to verify it. Later revalidation overrides stale intermediate conclusions. The-public package deliberately carries summaries instead of raw captures so a-reader can follow the evidence without receiving the private working archive.+Later revalidation overrides stale intermediate conclusions. These summaries+keep the evidence and final disposition readable without reproducing every raw+capture.[Optimization journey](../OPTIMIZATION_JOURNEY.md) |[Benchmarks](../BENCHMARKS.md) |diff --git a/docs/experiments/summaries/05-attention-and-kv-cache.md b/docs/experiments/summaries/05-attention-and-kv-cache.mdindex 14cdc874..94d85845 100644--- a/docs/experiments/summaries/05-attention-and-kv-cache.md+++ b/docs/experiments/summaries/05-attention-and-kv-cache.md@@ -5,17 +5,16 @@[Optimization journey](../../OPTIMIZATION_JOURNEY.md) |[Next: Prefill](06-prefill.md)-The current runtime uses split-KV attention, MLX-derived full-attention-geometry, and an exact FP16 KV ring. Packed K4/V4 remains an explicit-experiment because its quality loss outweighed its roughly 82 MiB saving-relative to the final FP16 ring.+The current runtime uses exact split-K/V attention and an FP16 KV cache. Packed+K4/V4 saved only about 82 MiB at 4K, grew across all 30 attention layers, and+failed the quality gate. It was rejected and removed.| Current result | Disposition || --- | --- || Split-KV plus GQA-aware SWA | Production |-| MLX full-attention geometry v2 | Production after reversed rejection |+| Exact split full attention | Production || FP16 KV ring | Production |-| Packed K4/V4 and alternate codecs | Experimental or rejected |+| Packed K4/V4 and alternate codecs | Rejected and removed |## Decode attention geometry@@ -92,12 +91,9 @@ relative to the final FP16 ring.- **Evidence:** Isolated time improved 65-68%; early end-to-end rowsimproved 2.8-3.7%. A forced-prefix exact-output gate then failed and thecandidate was removed.-- **What changed the conclusion:** A corrected v2 later- passed a distributional quality gate and exposed shared control nondeterminism,- so the project reopened the geometry family rather than treating v1's stop as- final.-- **Final disposition:** V1 remained removed; v2 reversed the geometry-family- rejection.+- **What changed the conclusion:** A corrected v2 reopened the geometry family,+ but the instruction checkpoint's full quality gate later rejected it too.+- **Final disposition:** Rejected; exact split remains production.- **Lesson:** Select the quality oracle from the candidate's mathematicalcontract without retroactively declaring an old candidate safe. See[METH-01](09-validation-and-measurement-lessons.md#meth-01).@@ -110,11 +106,14 @@ relative to the final FP16 ring.- **Variants tested:** Exact reference repair,isolated geometry, a 9,216-row quality corpus, and balanced M2 end-to-endrows.-- **Evidence:** Isolated speed improved 71-74%; the quality gate passed;- balanced decode improved 1.30-1.59%.-- **What changed the conclusion:** The- distributional gate replaced the invalid exact-output rejection.-- **Final disposition:** Production; reversed rejection.+- **Evidence:** Isolated speed improved 71-74%, and an earlier decode path+ improved 1.30-1.59%. On the instruction checkpoint's 9,216-row evaluation,+ exact split-K/V matched the FP16 reference while MLX-v2 exceeded the accepted+ mean delta-NLL threshold.+- **What changed the conclusion:** Revalidation against the shipping instruction+ checkpoint replaced the earlier promotion result.+- **Final disposition:** Rejected for the instruction checkpoint; exact split is+ production.- **Lesson:** Revalidate a strong speed signal when the rejection instrumentwas wrong. See [METH-01](09-validation-and-measurement-lessons.md#meth-01).@@ -133,7 +132,7 @@ relative to the final FP16 ring.helped; K staging and full-GQA regressed.- **What changed the conclusion:**Optimization could not erase packed access and dequantization cost.-- **Final disposition:** Explicit experiment, not production.+- **Final disposition:** Rejected and removed.- **Lesson:** Improve acandidate against the production control, not only against its first version.@@ -163,7 +162,7 @@ relative to the final FP16 ring.failed. Against the final FP16 ring, packed storage saves only about 82 MiB.- **What changed the conclusion:** The full corpus and ring-relative memorycomparison replaced earlier short and obsolete-linear comparisons.-- **Final disposition:** Rejected as production; experiment remains available.+- **Final disposition:** Rejected and removed.- **Lesson:** Approximation must clear quality against the best exact memorylayout.