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
Support longer contexts and speed up full attention (#182)
Andrey Mikhaylov37fd33f61304
diff --git a/Package.swift b/Package.swiftindex ff52f46c..f8d9fa28 100644--- a/Package.swift+++ b/Package.swift@@ -158,7 +158,7 @@ let package = Package(),.testTarget(name: "TurboFieldfareDecodeServiceTests",- dependencies: ["TurboFieldfareDecodeService", "TurboFieldfareAppCore", "TurboFieldfareDecodeProtocol"],+ dependencies: ["TurboFieldfare", "TurboFieldfareDecodeService", "TurboFieldfareAppCore", "TurboFieldfareDecodeProtocol"],path: "Tests/TurboFieldfareDecodeService"),.testTarget(diff --git a/Sources/TurboFieldfare/Infrastructure/ModelIO/ModelTypes.swift b/Sources/TurboFieldfare/Infrastructure/ModelIO/ModelTypes.swiftindex adb33fe7..b6abe89f 100644--- a/Sources/TurboFieldfare/Infrastructure/ModelIO/ModelTypes.swift+++ b/Sources/TurboFieldfare/Infrastructure/ModelIO/ModelTypes.swift@@ -25,6 +25,10 @@ public struct ArchConfig: Sendable, Equatable {public let attentionKEqV: Boolpublic let fullAttentionLayerMask: [UInt8]public let hiddenActivation: String+ /// The checkpoint's `max_position_embeddings`. The one ceiling every+ /// surface refuses above; not a manifest-compared field, so+ /// `ManifestReader.validateArch` does not read it.+ public let maxPositionEmbeddings: Intpublic init(hiddenSize: Int,@@ -47,7 +51,8 @@ public struct ArchConfig: Sendable, Equatable {tieWordEmbeddings: Bool,attentionKEqV: Bool,fullAttentionLayerMask: [UInt8],- hiddenActivation: String+ hiddenActivation: String,+ maxPositionEmbeddings: Int = 262_144) {self.hiddenSize = hiddenSizeself.intermediateSize = intermediateSize@@ -70,6 +75,7 @@ public struct ArchConfig: Sendable, Equatable {self.attentionKEqV = attentionKEqVself.fullAttentionLayerMask = fullAttentionLayerMaskself.hiddenActivation = hiddenActivation+ self.maxPositionEmbeddings = maxPositionEmbeddings}/// Canonical Gemma 4 26B-A4B baseline, checked against the installed@@ -96,7 +102,8 @@ public struct ArchConfig: Sendable, Equatable {tieWordEmbeddings: true,attentionKEqV: true,fullAttentionLayerMask: Self.gemma4LayerMask(),- hiddenActivation: "gelu_pytorch_tanh"+ hiddenActivation: "gelu_pytorch_tanh",+ maxPositionEmbeddings: 262_144)private static func gemma4LayerMask() -> [UInt8] {@@ -107,7 +114,7 @@ public struct ArchConfig: Sendable, Equatable {}/// Failure modes for the validation gates in `Model.load`.-enum ModelError: Error, CustomStringConvertible, Equatable {+public enum ModelError: Error, CustomStringConvertible, Equatable {case partialInstall(path: String)case notAGTurboDirectorycase unsupportedVersion(major: Int, minor: Int)@@ -122,6 +129,8 @@ enum ModelError: Error, CustomStringConvertible, Equatable {case indexCorrupt(detail: String)case posixFailed(call: String, errno: Int32)case trustedReceiptInvalid(detail: String)+ case contextExceedsModel(requested: Int, maximum: Int)+ case kvAllocationFailed(layer: Int, bytes: Int)public var description: String {switch self {@@ -153,6 +162,10 @@ enum ModelError: Error, CustomStringConvertible, Equatable {return "\(c) failed with errno \(e)"case .trustedReceiptInvalid(let detail):return "trusted install receipt invalid: \(detail)"+ case .contextExceedsModel(let requested, let maximum):+ return "maxContext \(requested) exceeds the model's maximum position \(maximum)"+ case .kvAllocationFailed(let layer, let bytes):+ return "KV cache allocation of \(bytes) bytes for layer \(layer) failed"}}}diff --git a/Sources/TurboFieldfare/Kernels/Attention/Attention.swift b/Sources/TurboFieldfare/Kernels/Attention/Attention.swiftindex 2571ea6e..3ceb77c8 100644--- a/Sources/TurboFieldfare/Kernels/Attention/Attention.swift+++ b/Sources/TurboFieldfare/Kernels/Attention/Attention.swift@@ -8,6 +8,7 @@ struct AttentionSplitGeometry: Sendable, Equatable {let chunkLength: Intlet partialThreadgroups: Intlet useSWAGroupedPartial: Bool+ let useFullGroupedVectorPartial: Bool}@@ -25,6 +26,7 @@ struct AttentionSplitGeometry: Sendable, Equatable {/// - `out` : `[numQHeads, headDim]`final class Attention {private let ctx: MetalContext+ private let psoGroupedVecFull: MTLComputePipelineStateprivate let psoPartial: MTLComputePipelineStateprivate let psoGQAPartial: MTLComputePipelineStateprivate let psoCombine: MTLComputePipelineState@@ -62,6 +64,9 @@ final class Attention {init(context: MetalContext) throws {self.ctx = context+ self.psoGroupedVecFull = try Self.specializedPipeline(+ context, "attention_decode_full_grouped_vec_partial",+ headDim: 512, numQHeads: 16, numKVHeads: 2)self.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")@@ -134,13 +139,15 @@ final class Attention {return max(1, min(defaultChunks, min(maxChunks, eff)))}- static func splitGeometry(numQHeads: UInt32,+ static func splitGeometry(headDim: UInt32 = 512, numQHeads: UInt32,numKVHeads: UInt32,seqLen: UInt32,kvStart: UInt32,- preferGQASWA: Bool) -> AttentionSplitGeometry {+ preferGQASWA: Bool, forceGroupedVector: Bool = false) -> AttentionSplitGeometry {let qPerKV = Int(numQHeads / numKVHeads)let useSWAGQAPartial = preferGQASWA && qPerKV <= 2+ let useGroupedVector = forceGroupedVector && !preferGQASWA+ && headDim == 512 && numQHeads == 16 && numKVHeads == 2let effectiveLength = Int(seqLen) - Int(kvStart)let baseChunks = Self.chunkCount(effLen: effectiveLength,preferGQASWA: useSWAGQAPartial)@@ -148,12 +155,13 @@ final class Attention {? max(baseChunks, min(Self.maxChunks, baseChunks * qPerKV)): baseChunkslet chunkLength = (max(1, effectiveLength) + numChunks - 1) / numChunks- let partialHeadGroups = useSWAGQAPartial ? Int(numKVHeads) : Int(numQHeads)+ let partialHeadGroups = (useSWAGQAPartial || useGroupedVector) ? Int(numKVHeads) : Int(numQHeads)return AttentionSplitGeometry(effectiveLength: effectiveLength,numChunks: numChunks,chunkLength: chunkLength,partialThreadgroups: partialHeadGroups * numChunks,- useSWAGroupedPartial: useSWAGQAPartial)+ useSWAGroupedPartial: useSWAGQAPartial,+ useFullGroupedVectorPartial: useGroupedVector)}@@ -202,7 +210,8 @@ final class Attention {numQHeads: UInt32,numKVHeads: UInt32,seqLen: UInt32,- scale: Float? = nil) {+ scale: Float? = nil,+ useGroupedVector: Bool = true) {precondition(numQHeads % numKVHeads == 0,"numQHeads must be a multiple of numKVHeads for GQA")precondition(headDim <= 512,@@ -216,7 +225,8 @@ final class Attention {v: v, vOffset: vOffset, out: out, outOffset: outOffset,headDim: headDim, numQHeads: numQHeads, numKVHeads: numKVHeads,seqLen: seqLen, kvStart: 0, scale: sc,- preferGQASWA: false)+ preferGQASWA: false,+ forceGroupedVector: useGroupedVector)}@@ -233,6 +243,7 @@ final class Attention {headDim: UInt32, numQHeads: UInt32, numKVHeads: UInt32,seqLen: UInt32, kvStart: UInt32, scale: Float,preferGQASWA: Bool,+ forceGroupedVector: Bool = false,ringCapacity: UInt32 = 0) {precondition(Int(numQHeads) <= Self.maxQHeads,"numQHeads \(numQHeads) exceeds split-KV scratch (max \(Self.maxQHeads))")@@ -240,15 +251,16 @@ final class Attention {"head_dim \(headDim) exceeds split-KV scratch (max \(Self.maxHeadDim))")precondition(ringCapacity == 0 || preferGQASWA,"FP16 KV ring is only valid for SWA attention")- let geometry = Self.splitGeometry(numQHeads: numQHeads,+ let geometry = Self.splitGeometry(headDim: headDim, numQHeads: numQHeads,numKVHeads: numKVHeads,seqLen: seqLen,kvStart: kvStart,- preferGQASWA: preferGQASWA)+ preferGQASWA: preferGQASWA,+ forceGroupedVector: forceGroupedVector)let useSWAGQAPartial = geometry.useSWAGroupedPartiallet nChunks = geometry.numChunkslet chunkLen = geometry.chunkLength- let partialPSO = partialPipeline(headDim: headDim,+ let partialPSO = geometry.useFullGroupedVectorPartial ? psoGroupedVecFull : partialPipeline(headDim: headDim,numQHeads: numQHeads,numKVHeads: numKVHeads,numChunks: nChunks,diff --git a/Sources/TurboFieldfare/Metal/Attention/attention.metal b/Sources/TurboFieldfare/Metal/Attention/attention.metalindex 9e215022..220059d6 100644--- a/Sources/TurboFieldfare/Metal/Attention/attention.metal+++ b/Sources/TurboFieldfare/Metal/Attention/attention.metal@@ -375,3 +375,86 @@ void attention_decode_combine(out_row[i] = half(acc * inv_d);}}++[[kernel, max_total_threads_per_threadgroup(kAttnThreads)]]+void attention_decode_full_grouped_vec_partial(+ device const half* Q [[buffer(0)]],+ device const half* K [[buffer(1)]],+ device const half* V [[buffer(2)]],+ device float* m_out [[buffer(3)]], // [num_q_heads * num_chunks]+ device float* d_out [[buffer(4)]], // [num_q_heads * num_chunks]+ device float* o_out [[buffer(5)]], // [num_q_heads * num_chunks * head_dim]+ constant uint& head_dim [[buffer(6)]],+ constant uint& num_q_heads [[buffer(7)]],+ constant uint& num_kv_heads [[buffer(8)]],+ constant uint& seq_len [[buffer(9)]],+ constant uint& kv_start [[buffer(10)]],+ constant uint& chunk_len [[buffer(11)]],+ constant uint& num_chunks [[buffer(12)]],+ constant float& scale [[buffer(13)]],+ uint tg_id [[threadgroup_position_in_grid]],+ uint simd_lane_id [[thread_index_in_simdgroup]],+ uint simd_group_id [[simdgroup_index_in_threadgroup]]+) {+ constexpr uint kGVHeadDim = 512;+ constexpr uint kGVQPerKV = 8;+ constexpr uint kGVPerLane = kGVHeadDim / 32; // 16 components per lane++ const uint NC = attn_fc_num_chunks(num_chunks);+ const uint NKV = attn_fc_num_kv_heads(num_kv_heads);++ const uint kv_head = tg_id / NC;+ const uint chunk = tg_id % NC;+ const uint q_head = kv_head * kGVQPerKV + simd_group_id;++ const uint p_start = kv_start + chunk * chunk_len;+ uint p_end = p_start + chunk_len;+ if (p_end > seq_len) { p_end = seq_len; }++ const uint component = simd_lane_id;++ thread float q_reg[kGVPerLane];+ thread float o_local[kGVPerLane];+ device const half* Q_row = Q + q_head * kGVHeadDim + component;+ for (uint i = 0; i < kGVPerLane; ++i) {+ q_reg[i] = float(Q_row[32 * i]);+ o_local[i] = 0.0f;+ }++ float m_run = -INFINITY;+ float d_run = 0.0f;+ const float sc = attn_fc_scale(scale);++ // An empty chunk (p_start past the range end) skips the loop and writes+ // (-inf, 0, 0), which the combine weights to zero via e^{-inf}.+ for (uint p = p_start; p < p_end; ++p) {+ const uint kv_base = (p * NKV + kv_head) * kGVHeadDim + component;+ device const half* K_row = K + kv_base;+ device const half* V_row = V + kv_base;++ float group_total = 0.0f;+ for (uint g = 0; g < 8; ++g) {+ const float partial = fma(q_reg[g + 8], float(K_row[32 * g + 256]),+ fma(q_reg[g], float(K_row[32 * g]), 0.0f));+ // Every lane participates before one lane retains the virtual sum.+ const float reduced = simd_sum(partial);+ if (simd_lane_id == g) { group_total = reduced; }+ }+ float s = simd_sum(group_total) * sc;++ 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 i = 0; i < kGVPerLane; ++i) {+ // Match production's contraction: round the new weighted value first.+ o_local[i] = fma(o_local[i], alpha, p_exp * float(V_row[32 * i]));+ }+ m_run = m_new;+ }++ const uint base = q_head * NC + chunk;+ if (simd_lane_id == 0) { m_out[base] = m_run; d_out[base] = d_run; }+ device float* o_row = o_out + base * kGVHeadDim + component;+ for (uint i = 0; i < kGVPerLane; ++i) { o_row[32 * i] = o_local[i]; }+}diff --git a/Sources/TurboFieldfare/Runtime/Configuration/ContextAdmission.swift b/Sources/TurboFieldfare/Runtime/Configuration/ContextAdmission.swiftnew file mode 100644index 00000000..9d043148--- /dev/null+++ b/Sources/TurboFieldfare/Runtime/Configuration/ContextAdmission.swift@@ -0,0 +1,133 @@+import Foundation++/// The one host-memory admission rule for a requested context length.+///+/// Every surface that can pick a context — the app menu, the CLI, the server,+/// the decode service — asks this type whether the host can back it, so a+/// refusal, a hidden menu row and a warning all quote the same arithmetic. The+/// numbers are FP16 KV geometry plus two measured constants; nothing here+/// allocates or touches the model.+public enum ContextAdmission {++ /// Everything resident that does not scale with context: the LM weights,+ /// the expert-cache slots, prefill scratch, the tokenizer and the Metal+ /// library. Measured at 1.75-1.94 GB across PR 156's five rungs and the+ /// M2-8 8K row at 16 cache slots; extra slots are accounted for separately.+ public static let nonKVRuntimeFootprintBytes: UInt64 = 2 << 30++ // The pinned IT pack uses 3,358,720 bytes per routed expert. Each layer+ // owns its slots; the streamer rounds each allocation to the host page size.+ private static let expertStrideBytes = 3_358_720++ private static func additionalExpertCacheBytes(config: ArchConfig, slots: Int) -> UInt64 {+ let page = Int(getpagesize())+ let slotBytes = ((expertStrideBytes + page - 1) / page) * page+ // Do not discount the measured baseline for smaller caches: the rest+ // of that allowance has not been measured separately.+ return UInt64(max(0, slots - 16)) * UInt64(config.numLayers) * UInt64(slotBytes)+ }++ /// Headroom left to the OS and to a minimum routed-expert page cache. A+ /// host that satisfied only the projected footprint would run with every+ /// expert read faulting against a cold cache.+ public static let hostReserveBytes: UInt64 = 3 << 30++ public enum Availability: Equatable, Sendable {+ case available+ case needsMemory(minimumHostBytes: UInt64)+ }++ /// Rows the production runtime allocates per sliding-window layer.+ ///+ /// `RealForwardRunner` floors its `maxPrefillChunkTokens` at the pooled+ /// image-token count, and `KVCacheManager` sizes the ring at+ /// `slidingWindow + maxPrefillChunkTokens`, so the widest chunk the runtime+ /// may see — not the default text chunk — is what the ring costs. 1,304+ /// today.+ public static func productionSlidingRingRows(config: ArchConfig, maxContext: Int) -> Int {+ let chunkRows = max(PrefillRuntimeConfig.defaultChunked.chunkTokens,+ VisionConfig().maximumPooledTokens)+ return min(maxContext, config.slidingWindow + chunkRows)+ }++ /// FP16 K and V bytes the runtime allocates for `maxContext`.+ ///+ /// Sliding-window layers are ring-capped; only the full-attention layers+ /// grow with the context, at 20,480 B per token across the five of them.+ public static func fp16KVBytes(config: ArchConfig, maxContext: Int) -> UInt64 {+ let fullLayers = config.fullAttentionLayerMask.reduce(0) { $0 + ($1 == 0 ? 0 : 1) }+ let slidingLayers = config.numLayers - fullLayers+ let fp16Bytes = 2+ let keyAndValue = 2+ let slidingRows = productionSlidingRingRows(config: config, maxContext: maxContext)+ let slidingBytesPerRow = config.numKVHeads * config.headDim * keyAndValue * fp16Bytes+ let fullBytesPerRow = config.numFullKVHeads * config.fullHeadDim * keyAndValue * fp16Bytes+ return UInt64(slidingLayers * slidingRows * slidingBytesPerRow)+ + UInt64(fullLayers * maxContext * fullBytesPerRow)+ }++ /// What the process is expected to occupy at this context.+ public static func projectedFootprintBytes(config: ArchConfig, maxContext: Int, expertCacheSlots: Int = 16) -> UInt64 {+ fp16KVBytes(config: config, maxContext: maxContext) + nonKVRuntimeFootprintBytes+ + additionalExpertCacheBytes(config: config, slots: expertCacheSlots)+ }++ /// The smallest host memory that admits this context.+ public static func minimumHostMemoryBytes(config: ArchConfig, maxContext: Int, expertCacheSlots: Int = 16) -> UInt64 {+ projectedFootprintBytes(config: config, maxContext: maxContext, expertCacheSlots: expertCacheSlots) + hostReserveBytes+ }++ public static func availability(config: ArchConfig,+ maxContext: Int,+ hostMemoryBytes: UInt64, expertCacheSlots: Int = 16) -> Availability {+ let minimum = minimumHostMemoryBytes(config: config, maxContext: maxContext, expertCacheSlots: expertCacheSlots)+ return hostMemoryBytes >= minimum ? .available : .needsMemory(minimumHostBytes: minimum)+ }++ public static var hostMemoryBytes: UInt64 { ProcessInfo.processInfo.physicalMemory }++ /// One sentence naming what the context needs and what this Mac has, for a+ /// refusal, a hidden menu row's caption or a CLI warning.+ public static func needDescription(config: ArchConfig,+ maxContext: Int,+ hostMemoryBytes: UInt64, expertCacheSlots: Int = 16) -> String {+ let need = marketingGigabytesRoundedUp(+ minimumHostMemoryBytes(config: config, maxContext: maxContext, expertCacheSlots: expertCacheSlots))+ let have = marketingGigabytesNearest(hostMemoryBytes)+ return "A \(grouped(maxContext))-token context needs \(need) GB of memory; this Mac has \(have) GB."+ }++ /// Memory sizes Apple actually ships, so the sentence names a machine the+ /// reader can recognize instead of "10.25 GiB".+ private static let machineSizesGB = [8, 16, 24, 32, 36, 48, 64, 96, 128, 192, 256, 512]++ /// The requirement is rounded in GiB because that is the unit+ /// `physicalMemory` reports: an "8 GB Mac" answers 8,589,934,592, so a need+ /// of 8,320,122,880 is met by it and must print as 8 GB, not 16.+ private static func marketingGigabytesRoundedUp(_ bytes: UInt64) -> Int {+ if let size = machineSizesGB.first(where: { UInt64($0) << 30 >= bytes }) { return size }+ return Int((bytes + (1 << 30) - 1) >> 30)+ }++ /// The host is reported in decimal GB, which is how the same machine is+ /// labeled in About This Mac.+ private static func marketingGigabytesNearest(_ bytes: UInt64) -> Int {+ let decimal = Double(bytes) / 1e9+ guard let nearest = machineSizesGB.min(by: {+ abs(Double($0) - decimal) < abs(Double($1) - decimal)+ }) else { return Int(decimal.rounded()) }+ return nearest+ }++ /// Grouped by threes without a locale, so the message reads the same in+ /// every region and in test assertions.+ private static func grouped(_ value: Int) -> String {+ let digits = Array(String(value))+ var out = ""+ for (index, digit) in digits.enumerated() {+ if index > 0, (digits.count - index) % 3 == 0 { out.append(",") }+ out.append(digit)+ }+ return out+ }+}diff --git a/Sources/TurboFieldfare/Runtime/KVCache/KVCacheManager.swift b/Sources/TurboFieldfare/Runtime/KVCache/KVCacheManager.swiftindex e8555f67..aa28b2d8 100644--- a/Sources/TurboFieldfare/Runtime/KVCache/KVCacheManager.swift+++ b/Sources/TurboFieldfare/Runtime/KVCache/KVCacheManager.swift@@ -73,6 +73,13 @@ public final class KVCacheManager {fp16RingCapacityOverride: Int? = nil) throws {precondition(maxContext > 0, "maxContext must be positive")precondition(maxPrefillChunkTokens > 0, "maxPrefillChunkTokens must be positive")+ // Refused before a single `makeBuffer`: a context past the checkpoint's+ // position ceiling has no valid RoPE positions, and allocating 5+ GiB+ // of KV before saying so is the expensive way to learn it.+ guard maxContext <= config.maxPositionEmbeddings else {+ throw ModelError.contextExceedsModel(requested: maxContext,+ maximum: config.maxPositionEmbeddings)+ }self.config = configself.maxContext = maxContextlet ringEnabled = fp16RingEnabled@@ -103,13 +110,13 @@ public final class KVCacheManager {let length = capacity * strideguard let kBuf = device.makeBuffer(length: length, options: .storageModeShared) else {- throw ModelError.residentBufferWrapFailed+ throw ModelError.kvAllocationFailed(layer: layer, bytes: length)}kBuf.label = "kv.K.layer\(layer)"ks.append(kBuf)guard let vBuf = device.makeBuffer(length: length, options: .storageModeShared) else {- throw ModelError.residentBufferWrapFailed+ throw ModelError.kvAllocationFailed(layer: layer, bytes: length)}vBuf.label = "kv.V.layer\(layer)"vs.append(vBuf)@@ -234,11 +241,15 @@ public final class KVCacheManager {position = newPosition}- /// Drop all cached positions and return physical pages to the OS.+ /// Drop all cached positions and advise the pages away.////// 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.+ /// and `validTokenCount` is now 0. The `MADV_DONTNEED` is advisory only:+ /// measured on macOS 26 (M5 Pro, 2026-08-28), `phys_footprint` did not move+ /// after advising a fully written 262,144-row cache, and a single attention+ /// bind had already charged each bound buffer in full. Sizing decisions+ /// must therefore treat the KV as resident at its allocated size for as+ /// long as the runner lives; see `ContextAdmission`.public func reset() {position = 0highWaterPosition = 0diff --git a/Sources/TurboFieldfare/Runtime/Vision/VisionImageTokenBudget.swift b/Sources/TurboFieldfare/Runtime/Vision/VisionImageTokenBudget.swiftindex 8922541f..2926587d 100644--- a/Sources/TurboFieldfare/Runtime/Vision/VisionImageTokenBudget.swift+++ b/Sources/TurboFieldfare/Runtime/Vision/VisionImageTokenBudget.swift@@ -20,6 +20,13 @@ public enum VisionImageTokenBudget {VisionConfig().maximumPooledTokens + markerTokensPerImage}+ /// An absolute ceiling on one turn's attachments, on top of the+ /// context-derived budget. The arithmetic alone is unbounded in the+ /// context: a 262,144-token context would offer about 930 images in a+ /// single message, each of which has to be decoded, preprocessed and+ /// encoded before the turn produces a token.+ public static let maximumAttachmentsPerTurn = 32+public static func imageTokens(softTokenCounts: [Int]) -> Int {softTokenCounts.reduce(0) { $0 + $1 + markerTokensPerImage }}@@ -61,6 +68,6 @@ public enum VisionImageTokenBudget {return 0}let available = maxContext - reservedTextTokens- return available / maximumTokensPerImage+ return min(available / maximumTokensPerImage, maximumAttachmentsPerTurn)}}diff --git a/Sources/TurboFieldfareApp/Core/Configuration/AppContextLengthOption.swift b/Sources/TurboFieldfareApp/Core/Configuration/AppContextLengthOption.swiftindex f558f05e..f8d22842 100644--- a/Sources/TurboFieldfareApp/Core/Configuration/AppContextLengthOption.swift+++ b/Sources/TurboFieldfareApp/Core/Configuration/AppContextLengthOption.swift@@ -6,6 +6,8 @@ public enum AppContextLengthOption: Int, CaseIterable, Identifiable, Sendable {case sixteenK = 16_384case thirtyTwoK = 32_768case sixtyFourK = 65_536+ case oneTwentyEightK = 131_072+ case twoFiftySixK = 262_144public var id: Int { rawValue }public var tokens: Int { rawValue }@@ -14,41 +16,75 @@ public enum AppContextLengthOption: Int, CaseIterable, Identifiable, Sendable {"\(tokens / 1_024)K"}+ /// The architecture every figure on this type is derived from. The menu+ /// only ever offers contexts for the model the app ships with.+ private static let architecture = ArchConfig.gemma4_26B_A4B++ /// Delegated rather than recomputed: the menu label, the loader's refusal,+ /// the server's and the CLI's answers all have to be the same arithmetic,+ /// and they were not when each surface carried its own copy.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- // The ring the runtime actually allocates: the window plus the widest- // prefill chunk it may see, which is the pooled image-token count, not- // the default text chunk. Using the smaller number understates every- // estimate by about 29.69 MiB.- let slidingRows = min(- tokens,- architecture.slidingWindow + max(- PrefillRuntimeConfig.defaultChunked.chunkTokens,- VisionConfig().maximumPooledTokens))- 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)+ ContextAdmission.fp16KVBytes(config: Self.architecture, maxContext: tokens)}+ public var projectedFootprintBytes: UInt64 {+ ContextAdmission.projectedFootprintBytes(config: Self.architecture,+ maxContext: tokens)+ }++ public var minimumHostMemoryBytes: UInt64 {+ ContextAdmission.minimumHostMemoryBytes(config: Self.architecture,+ maxContext: tokens)+ }++ public func availability(hostMemoryBytes: UInt64, expertCacheSlots: Int = 16) -> ContextAdmission.Availability {+ ContextAdmission.availability(config: Self.architecture,+ maxContext: tokens,+ hostMemoryBytes: hostMemoryBytes, expertCacheSlots: expertCacheSlots)+ }++ public func needDescription(hostMemoryBytes: UInt64, expertCacheSlots: Int = 16) -> String {+ ContextAdmission.needDescription(config: Self.architecture,+ maxContext: tokens,+ hostMemoryBytes: hostMemoryBytes, expertCacheSlots: expertCacheSlots)+ }++ /// The options this host can actually back, in ascending order.+ ///+ /// A 262,144-token KV is charged in full the moment a command buffer binds+ /// it — one full-attention layer over sixteen rows already costs the whole+ /// 1,085 MiB — so admission is decided by the cap, never by how much of it+ /// a conversation happens to use.+ public static func available(on hostMemoryBytes: UInt64, expertCacheSlots: Int = 16) -> [AppContextLengthOption] {+ allCases.filter { $0.availability(hostMemoryBytes: hostMemoryBytes, expertCacheSlots: expertCacheSlots) == .available }+ }++ /// The largest context this host can back, for clamping a stored choice it+ /// cannot. A host too small even for the smallest option still gets one:+ /// the loader refuses an unbacked context before it allocates, so the+ /// refusal is where that machine is told, not a menu with no rows in it.+ public static func largestAvailable(on hostMemoryBytes: UInt64, expertCacheSlots: Int = 16) -> AppContextLengthOption {+ available(on: hostMemoryBytes, expertCacheSlots: expertCacheSlots).last ?? .fourK+ }++ public static let defaultOption: AppContextLengthOption = .eightK++ /// The default row is labeled as such; every other row shows its FP16 KV+ /// allocation relative to the default, computed from `fp16KVBytes` rather+ /// than hardcoded so a default change moves every delta with it.public var menuLabel: String {- switch self {- // Measured against the 8K default, not against 4K: moving the default- // without moving the baseline would have left every delta describing a- // size the user is no longer starting from.- case .fourK: "4K, -85 MB"- case .eightK: "8K, Default"- case .sixteenK: "16K, +170 MB"- case .thirtyTwoK: "32K, +500 MB"- case .sixtyFourK: "64K, +1.17 GB"+ guard self != Self.defaultOption else { return "\(shortLabel), Default" }+ let delta = Int64(fp16KVBytes) - Int64(Self.defaultOption.fp16KVBytes)+ return "\(shortLabel), \(Self.formattedDelta(delta))"+ }++ private static func formattedDelta(_ bytes: Int64) -> String {+ let sign = bytes < 0 ? "-" : "+"+ let megabytes = Double(abs(bytes)) / 1_000_000+ guard megabytes < 1_000 else {+ return String(format: "%@%.2f GB", sign, megabytes / 1_000)}+ let rounded = Int((megabytes / 5).rounded()) * 5+ return "\(sign)\(rounded) MB"}}diff --git a/Sources/TurboFieldfareApp/Core/Configuration/MacAppSettings.swift b/Sources/TurboFieldfareApp/Core/Configuration/MacAppSettings.swiftindex 52fe1964..60bf6208 100644--- a/Sources/TurboFieldfareApp/Core/Configuration/MacAppSettings.swift+++ b/Sources/TurboFieldfareApp/Core/Configuration/MacAppSettings.swift@@ -3,7 +3,7 @@ import TurboFieldfarestruct MacAppSettings: Codable, Equatable, Sendable {static let fileName = "mac-app-settings.json"- static let currentVersion = 2+ static let currentVersion = 3var version: Int = currentVersionvar contextTokens: Int = AppContextLengthOption.eightK.tokensdiff --git a/Sources/TurboFieldfareApp/Core/Inference/AppGenerationRequest.swift b/Sources/TurboFieldfareApp/Core/Inference/AppGenerationRequest.swiftindex 30352b78..d52c5747 100644--- a/Sources/TurboFieldfareApp/Core/Inference/AppGenerationRequest.swift+++ b/Sources/TurboFieldfareApp/Core/Inference/AppGenerationRequest.swift@@ -80,6 +80,16 @@ public struct AppGenerationRequest: Equatable, Sendable {guard maxContextTokens > 0 else {throw AppInferenceError.invalidRequest("Max context must be greater than zero.")}+ // The checkpoint's `max_position_embeddings`. Above it the model is+ // being asked for a position it was never trained to address, which no+ // amount of memory makes valid, so this is refused here rather than+ // discovered as a KV allocation the runtime then throws on.+ let modelCeiling = ArchConfig.gemma4_26B_A4B.maxPositionEmbeddings+ guard maxContextTokens <= modelCeiling else {+ throw AppInferenceError.invalidRequest(+ "Max context \(maxContextTokens) is above the model's "+ + "\(modelCeiling)-token limit.")+ }guard conversationTokens >= 0, conversationTokens <= maxContextTokens else {throw AppInferenceError.invalidRequest("Conversation tokens must be between zero and the max context.")diff --git a/Sources/TurboFieldfareApp/Core/State/AppModel.swift b/Sources/TurboFieldfareApp/Core/State/AppModel.swiftindex bcd47dae..af302286 100644--- a/Sources/TurboFieldfareApp/Core/State/AppModel.swift+++ b/Sources/TurboFieldfareApp/Core/State/AppModel.swift@@ -64,7 +64,12 @@ public final class AppModel {/// which stored conversations can be continued — and what is on screen has/// to be redrawn from the answer that now applies, not the one taken when/// the row was clicked.- public private(set) var maxContextTokens: Int = AppContextLengthOption.eightK.tokens+ public private(set) var maxContextTokens: Int = AppContextLengthOption.eightK.tokens {+ didSet {+ if maxContextTokens != oldValue { contextClampNotice = nil }+ }+ }+ public private(set) var contextClampNotice: String?public var temperature: Double = 0.2public var topKEnabled: Bool = truepublic var topK: Int = 64@@ -172,6 +177,11 @@ public final class AppModel {/// Internal rather than private: the history extension releases the staged/// copies of a conversation the KV is giving up, and lives in another file.let attachmentStore: AppImageAttachmentStore+ /// What this Mac has, injected so the admission rule is testable without a+ /// machine of that size. Read once: `physicalMemory` cannot change under a+ /// running process, and re-reading it per query would make the menu, the+ /// clamp and the load refusal three separate answers.+ private let hostMemoryBytes: UInt64public let isVisionRuntimeSupported: Bool/// The stored conversations and which one is open.public let history = ConversationHistoryState()@@ -223,7 +233,8 @@ public final class AppModel {},conversationStoreProvider: @escaping @Sendable (URL) -> ConversationStore = {ConversationStore(rootURL: $0)- }) {+ },+ hostMemoryBytes: UInt64 = ContextAdmission.hostMemoryBytes) {let directory = (modelDirectory ?? AppModelLocation.defaultURL()).standardizedFileURLlet installETAClock = SuspendingClock()let settings = settingsPersistenceEnabled@@ -241,7 +252,11 @@ public final class AppModel {prefillEnabled: settings.prefillEnabled,rdadvisePolicy: settings.rdadvisePolicy,visionResidencyPolicy: .onDemand)- self.maxContextTokens = settings.contextTokens+ let admitted = Self.admittedContext(settings.contextTokens,+ hostMemoryBytes: hostMemoryBytes,+ expertCacheSlots: settings.expertCacheSlots)+ self.maxContextTokens = admitted.tokens+ self.contextClampNotice = admitted.noticeself.temperature = settings.temperatureself.topKEnabled = settings.topKEnabledself.topK = settings.topK@@ -260,6 +275,7 @@ public final class AppModel {self.visionInstaller = visionInstallerself.memorySampler = memorySamplerself.attachmentStore = attachmentStore+ self.hostMemoryBytes = hostMemoryBytesself.isVisionRuntimeSupported = visionRuntimeSupportedself.settingsPersistenceEnabled = settingsPersistenceEnabledself.conversationIdentityProvider = conversationIdentityProvider@@ -297,6 +313,54 @@ public final class AppModel {activateConversationStore()}+ /// What the Context picker may offer on this Mac.+ public var contextOptions: [AppContextLengthOption] {+ AppContextLengthOption.available(on: hostMemoryBytes, expertCacheSlots: runtimeOptions.expertCacheSlots)+ }++ /// The caption under the Context picker when admission is hiding rows.+ ///+ /// Static and free of SwiftUI so the sentence a user reads is covered by a+ /// test rather than by looking at the window. Nil when every size is+ /// offered — there is then nothing to explain.+ public nonisolated static func contextOptionsNote(hostMemoryBytes: UInt64, expertCacheSlots: Int = 16) -> String? {+ let hidden = AppContextLengthOption.allCases.filter {+ $0.availability(hostMemoryBytes: hostMemoryBytes, expertCacheSlots: expertCacheSlots) != .available+ }+ guard !hidden.isEmpty else { return nil }+ return hidden+ .map { $0.needDescription(hostMemoryBytes: hostMemoryBytes, expertCacheSlots: expertCacheSlots) }+ .joined(separator: " ")+ }++ public var contextOptionsNote: String? {+ Self.contextOptionsNote(hostMemoryBytes: hostMemoryBytes, expertCacheSlots: runtimeOptions.expertCacheSlots)+ }++ /// A stored context this host cannot back, replaced with the largest it+ /// can plus the sentence that says so.+ ///+ /// Not a cosmetic correction: `beginLoad` refuses an unbacked context+ /// before it allocates, so leaving the stored value in place would open+ /// the app on a setting whose every load fails.+ nonisolated static func admittedContext(+ _ tokens: Int,+ hostMemoryBytes: UInt64,+ expertCacheSlots: Int = 16+ ) -> (tokens: Int, notice: String?) {+ let config = ArchConfig.gemma4_26B_A4B+ guard case .needsMemory = ContextAdmission.availability(+ config: config, maxContext: tokens, hostMemoryBytes: hostMemoryBytes, expertCacheSlots: expertCacheSlots) else {+ return (tokens, nil)+ }+ let fallback = AppContextLengthOption.largestAvailable(on: hostMemoryBytes, expertCacheSlots: expertCacheSlots)+ let need = ContextAdmission.needDescription(config: config,+ maxContext: tokens,+ hostMemoryBytes: hostMemoryBytes, expertCacheSlots: expertCacheSlots)+ return (fallback.tokens,+ "\(need) Context is set to \(fallback.shortLabel) instead.")+ }+public var isRunning: Bool { runState == .running }public var isModelAvailable: Bool { loadState.isReady }@@ -840,6 +904,19 @@ public final class AppModel {persistSettings()}+ public func setExpertCacheSlots(_ slots: Int) {+ guard runtimeOptions.expertCacheSlots != slots else { return }+ runtimeOptions.expertCacheSlots = slots+ let admitted = Self.admittedContext(maxContextTokens,+ hostMemoryBytes: hostMemoryBytes,+ expertCacheSlots: slots)+ if admitted.tokens != maxContextTokens {+ setMaxContextTokens(admitted.tokens)+ contextClampNotice = admitted.notice+ }+ persistSettings()+ }+/// Changes the context, and redraws a stored conversation against it.////// Continuability is a function of the conversation's size and the context@@ -1096,7 +1173,14 @@ public final class AppModel {}static func imageCapacityMessage(capacity: Int, context: Int) -> String {- "At most \(capacity) image\(capacity == 1 ? "" : "s") fit in the "+ let plural = capacity == 1 ? "" : "s"+ // Once about 9,000 tokens are free it is the per-turn cap that binds,+ // not the context, and telling the reader to raise Context would send+ // them to a setting that cannot change the answer.+ guard capacity < VisionImageTokenBudget.maximumAttachmentsPerTurn else {+ return "At most \(capacity) image\(plural) can be sent in one message."+ }+ return "At most \(capacity) image\(plural) fit in the "+ "\(context / 1_024)K context this session is running with. Raise "+ "Context in Memory and reload the model to send more."}@@ -1181,6 +1265,20 @@ public final class AppModel {}let directory = URL(fileURLWithPath: modelPathText)let maxContext = maxContextTokens+ // Refused here, before the load state moves and before anything is+ // sent to the decode service. A 262,144-token KV is charged in full+ // the moment a command buffer binds it, so a host that cannot hold it+ // does not find out part-way through a load: it is killed.+ if case .needsMemory = ContextAdmission.availability(+ config: ArchConfig.gemma4_26B_A4B,+ maxContext: maxContext,+ hostMemoryBytes: hostMemoryBytes, expertCacheSlots: runtimeOptions.expertCacheSlots) {+ loadState = .failed(.modelLoadFailed(+ ContextAdmission.needDescription(config: ArchConfig.gemma4_26B_A4B,+ maxContext: maxContext,+ hostMemoryBytes: hostMemoryBytes, expertCacheSlots: runtimeOptions.expertCacheSlots)))+ return+ }let forceLogitsHead = currentForceLogitsHeadlet runtimeKey = AppLoadedRuntimeKey(modelDirectory: directory,maxContextTokens: maxContext,@@ -1946,7 +2044,15 @@ public final class AppModel {// `keepReady` written by an older build resurrect ~1 GB of resident// tower on a machine with no control that shows or clears it.visionResidencyPolicy: .onDemand)- maxContextTokens = settings.contextTokens+ // Clamped for the same reason as `init`: another model directory can+ // carry a context this Mac cannot back, and adopting it would leave+ // the app on a setting the loader refuses. Assigned before the notice+ // because the assignment clears it.+ let admitted = Self.admittedContext(settings.contextTokens,+ hostMemoryBytes: hostMemoryBytes,+ expertCacheSlots: settings.expertCacheSlots)+ maxContextTokens = admitted.tokens+ contextClampNotice = admitted.noticetemperature = settings.temperaturetopKEnabled = settings.topKEnabledtopK = settings.topKdiff --git a/Sources/TurboFieldfareApp/Mac/Diagnostics/InspectorView.swift b/Sources/TurboFieldfareApp/Mac/Diagnostics/InspectorView.swiftindex 4bf4d52a..de010899 100644--- a/Sources/TurboFieldfareApp/Mac/Diagnostics/InspectorView.swift+++ b/Sources/TurboFieldfareApp/Mac/Diagnostics/InspectorView.swift@@ -299,8 +299,10 @@ struct InspectorView: View {private var memorySection: some View {Section("Memory") {LabeledContent("Context") {+ // Only the sizes this Mac can back. Offering one it cannot+ // would put a row in the menu that every load then refuses.Picker("Context", selection: contextTokensBinding) {- ForEach(AppContextLengthOption.allCases) { option in+ ForEach(model.contextOptions) { option inText(option.menuLabel).tag(option.tokens)}}@@ -309,8 +311,17 @@ struct InspectorView: View {.fixedSize().accessibilityIdentifier(.inspectorContext)}+ // The clamp notice already carries the need it clamped for, so+ // showing both would print the same sentence twice.+ if let note = model.contextClampNotice ?? model.contextOptionsNote {+ Text(note)+ .font(.caption)+ .foregroundStyle(.secondary)+ }LabeledContent("Slots") {- Picker("Slots", selection: $model.runtimeOptions.expertCacheSlots) {+ Picker("Slots", selection: Binding(+ get: { model.runtimeOptions.expertCacheSlots },+ set: { model.setExpertCacheSlots($0) })) {ForEach(AppRuntimeOptions.allowedSlotCounts, id: \.self) { slots inText(AppRuntimeOptions.slotsLabel(for: slots)).tag(slots)}diff --git a/Sources/TurboFieldfareApp/MacPresentation/AboutPanelPresentation.swift b/Sources/TurboFieldfareApp/MacPresentation/AboutPanelPresentation.swiftindex ec251b1e..ea4c9bd8 100644--- a/Sources/TurboFieldfareApp/MacPresentation/AboutPanelPresentation.swift+++ b/Sources/TurboFieldfareApp/MacPresentation/AboutPanelPresentation.swift@@ -17,7 +17,7 @@ public enum AboutPanelPresentation {// Most users build from a clone, where there is no Info.plist to read a// version from, so this constant is what they see. Scripts/check_app_version.rb// fails CI when it falls behind the newest published release.- public static let fallbackShortVersion = "0.8.1"+ public static let fallbackShortVersion = "0.9.0"private static let licenseURL = URL(string: "https://github.com/drumih/turbo-fieldfare/blob/main/LICENSE")!diff --git a/Sources/TurboFieldfareCLI/Args.swift b/Sources/TurboFieldfareCLI/Args.swiftindex 95d2550a..bb27fde2 100644--- a/Sources/TurboFieldfareCLI/Args.swift+++ b/Sources/TurboFieldfareCLI/Args.swift@@ -82,6 +82,7 @@ public enum ArgsError: Error, Equatable, CustomStringConvertible {case mutuallyExclusive(String, String)case modeMissingcase imagePromptNeedsExpertCacheSlots(have: Int, need: Int)+ case contextExceedsModel(requested: Int, maximum: Int)public var description: String {switch self {@@ -97,6 +98,8 @@ public enum ArgsError: Error, Equatable, CustomStringConvertible {return "--image requires chunked prefill, which needs at least \(need) "+ "expert-cache slots; --expert-cache-slots \(have) cannot serve it: "+ "raise --expert-cache-slots to \(need) or more, or drop --image"+ case .contextExceedsModel(let requested, let maximum):+ return "--max-context \(requested) exceeds the model's maximum position \(maximum)"}}}@@ -131,7 +134,7 @@ extension Args {options:--max-new <int> Generated-token limit (default 1024).- --max-context <int> Context limit in tokens (default 8192).+ --max-context <int> Context limit in tokens (default 8192, max 262144).--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).@@ -253,6 +256,10 @@ extension Args {guard let parsed = Int(value), parsed > 0 else {throw ArgsError.invalidValue(flag: flag, value: value)}+ let ceiling = ArchConfig.gemma4_26B_A4B.maxPositionEmbeddings+ guard parsed <= ceiling else {+ throw ArgsError.contextExceedsModel(requested: parsed, maximum: ceiling)+ }maxContext = parsedcase "--temperature":let value = try takeValue(argv, &index, flag: flag)diff --git a/Sources/TurboFieldfareCLI/Run.swift b/Sources/TurboFieldfareCLI/Run.swiftindex 9143a294..b15e4b62 100644--- a/Sources/TurboFieldfareCLI/Run.swift+++ b/Sources/TurboFieldfareCLI/Run.swift@@ -51,6 +51,7 @@ public func run(args: Args,stdout: FileHandle = .standardOutput,stderr: FileHandle = .standardError) async -> RunResult {do {+let modelURL = URL(fileURLWithPath: args.model)let input = try parseInput(args: args)var selectedDevice: MTLDevice?@@ -124,6 +125,21 @@ public func run(args: Args,let runtime = try args.resolvedRuntimeConfiguration(forceLogitsHead: !makeConfig(maxNewTokens: args.maxNew).isPureGreedy,imagePrompt: input.hasImages)+ // The CLI is the diagnostic surface: it says what the context will cost+ // and runs anyway, where the app hides the row and the server refuses.+ // Not gated on --quiet, which suppresses the timing footer, not a+ // warning that the run may swap or be killed.+ let hostMemory = ContextAdmission.hostMemoryBytes+ if case .needsMemory = ContextAdmission.availability(+ config: ArchConfig.gemma4_26B_A4B,+ maxContext: args.maxContext,+ hostMemoryBytes: hostMemory, expertCacheSlots: runtime.expertCacheSlots) {+ let need = ContextAdmission.needDescription(+ config: ArchConfig.gemma4_26B_A4B,+ maxContext: args.maxContext,+ hostMemoryBytes: hostMemory, expertCacheSlots: runtime.expertCacheSlots)+ stderr.write(Data("[memory: \(need) Continuing.]\n".utf8))+ }if !args.quiet,let notice = prefillCoercionNotice(diff --git a/Sources/TurboFieldfareDecodeService/DecodeLoadAdmission.swift b/Sources/TurboFieldfareDecodeService/DecodeLoadAdmission.swiftnew file mode 100644index 00000000..d5faf6f9--- /dev/null+++ b/Sources/TurboFieldfareDecodeService/DecodeLoadAdmission.swift@@ -0,0 +1,40 @@+import Foundation+import TurboFieldfare++/// Whether the service may attempt a load at the requested context.+///+/// Pure and separate from the command loop so the decision is testable without+/// a socket, a model or a machine of the size in question. The service is the+/// process that would be killed: a 262,144-token KV is charged in full the+/// moment a command buffer binds it, so an unbacked context is not a load that+/// runs slowly — it is a jetsam kill with no event on the wire, which the app+/// can only report as a lost connection.+enum DecodeLoadAdmission {+ /// Diagnostics only. Set it to run a context this rule refuses and find out+ /// what actually happens on the machine, which is the measurement the rule+ /// itself came from.+ static let overrideEnvironmentKey = "TURBO_FIELDFARE_ALLOW_UNBACKED_CONTEXT"++ /// The message to answer the load with, or nil to proceed.+ static func refusal(maxContextTokens: Int,+ hostMemoryBytes: UInt64,+ environment: [String: String], expertCacheSlots: Int = 16) -> String? {+ let config = ArchConfig.gemma4_26B_A4B+ // The ceiling is the checkpoint's, not the host's, so no override+ // reaches it: memory cannot make a position the model was never+ // trained to address valid.+ guard maxContextTokens <= config.maxPositionEmbeddings else {+ return ModelError.contextExceedsModel(+ requested: maxContextTokens,+ maximum: config.maxPositionEmbeddings).description+ }+ guard environment[overrideEnvironmentKey] != "1" else { return nil }+ guard case .needsMemory = ContextAdmission.availability(+ config: config,+ maxContext: maxContextTokens,+ hostMemoryBytes: hostMemoryBytes, expertCacheSlots: expertCacheSlots) else { return nil }+ return ContextAdmission.needDescription(config: config,+ maxContext: maxContextTokens,+ hostMemoryBytes: hostMemoryBytes, expertCacheSlots: expertCacheSlots)+ }+}diff --git a/Sources/TurboFieldfareDecodeService/Entry.swift b/Sources/TurboFieldfareDecodeService/Entry.swiftindex 0c134b83..aa27a6ec 100644--- a/Sources/TurboFieldfareDecodeService/Entry.swift+++ b/Sources/TurboFieldfareDecodeService/Entry.swift@@ -94,6 +94,16 @@ enum DecodeServiceError: Error, CustomStringConvertible {}do {let options = try appRuntimeOptions(request.runtimeOptions)+ if let refusal = DecodeLoadAdmission.refusal(+ maxContextTokens: request.maxContextTokens,+ hostMemoryBytes: ContextAdmission.hostMemoryBytes,+ environment: ProcessInfo.processInfo.environment,+ expertCacheSlots: options.expertCacheSlots) {+ try? write(DecodeServiceEvent(+ kind: .failed, generationID: request.requestID, error: refusal),+ to: handles.output)+ break+ }// The session load already checks for cancellation between// its stages; running it in a task is what gives the input// thread something to cancel.diff --git a/Sources/TurboFieldfareServer/Core/ServerArguments.swift b/Sources/TurboFieldfareServer/Core/ServerArguments.swiftindex 56d3f740..9179b459 100644--- a/Sources/TurboFieldfareServer/Core/ServerArguments.swift+++ b/Sources/TurboFieldfareServer/Core/ServerArguments.swift@@ -16,6 +16,11 @@ public struct ServerArguments: Equatable, Sendable {public let visionPack: String?public let visionResidency: VisionResidencyPolicy+ public static let allowedMaxContext = [+ 4_096, 8_192, 16_384, 32_768, 65_536, 98_304, 131_072, 196_608, 262_144,+ ]+ public static let unbackedContextOverrideVariable = "TURBO_FIELDFARE_ALLOW_UNBACKED_CONTEXT"+public static let usage = """usage: TurboFieldfareServer --model <completed .gturbo directory> [options]@@ -25,7 +30,10 @@ public struct ServerArguments: Equatable, Sendable {Routed-expert residency during vision (default on-demand).--port <1...65535> Loopback port (default 8080).--model-id <id> API model identifier (default gemma-4-26b-a4b-it).- --max-context <tokens> 4096, 8192, 16384, 32768, or 65536 (default 16384).+ --max-context <tokens> 4096, 8192, 16384, 32768, 65536, 98304,+ 131072, 196608, or 262144 (default 16384).+ Contexts exceeding the host memory budget are refused.+ TURBO_FIELDFARE_ALLOW_UNBACKED_CONTEXT=1 overrides this.--queue-limit <count> Maximum queued requests (default 4).--prompt-cache-mode <off|single-prefix>Prompt KV reuse mode (default single-prefix).@@ -80,7 +88,11 @@ public struct ServerArguments: Equatable, Sendable {forceLogitsHead: forceLogitsHead)}- public static func parse(_ input: [String]) throws -> ServerArguments {+ public static func parse(+ _ input: [String],+ hostMemoryBytes: UInt64 = ContextAdmission.hostMemoryBytes,+ environment: [String: String] = ProcessInfo.processInfo.environment+ ) throws -> ServerArguments {var model: String?var port = 8080var modelID = "gemma-4-26b-a4b-it"@@ -118,7 +130,7 @@ public struct ServerArguments: Equatable, Sendable {modelID = valuecase "--max-context":guard let parsed = Int(value),- [4_096, 8_192, 16_384, 32_768, 65_536].contains(parsed) else {+ allowedMaxContext.contains(parsed) else {throw ServerArgumentError.invalid("--max-context is not supported")}maxContext = parsed@@ -193,6 +205,21 @@ public struct ServerArguments: Equatable, Sendable {}}guard let model else { throw ServerArgumentError.invalid("--model is required") }+ // Refused here rather than at load: the KV allocation for a context the+ // host cannot back fails deep inside the runtime, after the model has+ // already started loading, with an allocator error that says nothing+ // about how much memory the choice actually needs.+ let config = ArchConfig.gemma4_26B_A4B+ if case .needsMemory = ContextAdmission.availability(config: config,+ maxContext: maxContext,+ hostMemoryBytes: hostMemoryBytes, expertCacheSlots: expertCacheSlots),+ environment[unbackedContextOverrideVariable] != "1" {+ throw ServerArgumentError.invalid(+ ContextAdmission.needDescription(config: config,+ maxContext: maxContext,+ hostMemoryBytes: hostMemoryBytes, expertCacheSlots: expertCacheSlots)+ + " Set \(unbackedContextOverrideVariable)=1 to start anyway.")+ }return ServerArguments(model: model,port: port,modelID: modelID,diff --git a/Sources/TurboFieldfareServer/Core/ServerInference.swift b/Sources/TurboFieldfareServer/Core/ServerInference.swiftindex fb947d19..e94925e8 100644--- a/Sources/TurboFieldfareServer/Core/ServerInference.swift+++ b/Sources/TurboFieldfareServer/Core/ServerInference.swift@@ -12,15 +12,26 @@ public struct ServerCompletion: Equatable, Sendable {public let toolCalls: [ParsedToolCall]public let finishReason: Stringpublic let usage: OpenAIUsage+ /// Wall time the runtime spent prefilling the prompt and decoding the+ /// completion, as `runRawCompletion` already measures them around those two+ /// phases; nothing is timed here. Defaulted to zero so a backend that does+ /// not decode through the runtime — the test doubles, the compatibility+ /// harness — reports no timing rather than a fabricated one.+ public let prefillSeconds: Double+ public let decodeSeconds: Doublepublic init(content: String,toolCalls: [ParsedToolCall],finishReason: String,- usage: OpenAIUsage) {+ usage: OpenAIUsage,+ prefillSeconds: Double = 0,+ decodeSeconds: Double = 0) {self.content = contentself.toolCalls = toolCallsself.finishReason = finishReasonself.usage = usage+ self.prefillSeconds = prefillSeconds+ self.decodeSeconds = decodeSeconds}}@@ -1114,7 +1125,9 @@ public actor ServerModelSession: ServerInferenceBackend {usage: OpenAIUsage(promptTokens: result.prefillTokens,completionTokens: result.newTokens,totalTokens: result.prefillTokens + result.newTokens,- cachedTokens: result.cachedPromptTokens))+ cachedTokens: result.cachedPromptTokens),+ prefillSeconds: result.prefillSeconds,+ decodeSeconds: result.decodeSeconds)}private func renderPrompt(_ request: ValidatedChatRequest) throws -> [Int32] {diff --git a/Sources/TurboFieldfareServer/Core/ServerLog.swift b/Sources/TurboFieldfareServer/Core/ServerLog.swiftindex 3e6d41eb..77b6137b 100644--- a/Sources/TurboFieldfareServer/Core/ServerLog.swift+++ b/Sources/TurboFieldfareServer/Core/ServerLog.swift@@ -21,12 +21,38 @@ enum ServerLog {static func completed(id: String,duration: Duration,completion: ServerCompletion) {+ write(completedMessage(id: id, duration: duration, completion: completion))+ }++ /// Split out so the throughput arithmetic can be checked without a log sink+ /// and without a decode. `pp_tok_s` divides by the tokens actually+ /// prefilled: a prompt-cache hit contributes no prefill work, so counting+ /// cached tokens as prefilled would report a rate the runtime never+ /// achieved. Carries counts and durations only, never content.+ static func completedMessage(id: String,+ duration: Duration,+ completion: ServerCompletion) -> String {let usage = completion.usage- write("request \(id) completed in \(format(duration)) "+ // Clamped because both counts come from the runtime: a cached count+ // above the prompt would otherwise log a negative token count and a+ // negative rate rather than the zero work that was done.+ let computedPrefillTokens = max(+ usage.promptTokens - usage.promptTokensDetails.cachedTokens, 0)+ let prefillTokensPerSecond = completion.prefillSeconds > 0+ ? Double(computedPrefillTokens) / completion.prefillSeconds+ : 0+ let decodeTokensPerSecond = completion.decodeSeconds > 0+ ? Double(usage.completionTokens) / completion.decodeSeconds+ : 0+ return "request \(id) completed in \(format(duration)) "+ "prompt=\(usage.promptTokens) "+ "cached=\(usage.promptTokensDetails.cachedTokens) "+ "completion=\(usage.completionTokens) "- + "finish=\(completion.finishReason)")+ + "pp=\(formatSeconds(completion.prefillSeconds)) "+ + "pp_tok_s=\(formatRate(prefillTokensPerSecond)) "+ + "tg=\(formatSeconds(completion.decodeSeconds)) "+ + "tg_tok_s=\(formatRate(decodeTokensPerSecond)) "+ + "finish=\(completion.finishReason)"}/// The session is an actor, so generation is serialized: this line always@@ -81,7 +107,15 @@ enum ServerLog {private static func format(_ duration: Duration) -> String {let seconds = Double(duration.components.seconds)+ Double(duration.components.attoseconds) / 1e18- return String(format: "%.3fs", seconds)+ return formatSeconds(seconds)+ }++ private static func formatSeconds(_ seconds: Double) -> String {+ String(format: "%.3fs", seconds)+ }++ private static func formatRate(_ rate: Double) -> String {+ String(format: "%.3f", rate)}private static func write(_ message: String) {diff --git a/Tests/TurboFieldfare/Core/CLI/CLIArgumentsTests.swift b/Tests/TurboFieldfare/Core/CLI/CLIArgumentsTests.swiftindex 8e54658d..ec3a44cf 100644--- a/Tests/TurboFieldfare/Core/CLI/CLIArgumentsTests.swift+++ b/Tests/TurboFieldfare/Core/CLI/CLIArgumentsTests.swift@@ -337,4 +337,36 @@ import TurboFieldfare}}+ /// The CLI accepts the checkpoint's whole position range; nothing below+ /// the model ceiling is the CLI's to refuse.+ @Test func maxContextAtModelCeilingAccepted() throws {+ let a = try Args.parse([+ "--model", "m.gturbo",+ "--prompt", "x",+ "--max-context", "262144",+ ])+ #expect(a.maxContext == 262_144)+ #expect(a.maxContext == ArchConfig.gemma4_26B_A4B.maxPositionEmbeddings)+ }++ /// One token past the ceiling is refused at parse time, naming both the+ /// request and the maximum — before the model load that would otherwise+ /// turn it into a KV allocation failure.+ @Test func maxContextAboveModelCeilingRejected() {+ do {+ _ = try Args.parse([+ "--model", "m.gturbo",+ "--prompt", "x",+ "--max-context", "262145",+ ])+ Issue.record("--max-context 262145 was accepted above the model ceiling")+ } catch let error as ArgsError {+ #expect(error == .contextExceedsModel(requested: 262_145, maximum: 262_144))+ #expect(error.description.contains("262145"))+ #expect(error.description.contains("262144"))+ } catch {+ Issue.record("unexpected error: \(error)")+ }+ }+}diff --git a/Tests/TurboFieldfare/Core/Kernels/Attention/AttentionTests.swift b/Tests/TurboFieldfare/Core/Kernels/Attention/AttentionTests.swiftindex a782ca37..0088d0b1 100644--- a/Tests/TurboFieldfare/Core/Kernels/Attention/AttentionTests.swift+++ b/Tests/TurboFieldfare/Core/Kernels/Attention/AttentionTests.swift@@ -115,6 +115,7 @@ import TurboFieldfareValidationSupportseqLen: Int,mode: Mode,shareKV: Bool = false,+ useGroupedVector: Bool = true,seed: UInt64,tolerance: Float = Tolerance.fp16ChainedReduction) throws {@@ -171,7 +172,7 @@ import TurboFieldfareValidationSupportheadDim: UInt32(headDim),numQHeads: UInt32(numQHeads),numKVHeads: UInt32(numKVHeads),- seqLen: UInt32(seqLen))+ seqLen: UInt32(seqLen), useGroupedVector: useGroupedVector)}cmd.commit()cmd.waitUntilCompleted()@@ -384,4 +385,177 @@ import TurboFieldfareValidationSupportseqLen: 128, mode: .full, shareKV: true,seed: 0x177)}++ // Grouped vector split-KV (D512 full attention) ---------------------------++ /// These are tolerance checks against the independent FP32 reference.+ /// GroupedAttentionIdentityTests separately checks D-1a against production.+ ///+ /// 17 is the case that matters most: 16 chunks over 17 keys gives+ /// chunkLen 2, so chunk 9 onward start past the range end and must+ /// contribute (-inf, 0, 0) rather than garbage.+ @Test(arguments: [1, 3, 5, 17, 31, 32, 33, 64, 128, 1_024, 4_096])+ func attentionFull_groupedVector_matchesReference(seqLen: Int) throws {+ try Self.runAndCompare(headDim: 512, numQHeads: 16, numKVHeads: 2,+ seqLen: seqLen, mode: .full,+ useGroupedVector: true,+ seed: 0x9E1 &+ UInt64(seqLen))+ }++ /// K and V diverge through separate per-head norms and RoPE in the real+ /// runtime; aliasing them would hide a V-indexing bug.+ @Test func attentionFull_groupedVector_sharedKV() throws {+ try Self.runAndCompare(headDim: 512, numQHeads: 16, numKVHeads: 2,+ seqLen: 320, mode: .full, shareKV: true,+ useGroupedVector: true, seed: 0x9E2)+ }++ /// Production scale is 1.0; the reference convention is 1/sqrt(head_dim).+ /// The kernel applies the scale after the dot, as the exact kernel does,+ /// so both must land on the reference.+ @Test func attentionFull_groupedVector_defaultScale() throws {+ try Self.runAndCompare(headDim: 512, numQHeads: 16, numKVHeads: 2,+ seqLen: 96, mode: .full,+ useGroupedVector: true, seed: 0x9E3)+ }++ @Test func attentionFull_groupedVector_isDeterministic() throws {+ let ctx = try MetalContext()+ let kernel = try Attention(context: ctx)+ var rng = SeedTree(0x9E4).key("grouped-vec-determinism")+ let qCount = 16 * 512+ let kvCount = 700 * 2 * 512+ let q = (0..<qCount).map { _ in Float16(rng.uniform(-0.5, 0.5)) }+ let k = (0..<kvCount).map { _ in Float16(rng.uniform(-0.5, 0.5)) }+ let v = (0..<kvCount).map { _ in Float16(rng.uniform(-0.5, 0.5)) }+ 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) else {+ Issue.record("Failed to allocate buffers"); return+ }+ func run() -> [Float] {+ guard let out = Fp16Buffer.make(ctx.device, count: qCount),+ let cb = ctx.queue.makeCommandBuffer() else { return [] }+ kernel.encodeFull(commandBuffer: cb, q: qBuf, k: kBuf, v: vBuf, out: out,+ headDim: 512, numQHeads: 16, numKVHeads: 2,+ seqLen: 700, scale: 1.0, useGroupedVector: true)+ cb.commit(); cb.waitUntilCompleted()+ return Fp16Buffer.read(out, count: qCount)+ }+ #expect(run() == run())+ }++ /// One threadgroup per (kv_head, chunk) instead of one per (q_head, chunk):+ /// 8x fewer partial threadgroups for the same split.+ @Test func attentionFull_groupedVector_dispatchesPerKVHead() throws {+ let grouped = Attention.splitGeometry(headDim: 512, numQHeads: 16,+ numKVHeads: 2, seqLen: 4_096,+ kvStart: 0, preferGQASWA: false,+ forceGroupedVector: true)+ let exact = Attention.splitGeometry(headDim: 512, numQHeads: 16,+ numKVHeads: 2, seqLen: 4_096,+ kvStart: 0, preferGQASWA: false)+ #expect(grouped.useFullGroupedVectorPartial)+ #expect(!exact.useFullGroupedVectorPartial)+ #expect(grouped.numChunks == exact.numChunks)+ #expect(grouped.partialThreadgroups == 2 * grouped.numChunks)+ #expect(exact.partialThreadgroups == 16 * exact.numChunks)+ }++ /// The kernel indexes 16 Q heads over 2 KV heads with 16 components per+ /// lane. Any other shape must fall back to the exact split kernel.+ @Test func attentionFull_groupedVector_rejectsOtherShapes() throws {+ let wrongHeadDim = Attention.splitGeometry(headDim: 256, numQHeads: 16,+ numKVHeads: 8, seqLen: 1_024,+ kvStart: 0, preferGQASWA: false,+ forceGroupedVector: true)+ let wrongGQA = Attention.splitGeometry(headDim: 512, numQHeads: 16,+ numKVHeads: 4, seqLen: 1_024,+ kvStart: 0, preferGQASWA: false,+ forceGroupedVector: true)+ #expect(!wrongHeadDim.useFullGroupedVectorPartial)+ #expect(!wrongGQA.useFullGroupedVectorPartial)+ }++ /// The FP32 reference holds ~0.8 GB of `[Float]` at these lengths, which+ /// the 8 GB dev Mac cannot afford, so the long-context correctness pin is+ /// against the exact split kernel instead: same inputs, same combine, a+ /// different pass-1 reduction. Without this the kernel is only covered to+ /// 4,096 while it is measured at 65,536.+ @Test(arguments: [16_384, 65_536])+ func attentionFull_groupedVector_matchesExactKernelAtLongContext(seqLen: Int) throws {+ let ctx = try MetalContext()+ let kernel = try Attention(context: ctx)+ var rng = SeedTree(0x9E5).key("grouped-vec-long-\(seqLen)")+ let qCount = 16 * 512+ let kvCount = seqLen * 2 * 512+ let q = (0..<qCount).map { _ in Float16(rng.uniform(-0.5, 0.5)) }+ let k = (0..<kvCount).map { _ in Float16(rng.uniform(-0.5, 0.5)) }+ let v = (0..<kvCount).map { _ in Float16(rng.uniform(-0.5, 0.5)) }+ 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) else {+ Issue.record("Failed to allocate buffers"); return+ }+ func run(grouped: Bool) -> [Float] {+ guard let out = Fp16Buffer.make(ctx.device, count: qCount),+ let cb = ctx.queue.makeCommandBuffer() else { return [] }+ kernel.encodeFull(commandBuffer: cb, q: qBuf, k: kBuf, v: vBuf, out: out,+ headDim: 512, numQHeads: 16, numKVHeads: 2,+ seqLen: UInt32(seqLen), scale: 1.0,+ useGroupedVector: grouped)+ cb.commit(); cb.waitUntilCompleted()+ return Fp16Buffer.read(out, count: qCount)+ }+ let rel = RelError.compute(actual: run(grouped: true),+ reference: run(grouped: false))+ if rel >= Tolerance.fp16ChainedReduction {+ print("grouped-vec vs exact at seqLen=\(seqLen): rel=\(rel)")+ }+ #expect(rel < Tolerance.fp16ChainedReduction)+ }++ /// Every other case draws from U(-0.5, 0.5), which keeps scores near zero+ /// and barely exercises the online-softmax rescale. At production scale 1.0+ /// over 512 dims, real scores span a far wider range: here U(-3, 3) inputs+ /// give scores around +/-200, so `alpha = exp(m_run - m_new)` underflows to+ /// zero whenever a late key takes the running max and the accumulated+ /// output must be discarded rather than blended. A kernel that dropped the+ /// rescale entirely still passes the small-amplitude cases.+ @Test(arguments: [64, 1_024, 4_096])+ func attentionFull_groupedVector_wideScoreRange(seqLen: Int) throws {+ let ctx = try MetalContext()+ let kernel = try Attention(context: ctx)+ var rng = SeedTree(0x9E6).key("grouped-vec-wide-\(seqLen)")+ let qCount = 16 * 512+ let kvCount = seqLen * 2 * 512+ let q = (0..<qCount).map { _ in Float16(rng.uniform(-3.0, 3.0)) }+ let k = (0..<kvCount).map { _ in Float16(rng.uniform(-3.0, 3.0)) }+ let v = (0..<kvCount).map { _ in Float16(rng.uniform(-0.5, 0.5)) }+ 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) else {+ Issue.record("Failed to allocate buffers"); return+ }+ func run(grouped: Bool) -> [Float] {+ guard let out = Fp16Buffer.make(ctx.device, count: qCount),+ let cb = ctx.queue.makeCommandBuffer() else { return [] }+ kernel.encodeFull(commandBuffer: cb, q: qBuf, k: kBuf, v: vBuf, out: out,+ headDim: 512, numQHeads: 16, numKVHeads: 2,+ seqLen: UInt32(seqLen), scale: 1.0,+ useGroupedVector: grouped)+ cb.commit(); cb.waitUntilCompleted()+ return Fp16Buffer.read(out, count: qCount)+ }+ let reference = AttentionRef.apply(q: q.map(Float.init), k: k.map(Float.init),+ v: v.map(Float.init),+ headDim: 512, numQHeads: 16, numKVHeads: 2,+ seqLen: seqLen, window: nil, scale: 1.0)+ let grouped = run(grouped: true)+ let exact = run(grouped: false)+ let relGrouped = RelError.compute(actual: grouped, reference: reference)+ let relExact = RelError.compute(actual: exact, reference: reference)+ #expect(relGrouped < Tolerance.fp16ChainedReduction,+ "grouped rel=\(relGrouped) exact rel=\(relExact) at seqLen=\(seqLen)")+ }}diff --git a/Tests/TurboFieldfare/Core/Kernels/Attention/GroupedAttentionIdentityTests.swift b/Tests/TurboFieldfare/Core/Kernels/Attention/GroupedAttentionIdentityTests.swiftnew file mode 100644index 00000000..093ac1f2--- /dev/null+++ b/Tests/TurboFieldfare/Core/Kernels/Attention/GroupedAttentionIdentityTests.swift@@ -0,0 +1,163 @@+import Foundation+import Metal+import Testing+@testable import TurboFieldfare++@Suite(.serialized)+struct GroupedAttentionIdentityTests {+ // The old contiguous reduction passes tolerance checks while changing scores.+ // One-key chunks expose scores directly as m; longer chunks pin recurrence state.+ @Test(arguments: [1, 3, 16, 17, 33, 65, 257, 16_384, 65_536])+ func exactOrder(seqLen: Int) throws {+ try compare(seqLen: seqLen, pattern: "random")+ }++ @Test(arguments: ["cancellation", "lateMaximum", "equal", "wide"])+ func adversarial(pattern: String) throws {+ try compare(seqLen: 257, pattern: pattern)+ }++ // Fusing weight * V instead of old * alpha changes component 3 by one ULP.+ @Test func twoKeyRecurrence() throws {+ try compare(seqLen: 2, pattern: "random", chunkLength: 2)+ }++ @Test(arguments: [UInt64(0), 1, 0x12345678, UInt64.max])+ func variedSeeds(seed: UInt64) throws {+ try compare(seqLen: 257, pattern: "random", seed: seed)+ }++ private func compare(seqLen: Int, pattern: String, chunkLength: Int? = nil,+ seed: UInt64 = 0x9E571) throws {+ let ctx = try MetalContext()+ func buffer(_ count: Int, _ stride: Int) throws -> MTLBuffer {+ try #require(ctx.device.makeBuffer(length: count * stride, options: .storageModeShared))+ }+ let q = try buffer(8192, 2)+ let k = try buffer(seqLen * 1024, 2)+ let v = try buffer(seqLen * 1024, 2)+ var state = seed+ func random() -> Float16 {+ state = state &* 6364136223846793005 &+ 1442695040888963407+ return Float16(Float(Int32(truncatingIfNeeded: state >> 32)) / Float(Int32.max) * 0.5)+ }+ let qp = q.contents().bindMemory(to: Float16.self, capacity: 8192)+ for i in 0..<8192 {+ qp[i] = pattern == "wide" ? Float16(Float(random()) * 6)+ : (pattern == "random" ? random() : 1)+ }+ let kp = k.contents().bindMemory(to: Float16.self, capacity: seqLen * 1024)+ let vp = v.contents().bindMemory(to: Float16.self, capacity: seqLen * 1024)+ for i in 0..<(seqLen * 1024) {+ switch pattern {+ case "cancellation":+ kp[i] = [Float16(32), Float16(0.03125), Float16(-32), Float16(-0.015625)][i % 4]+ case "lateMaximum":+ // Every chunk sees a new maximum after weights have underflowed.+ kp[i] = Float16((i / 1024) % 17 == 16 ? 2 : -2)+ case "equal": kp[i] = 0.125+ case "wide": kp[i] = Float16(Float(random()) * 6)+ default: kp[i] = random()+ }+ vp[i] = random()+ }+ let constants = [+ MetalFunctionConstant(index: 60, value: .uint32(512)),+ MetalFunctionConstant(index: 61, value: .uint32(16)),+ MetalFunctionConstant(index: 62, value: .uint32(2)),+ MetalFunctionConstant(index: 63, value: .bool(true)),+ ]+ let exact = try ctx.pipeline("attention_decode_partial", constants: constants + [+ MetalFunctionConstant(index: 65, value: .uint32(16))+ ])+ let grouped = try ctx.pipeline("attention_decode_full_grouped_vec_partial", constants: constants)+ let combine = try ctx.pipeline("attention_decode_combine", constants: constants + [+ MetalFunctionConstant(index: 65, value: .uint32(16))+ ])+ func run(_ pso: MTLComputePipelineState, grouped: Bool) throws -> [MTLBuffer] {+ let outputs = try [buffer(256, 4), buffer(256, 4), buffer(256 * 512, 4), buffer(8192, 2)]+ let cb = try #require(ctx.queue.makeCommandBuffer())+ let enc = try #require(cb.makeComputeCommandEncoder())+ enc.setComputePipelineState(pso)+ for (index, b) in ([q, k, v] + Array(outputs.prefix(3))).enumerated() {+ enc.setBuffer(b, offset: 0, index: index)+ }+ for (offset, value) in [512, 16, 2, seqLen, 0, chunkLength ?? (seqLen + 15) / 16, 16].enumerated() {+ var value = UInt32(value)+ enc.setBytes(&value, length: 4, index: 6 + offset)+ }+ var scale: Float = 1+ enc.setBytes(&scale, length: 4, index: 13)+ enc.dispatchThreadgroups(MTLSize(width: grouped ? 32 : 256, height: 1, depth: 1),+ threadsPerThreadgroup: MTLSize(width: 256, height: 1, depth: 1))+ enc.endEncoding()+ let merge = try #require(cb.makeComputeCommandEncoder())+ merge.setComputePipelineState(combine)+ for (index, b) in outputs.enumerated() { merge.setBuffer(b, offset: 0, index: index) }+ var hd: UInt32 = 512, nc: UInt32 = 16+ merge.setBytes(&hd, length: 4, index: 4)+ merge.setBytes(&nc, length: 4, index: 5)+ merge.dispatchThreadgroups(MTLSize(width: 16, height: 1, depth: 1),+ threadsPerThreadgroup: MTLSize(width: 256, height: 1, depth: 1))+ merge.endEncoding()+ cb.commit()+ cb.waitUntilCompleted()+ if let error = cb.error { throw error }+ try #require(cb.status == .completed)+ return outputs+ }+ if seqLen >= 17, chunkLength == nil {+ let outputs = try [buffer(8192, 2), buffer(8192, 2)]+ for index in 0..<2 {+ let attention = try Attention(context: ctx)+ let cb = try #require(ctx.queue.makeCommandBuffer())+ attention.encodeFull(commandBuffer: cb, q: q, k: k, v: v, out: outputs[index],+ headDim: 512, numQHeads: 16, numKVHeads: 2,+ seqLen: UInt32(seqLen), scale: 1, useGroupedVector: index == 1)+ cb.commit()+ cb.waitUntilCompleted()+ if let error = cb.error { throw error }+ try #require(cb.status == .completed)+ }+ #expect(memcmp(outputs[0].contents(), outputs[1].contents(), outputs[0].length) == 0,+ "runtime output mismatch length=\(seqLen) pattern=\(pattern) seed=\(seed)")+ }+ let control = try run(exact, grouped: false)+ for repetition in 0..<2 {+ let candidate = try run(grouped, grouped: true)+ for index in 0..<4 {+ let names = ["m/score", "d", "o", "FP16"]+ let stride = index == 3 ? 2 : 4+ let a = control[index].contents()+ let b = candidate[index].contents()+ var changed = 0+ var first = -1+ var maxError: Float = 0+ for element in 0..<(control[index].length / stride) {+ let differs: Bool+ if stride == 4 {+ differs = a.load(fromByteOffset: element * 4, as: UInt32.self) != b.load(fromByteOffset: element * 4, as: UInt32.self)+ if differs {+ maxError = max(maxError, abs(a.load(fromByteOffset: element * 4, as: Float.self) - b.load(fromByteOffset: element * 4, as: Float.self)))+ }+ } else {+ differs = a.load(fromByteOffset: element * 2, as: UInt16.self) != b.load(fromByteOffset: element * 2, as: UInt16.self)+ if differs {+ maxError = max(maxError, abs(Float(a.load(fromByteOffset: element * 2, as: Float16.self)) - Float(b.load(fromByteOffset: element * 2, as: Float16.self))))+ }+ }+ if differs { changed += 1; if first < 0 { first = element } }+ }+ print("D1a length=\(seqLen) pattern=\(pattern) seed=\(seed) repetition=\(repetition) state=\(names[index]) changed=\(changed) first=\(first) maxAbs=\(maxError)")+ if first >= 0 {+ if stride == 4 {+ print("D1a first exact=\(a.load(fromByteOffset: first * 4, as: Float.self)) candidate=\(b.load(fromByteOffset: first * 4, as: Float.self)) exactBits=\(a.load(fromByteOffset: first * 4, as: UInt32.self)) candidateBits=\(b.load(fromByteOffset: first * 4, as: UInt32.self))")+ } else {+ print("D1a first exactBits=\(a.load(fromByteOffset: first * 2, as: UInt16.self)) candidateBits=\(b.load(fromByteOffset: first * 2, as: UInt16.self))")+ }+ }+ #expect(changed == 0, "length=\(seqLen) pattern=\(pattern) state=\(names[index]) first=\(first) changed=\(changed) maxAbs=\(maxError)")+ }+ }+ }+}diff --git a/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillRoPETests.swift b/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillRoPETests.swiftindex 58d301c3..03322c96 100644--- a/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillRoPETests.swift+++ b/Tests/TurboFieldfare/Core/Kernels/Prefill/PrefillRoPETests.swift@@ -152,4 +152,149 @@ import TurboFieldfareValidationSupportrowStride: rowStride,usedPerRow: used)}++ // ------------------------------------------------------------------------+ // Native-context positions — the decode/prefill half of the 256K numerics+ // gate. `max_position_embeddings` is 262,144, so the last row of the block+ // sits at 262,143 and its pair-0 angle is ~2.6e5 rad.+ //+ // `prefill_rope_apply_neox_pair` in `prefill.metal` and+ // `rope_apply_neox_pair` in `rope.metal` are the same expression —+ // `pow(theta, -2i/head_dim)`, then `sin`/`cos` on `position * freq` — so+ // both sides of this comparison run the same GPU math and the fp32 angle+ // quantization cancels. Anything left is a genuine prefill/decode split,+ // which is exactly what a conversation resumed from its record would hit:+ // the history is re-prefilled in blocks and the continuation decodes token+ // by token at the positions immediately after it. Production wiring:+ // `PrefillQKVEpilogue` drives `PrefillRoPE`; `RealForwardRunner` drives+ // `RoPE`'s `pow` variants (or the same expression inside the fused QKV+ // epilogue, which is the default). `Tolerance.fp16Reduction` applies.+ // ------------------------------------------------------------------------++ @Test(arguments: [4_096, 65_535, 131_071, 262_143])+ func blockDefaultNeoxMatchesScalarAtNativeMaximumPosition(endPosition: Int) throws {+ let rows = 4+ let heads = 8+ let headDim = 256+ let used = heads * headDim+ let rowStride = used + 37+ let startPosition = endPosition - rows + 1+ let theta: Float = 10_000.0+ let input = Self.makeBlock(rows: rows,+ rowStride: rowStride,+ usedPerRow: used,+ seed: UInt64(0x2565_0000 + endPosition),+ label: "prefill-rope-swa-native")++ let ctx = try MetalContext()+ let scalar = try RoPE(context: ctx)+ let block = try PrefillRoPE(context: ctx)+ guard let ref = Fp16Buffer.make(ctx.device, halves: input),+ let candidate = Fp16Buffer.make(ctx.device, halves: input) else {+ Issue.record("alloc failed")+ return+ }++ let cb = ctx.queue.makeCommandBuffer()!+ for row in 0..<rows {+ scalar.encodeDefaultNeox(commandBuffer: cb,+ data: ref,+ dataOffset: row * rowStride * MemoryLayout<Float16>.size,+ position: UInt32(startPosition + row),+ headDim: UInt32(headDim),+ numHeads: UInt32(heads),+ numTokens: 1,+ theta: theta)+ }+ block.encodeDefaultNeox(commandBuffer: cb,+ data: candidate,+ startPosition: UInt32(startPosition),+ queryCount: UInt32(rows),+ headDim: UInt32(headDim),+ numHeads: UInt32(heads),+ tokenStrideElements: UInt32(rowStride),+ theta: theta)+ cb.commit()+ cb.waitUntilCompleted()++ let reference = Fp16Buffer.read(ref, count: rows * rowStride)+ let actual = Fp16Buffer.read(candidate, count: rows * rowStride)+ let rel = RelError.compute(actual: actual, reference: reference)+ let maxAbs = RelError.maxAbsDiff(actual, reference)+ print("ROPE_PREFILL_PARITY pos=\(endPosition) shape=swa-hd256-h\(heads) rel=\(rel) maxAbs=\(maxAbs)")+ #expect(rel < Tolerance.fp16Reduction,+ "block SWA RoPE end=\(endPosition) rel=\(rel) maxAbs=\(maxAbs)")+ #expect(maxAbs <= 1e-3,+ "block SWA RoPE end=\(endPosition) maxAbs=\(maxAbs) rel=\(rel)")+ Self.assertPaddingUnchanged(candidate,+ original: input,+ rows: rows,+ rowStride: rowStride,+ usedPerRow: used)+ }++ @Test(arguments: [4_096, 65_535, 131_071, 262_143])+ func blockProportionalNeoxMatchesScalarAtNativeMaximumPosition(endPosition: Int) throws {+ let rows = 4+ let heads = 2+ let headDim = 512+ let rotatedPairs = 64+ let used = heads * headDim+ let rowStride = used + 19+ let startPosition = endPosition - rows + 1+ let theta: Float = 1_000_000.0+ let input = Self.makeBlock(rows: rows,+ rowStride: rowStride,+ usedPerRow: used,+ seed: UInt64(0x2566_0000 + endPosition),+ label: "prefill-rope-full-native")++ let ctx = try MetalContext()+ let scalar = try RoPE(context: ctx)+ let block = try PrefillRoPE(context: ctx)+ guard let ref = Fp16Buffer.make(ctx.device, halves: input),+ let candidate = Fp16Buffer.make(ctx.device, halves: input) else {+ Issue.record("alloc failed")+ return+ }++ let cb = ctx.queue.makeCommandBuffer()!+ for row in 0..<rows {+ scalar.encodeProportionalNeox(commandBuffer: cb,+ data: ref,+ dataOffset: row * rowStride * MemoryLayout<Float16>.size,+ position: UInt32(startPosition + row),+ headDim: UInt32(headDim),+ numHeads: UInt32(heads),+ rotatedPairs: UInt32(rotatedPairs),+ numTokens: 1,+ theta: theta)+ }+ block.encodeProportionalNeox(commandBuffer: cb,+ data: candidate,+ startPosition: UInt32(startPosition),+ queryCount: UInt32(rows),+ headDim: UInt32(headDim),+ numHeads: UInt32(heads),+ rotatedPairs: UInt32(rotatedPairs),+ tokenStrideElements: UInt32(rowStride),+ theta: theta)+ cb.commit()+ cb.waitUntilCompleted()++ let reference = Fp16Buffer.read(ref, count: rows * rowStride)+ let actual = Fp16Buffer.read(candidate, count: rows * rowStride)+ let rel = RelError.compute(actual: actual, reference: reference)+ let maxAbs = RelError.maxAbsDiff(actual, reference)+ print("ROPE_PREFILL_PARITY pos=\(endPosition) shape=full-hd512-h\(heads) rel=\(rel) maxAbs=\(maxAbs)")+ #expect(rel < Tolerance.fp16Reduction,+ "block full RoPE end=\(endPosition) rel=\(rel) maxAbs=\(maxAbs)")+ #expect(maxAbs <= 1e-3,+ "block full RoPE end=\(endPosition) maxAbs=\(maxAbs) rel=\(rel)")+ Self.assertPaddingUnchanged(candidate,+ original: input,+ rows: rows,+ rowStride: rowStride,+ usedPerRow: used)+ }}diff --git a/Tests/TurboFieldfare/Core/Runtime/Configuration/ContextAdmissionTests.swift b/Tests/TurboFieldfare/Core/Runtime/Configuration/ContextAdmissionTests.swiftnew file mode 100644index 00000000..85046eb0--- /dev/null+++ b/Tests/TurboFieldfare/Core/Runtime/Configuration/ContextAdmissionTests.swift@@ -0,0 +1,142 @@+import Testing+import Foundation+@testable import TurboFieldfare++/// Pins the admission arithmetic every context-picking surface shares. The+/// byte figures are the FP16 KV allocation the runtime actually makes — 25+/// ring-capped sliding layers plus 5 linear full layers — so a change to the+/// ring geometry or the layer mask fails here before it silently moves a menu+/// label, a server refusal and a CLI warning apart.+@Suite struct ContextAdmissionTests {++ @Test(arguments: [24, 32])+ func extraCacheSlotsAreChargedAtTheAdmissionBoundary(slots: Int) {+ let config = ArchConfig.gemma4_26B_A4B+ let baseline = ContextAdmission.minimumHostMemoryBytes(config: config, maxContext: 131_072)+ let page = Int(getpagesize())+ let slotBytes = ((3_358_720 + page - 1) / page) * page+ let expected = baseline + UInt64((slots - 16) * 30 * slotBytes)+ #expect(ContextAdmission.minimumHostMemoryBytes(config: config, maxContext: 131_072,+ expertCacheSlots: slots) == expected)+ #expect(ContextAdmission.availability(config: config, maxContext: 131_072,+ hostMemoryBytes: expected - 1, expertCacheSlots: slots)+ == .needsMemory(minimumHostBytes: expected))+ #expect(ContextAdmission.availability(config: config, maxContext: 131_072,+ hostMemoryBytes: expected, expertCacheSlots: slots) == .available)+ #expect(ContextAdmission.availability(config: config, maxContext: 131_072,+ hostMemoryBytes: 8 << 30, expertCacheSlots: slots)+ == .needsMemory(minimumHostBytes: expected))+ }++ @Test func smallerCacheDoesNotDiscountTheMeasuredRuntimeAllowance() {+ #expect(ContextAdmission.projectedFootprintBytes(config: config, maxContext: 131_072,+ expertCacheSlots: 8)+ == ContextAdmission.projectedFootprintBytes(config: config, maxContext: 131_072))+ }+++ private let config = ArchConfig.gemma4_26B_A4B+ private let eightGigabyteHost: UInt64 = 8_589_934_592+ private let sixteenGigabyteHost: UInt64 = 17_179_869_184++ @Test func fp16KVBytesMatchesTheRuntimeAllocationAtEverySize() {+ let expected: [(context: Int, bytes: UInt64)] = [+ (4_096, 350_945_280),+ (8_192, 434_831_360),+ (16_384, 602_603_520),+ (32_768, 938_147_840),+ (65_536, 1_609_236_480),+ (131_072, 2_951_413_760),+ (262_144, 5_635_768_320),+ ]+ for row in expected {+ #expect(ContextAdmission.fp16KVBytes(config: config, maxContext: row.context)+ == row.bytes,+ "context \(row.context)")+ }+ }++ /// Only the five full-attention layers grow with the context; the sliding+ /// ring is fixed. 20,480 B per token across those five is the whole slope.+ @Test func onlyFullAttentionLayersGrowWithContext() {+ let small = ContextAdmission.fp16KVBytes(config: config, maxContext: 8_192)+ let large = ContextAdmission.fp16KVBytes(config: config, maxContext: 16_384)+ #expect(large - small == UInt64((16_384 - 8_192) * 20_480))+ }++ @Test func productionSlidingRingRowsMatchTheRunnersChunkFloor() {+ #expect(ContextAdmission.productionSlidingRingRows(config: config, maxContext: 8_192)+ == 1_304)+ // A context below the ring size caps the ring at the context.+ #expect(ContextAdmission.productionSlidingRingRows(config: config, maxContext: 1_024)+ == 1_024)+ }++ @Test func eightGigabyteHostBacks128KButNot256K() {+ #expect(ContextAdmission.availability(config: config,+ maxContext: 131_072,+ hostMemoryBytes: eightGigabyteHost)+ == .available)+ #expect(ContextAdmission.availability(config: config,+ maxContext: 262_144,+ hostMemoryBytes: eightGigabyteHost)+ == .needsMemory(minimumHostBytes: 11_004_477_440))+ }++ @Test func sixteenGigabyteHostBacksEverySize() {+ for context in [4_096, 8_192, 16_384, 32_768, 65_536, 131_072, 262_144] {+ #expect(ContextAdmission.availability(config: config,+ maxContext: context,+ hostMemoryBytes: sixteenGigabyteHost)+ == .available,+ "context \(context)")+ }+ }++ /// The rule admits at exactly the minimum, not one byte above it: an+ /// off-by-one here would hide 128K from every 8 GB Mac, whose 270 MB of+ /// margin is the whole question step 9 of the plan measures.+ @Test func admissionBoundaryIsInclusive() {+ let minimum = ContextAdmission.minimumHostMemoryBytes(config: config,+ maxContext: 131_072)+ #expect(ContextAdmission.availability(config: config,+ maxContext: 131_072,+ hostMemoryBytes: minimum - 1)+ == .needsMemory(minimumHostBytes: minimum))+ #expect(ContextAdmission.availability(config: config,+ maxContext: 131_072,+ hostMemoryBytes: minimum)+ == .available)+ }++ @Test func projectedFootprintIsKVPlusTheMeasuredNonKVRuntime() {+ let projected = ContextAdmission.projectedFootprintBytes(config: config,+ maxContext: 262_144)+ #expect(projected == 5_635_768_320 + ContextAdmission.nonKVRuntimeFootprintBytes)+ #expect(ContextAdmission.minimumHostMemoryBytes(config: config, maxContext: 262_144)+ == projected + ContextAdmission.hostReserveBytes)+ }++ @Test func needDescriptionNamesBothTheRequirementAndTheHost() {+ let message = ContextAdmission.needDescription(config: config,+ maxContext: 262_144,+ hostMemoryBytes: eightGigabyteHost)+ #expect(message.contains("16 GB"))+ #expect(message.contains("8 GB"))+ #expect(message.contains("262,144"))+ }++ /// 128K needs 8,320,122,880 bytes, which an 8 GB Mac has. Reporting that+ /// as "needs 16 GB" while `availability` calls it available would put the+ /// caption and the menu in direct contradiction.+ @Test func needDescriptionRoundsToASizeThatActuallyBacksTheContext() {+ let message = ContextAdmission.needDescription(config: config,+ maxContext: 131_072,+ hostMemoryBytes: eightGigabyteHost)+ #expect(message.contains("needs 8 GB"))+ }++ @Test func contextCeilingComesFromTheCheckpoint() {+ #expect(config.maxPositionEmbeddings == 262_144)+ }+}diff --git a/Tests/TurboFieldfare/Core/Runtime/KVCache/KVCacheManagerTests.swift b/Tests/TurboFieldfare/Core/Runtime/KVCache/KVCacheManagerTests.swiftindex 7d2343ae..9c8af954 100644--- a/Tests/TurboFieldfare/Core/Runtime/KVCache/KVCacheManagerTests.swift+++ b/Tests/TurboFieldfare/Core/Runtime/KVCache/KVCacheManagerTests.swift@@ -11,6 +11,7 @@ import Metalprivate func makeManager(maxContext: Int,fp16RingEnabled: Bool = false,+ maxPrefillChunkTokens: Int = 128,fp16RingCapacityOverride: Int? = nil) throws -> (MetalContext, KVCacheManager) {let ctx = try MetalContext()let kv = try KVCacheManager(device: ctx.device,@@ -18,11 +19,16 @@ import MetalmaxContext: maxContext,fp16RingEnabled: fp16RingEnabled,slidingWindow: config.slidingWindow,- maxPrefillChunkTokens: 128,+ maxPrefillChunkTokens: maxPrefillChunkTokens,fp16RingCapacityOverride: fp16RingCapacityOverride)return (ctx, kv)}+ /// The chunk floor `RealForwardRunner` applies in production, which is what+ /// makes the ring 1,304 rows rather than the 1,152 a bare 128-token chunk+ /// would give.+ private var productionChunkTokens: Int { VisionConfig().maximumPooledTokens }+@Test func strideAndBufferSizes_matchConfig() throws {let (_, kv) = try makeManager(maxContext: 128)@@ -184,6 +190,37 @@ import Metal#expect(kv.position == 2)}+ /// The ceiling is the checkpoint's `max_position_embeddings`, and it is+ /// checked before the first `makeBuffer`: at 262,145 the allocation loop+ /// would ask for 5.4 GiB of full-layer KV for positions the model has no+ /// RoPE frequencies for.+ @Test func contextAboveModelMaximumIsRefusedBeforeAllocation() throws {+ do {+ _ = try makeManager(maxContext: 262_145, fp16RingEnabled: true)+ Issue.record("262,145 was accepted above the model maximum 262,144")+ } catch let error as ModelError {+ #expect(error == .contextExceedsModel(requested: 262_145, maximum: 262_144))+ #expect(error.description.contains("262145"))+ #expect(error.description.contains("262144"))+ }+ }++ /// The model maximum itself constructs. Gated on host memory: the full+ /// layers reserve 5.4 GiB of address space, which is not something CI or+ /// the 8 GB dev Mac should be asked for.+ @Test func modelMaximumContextAllocates() throws {+ guard ProcessInfo.processInfo.physicalMemory >= 16 << 30 else { return }+ let (_, kv) = try makeManager(maxContext: 262_144,+ fp16RingEnabled: true,+ maxPrefillChunkTokens: productionChunkTokens)+ #expect(kv.capacity(layer: 5) == 262_144)+ #expect(kv.capacity(layer: 0)+ == ContextAdmission.productionSlidingRingRows(config: config,+ maxContext: 262_144))+ #expect(kv.capacity(layer: 0) == 1_304)+ #expect(kv.bufferLength(layer: 5) == 262_144 * 2_048)+ }+@Test func reset_clearsPosition() throws {let (_, kv) = try makeManager(maxContext: 128)for _ in 0..<100 { kv.advance() }@@ -196,4 +233,5 @@ import Metal#expect(kv.position == 1)}+}diff --git a/Tests/TurboFieldfareApp/Core/Configuration/AppContextLengthOptionTests.swift b/Tests/TurboFieldfareApp/Core/Configuration/AppContextLengthOptionTests.swiftindex 37dc3fe2..9088f1c2 100644--- a/Tests/TurboFieldfareApp/Core/Configuration/AppContextLengthOptionTests.swift+++ b/Tests/TurboFieldfareApp/Core/Configuration/AppContextLengthOptionTests.swift@@ -1,10 +1,21 @@import Testing+import TurboFieldfare@testable import TurboFieldfareAppCore@Suite struct AppContextLengthOptionTests {+ private let eightGigabyteHost: UInt64 = 8_589_934_592+ private let sixteenGigabyteHost: UInt64 = 17_179_869_184+@Test func optionsUseSupportedContextLengthsInAscendingOrder() {#expect(AppContextLengthOption.allCases.map(\.tokens)- == [4_096, 8_192, 16_384, 32_768, 65_536])+ == [4_096, 8_192, 16_384, 32_768, 65_536, 131_072, 262_144])+ }++ /// The ceiling is the checkpoint's `max_position_embeddings`, so the menu+ /// cannot offer a position the model was never trained to address.+ @Test func thelargestOptionIsTheModelCeiling() {+ #expect(AppContextLengthOption.allCases.last?.tokens+ == ArchConfig.gemma4_26B_A4B.maxPositionEmbeddings)}@Test func optionsReportProductionFP16KVAllocation() {@@ -12,19 +23,86 @@ import Testing$0.fp16KVBytes / 1_048_576}// 29 MiB above the older figures at every size, because the sliding- // ring is sized for the widest prefill chunk the runtime may see - the- // pooled image-token count - and the estimate had used the smaller text+ // ring is sized for the widest prefill chunk the runtime may see — the+ // pooled image-token count — and the estimate had used the smaller text// chunk. The menu deltas are unchanged: every option grew equally.- #expect(mebibytes == [334, 414, 574, 894, 1_534])- // Deltas are relative to the default, which is 8K as of 2026-08-17 so- // that an image and its prompt fit without the user changing anything.- // 334 - 414 = -80 MiB, 574 - 414 = +160 MiB, and so on.+ #expect(mebibytes == [334, 414, 574, 894, 1_534, 2_814, 5_374])#expect(AppContextLengthOption.allCases.map(\.menuLabel) == ["4K, -85 MB","8K, Default","16K, +170 MB",- "32K, +500 MB",+ "32K, +505 MB","64K, +1.17 GB",+ "128K, +2.52 GB",+ "256K, +5.20 GB",])}++ /// The option is only a face on `ContextAdmission`; if it ever computed its+ /// own figures the menu label and the loader's refusal would drift apart.+ @Test func everyFigureComesFromTheSharedAdmissionRule() {+ for option in AppContextLengthOption.allCases {+ let config = ArchConfig.gemma4_26B_A4B+ #expect(option.fp16KVBytes+ == ContextAdmission.fp16KVBytes(config: config, maxContext: option.tokens))+ #expect(option.projectedFootprintBytes+ == ContextAdmission.projectedFootprintBytes(config: config,+ maxContext: option.tokens))+ #expect(option.minimumHostMemoryBytes+ == ContextAdmission.minimumHostMemoryBytes(config: config,+ maxContext: option.tokens))+ }+ }++ @Test func aneightGigabyteMacIsOfferedEverythingUpTo128K() {+ #expect(AppContextLengthOption.available(on: eightGigabyteHost).map(\.tokens)+ == [4_096, 8_192, 16_384, 32_768, 65_536, 131_072])+ #expect(AppContextLengthOption.twoFiftySixK.availability(+ hostMemoryBytes: eightGigabyteHost)+ == .needsMemory(minimumHostBytes: 11_004_477_440))+ #expect(AppContextLengthOption.largestAvailable(on: eightGigabyteHost)+ == .oneTwentyEightK)+ }++ @Test func asixteenGigabyteMacIsOfferedEverySize() {+ #expect(AppContextLengthOption.available(on: sixteenGigabyteHost)+ == AppContextLengthOption.allCases)+ #expect(AppContextLengthOption.largestAvailable(on: sixteenGigabyteHost)+ == .twoFiftySixK)+ }++ /// The rule admits at exactly the minimum. One byte below it 128K has to+ /// disappear from the menu, or an 8 GB Mac whose margin the plan puts at+ /// 270 MB would be offered a context the loader then refuses.+ @Test func themenuBoundaryIsTheAdmissionBoundary() {+ let minimum = AppContextLengthOption.oneTwentyEightK.minimumHostMemoryBytes+ #expect(AppContextLengthOption.available(on: minimum - 1).map(\.tokens)+ == [4_096, 8_192, 16_384, 32_768, 65_536])+ #expect(AppContextLengthOption.available(on: minimum).map(\.tokens)+ == [4_096, 8_192, 16_384, 32_768, 65_536, 131_072])+ #expect(AppContextLengthOption.largestAvailable(on: minimum - 1) == .sixtyFourK)+ }++ @Test func theneedDescriptionNamesTheRequirementAndTheHost() {+ let message = AppContextLengthOption.twoFiftySixK+ .needDescription(hostMemoryBytes: eightGigabyteHost)+ #expect(message.contains("262,144"))+ #expect(message.contains("16 GB"))+ #expect(message.contains("8 GB"))+ }++ @Test func defaultOptionMatchesRuntimeDefault() {+ #expect(AppContextLengthOption.defaultOption.tokens+ == 8_192)+ #expect(MacAppSettings().contextTokens+ == AppContextLengthOption.defaultOption.tokens)+ #expect(AppContextLengthOption.defaultOption == .eightK)+ // Every Mac this app runs on has at least 8 GB, so the shipped default+ // is never one of the rows admission hides.+ for host in [eightGigabyteHost, sixteenGigabyteHost] {+ #expect(AppContextLengthOption.available(on: host)+ .contains(AppContextLengthOption.defaultOption),+ "the default context was hidden on a \(host)-byte host")+ }+ }}diff --git a/Tests/TurboFieldfareApp/Core/Configuration/MacAppSettingsTests.swift b/Tests/TurboFieldfareApp/Core/Configuration/MacAppSettingsTests.swiftindex 1881747a..f939d244 100644--- a/Tests/TurboFieldfareApp/Core/Configuration/MacAppSettingsTests.swift+++ b/Tests/TurboFieldfareApp/Core/Configuration/MacAppSettingsTests.swift@@ -225,6 +225,86 @@ import Testing"if 4K ever becomes the default, this test is asking the wrong question")}+ /// Why version 3 exists at all.+ ///+ /// 128K and 256K are new options. An older build's `isValid` checks the+ /// stored context against the options *it* knows, so it rejects 262,144 —+ /// and `loadOrCreate` deletes the file on that rejection, taking every+ /// other setting with it. Stamping the file 3 makes that build take the+ /// newer-version branch instead, which returns defaults and leaves the file+ /// alone. The migration is version-only: a v2 file keeps the context its+ /// owner chose.+ @Test func versionTwoMigrationKeepsContext() 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)+ let stored = MacAppSettings(+ version: 2,+ contextTokens: 4_096,+ expertCacheSlots: 24,+ temperature: 0.4)+ try JSONEncoder().encode(stored).write(to: fileURL)++ let settings = MacAppSettingsFileStore.loadOrCreate(forModelDirectory: model)+ let persisted = try JSONDecoder().decode(+ MacAppSettings.self, from: Data(contentsOf: fileURL))++ #expect(settings.version == 3)+ #expect(settings.contextTokens == 4_096,+ "the version bump rewrote a deliberately chosen context")+ #expect(settings.expertCacheSlots == 24)+ #expect(settings.temperature == 0.4)+ #expect(persisted == settings)+ }++ /// The hazard version 3 closes, seen from the other side: a file from a+ /// build newer than this one carries a context this build's `isValid`+ /// cannot admit. It must survive untouched rather than be deleted.+ @Test func anewerFileWithAnUnknownContextIsLeftOnDisk() 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)+ let future = """+ {+ "version": \(MacAppSettings.currentVersion + 1),+ "contextTokens": 999999,+ "expertCacheSlots": 16,+ "temperature": 0.2,+ "topKEnabled": true,+ "topK": 64,+ "topPEnabled": true,+ "topP": 0.95,+ "prefillEnabled": true+ }+ """+ try Data(future.utf8).write(to: fileURL)++ let settings = MacAppSettingsFileStore.loadOrCreate(forModelDirectory: model)++ #expect(settings == MacAppSettings(),+ "an unknown version should be run on defaults, not adopted")+ #expect(try String(contentsOf: fileURL, encoding: .utf8) == future,+ "a newer build's settings file was rewritten or deleted")+ }++ /// The new ceiling round-trips at this version: written, validated, read+ /// back and still 262,144.+ @Test func aversionThreeFileKeepsA256KContext() throws {+ let root = try makeTemporaryRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let model = root.appendingPathComponent("gemma4.gturbo", isDirectory: true)+ let stored = MacAppSettings(contextTokens: 262_144)+ #expect(stored.version == 3)++ try MacAppSettingsFileStore.save(stored, forModelDirectory: model)+ let settings = MacAppSettingsFileStore.loadOrCreate(forModelDirectory: model)++ #expect(settings == stored)+ #expect(settings.contextTokens == 262_144)+ }+/// A v1 file at any other context is restamped untouched too — the version/// bump must not be a licence to edit values.@Test func versionOneMigrationOnlyRestampsTheVersion() throws {@@ -417,11 +497,11 @@ import Testinglet modelDirectory = root.appendingPathComponent("gemma4.gturbo", isDirectory: true)let fileURL = MacAppSettingsFileStore.fileURL(forModelDirectory: modelDirectory)- // A plausible version 3: `topP` became `topProbability`. Everything else- // this build knows is still present and still valid.+ // A plausible next version: `topP` became `topProbability`. Everything+ // else this build knows is still present and still valid.let newer = """{- "version": 3,+ "version": \(MacAppSettings.currentVersion + 1),"contextTokens": 8192,"expertCacheSlots": 16,"temperature": 0.2,diff --git a/Tests/TurboFieldfareApp/Core/Inference/AppGenerationRequestTests.swift b/Tests/TurboFieldfareApp/Core/Inference/AppGenerationRequestTests.swiftindex c66f8495..74a331fc 100644--- a/Tests/TurboFieldfareApp/Core/Inference/AppGenerationRequestTests.swift+++ b/Tests/TurboFieldfareApp/Core/Inference/AppGenerationRequestTests.swift@@ -186,6 +186,30 @@ import TurboFieldfare}}+ /// The model's `max_position_embeddings`. A context above it is not a+ /// memory question — no machine makes a position the model was never+ /// trained to address valid — so it is refused here rather than surfacing+ /// as a KV allocation the runtime throws on.+ @Test func acontextAboveTheModelCeilingIsRejectedNamingBothNumbers() throws {+ let ceiling = ArchConfig.gemma4_26B_A4B.maxPositionEmbeddings+ #expect(ceiling == 262_144)++ try AppGenerationRequest(+ modelDirectory: existingDirectory, prompt: "hello",+ maxContextTokens: ceiling).validate()++ do {+ try AppGenerationRequest(+ modelDirectory: existingDirectory, prompt: "hello",+ maxContextTokens: ceiling + 1).validate()+ Issue.record("a context above the model ceiling was accepted")+ } catch let error as AppInferenceError {+ let message = "\(error)"+ #expect(message.contains("262145"))+ #expect(message.contains("262144"))+ }+ }+@Test func invalidContextCannotOverflowImageCapacity() {let request = AppGenerationRequest(modelDirectory: existingDirectory,diff --git a/Tests/TurboFieldfareApp/Core/State/AppImageCapacityTests.swift b/Tests/TurboFieldfareApp/Core/State/AppImageCapacityTests.swiftindex b0713fd3..982f763a 100644--- a/Tests/TurboFieldfareApp/Core/State/AppImageCapacityTests.swift+++ b/Tests/TurboFieldfareApp/Core/State/AppImageCapacityTests.swift@@ -61,6 +61,41 @@ import TurboFieldfare}}+ /// The context-derived budget is unbounded in the context: at 262,144+ /// tokens the arithmetic alone offers about 930 images in one message. The+ /// absolute per-turn cap is what stops that, and it binds only once the+ /// context is large enough for it to.+ @Test func theperTurnCapBoundsWhatALargeContextWouldOffer() {+ #expect(VisionImageTokenBudget.capacity(+ maxContext: 262_144, reservedTextTokens: 0)+ == VisionImageTokenBudget.maximumAttachmentsPerTurn)+ #expect(VisionImageTokenBudget.maximumAttachmentsPerTurn == 32)++ // One token below where the cap starts binding, the context is still+ // the thing that decides.+ let atTheCap = VisionImageTokenBudget.maximumTokensPerImage+ * VisionImageTokenBudget.maximumAttachmentsPerTurn+ #expect(VisionImageTokenBudget.capacity(+ maxContext: atTheCap, reservedTextTokens: 0) == 32)+ #expect(VisionImageTokenBudget.capacity(+ maxContext: atTheCap - 1, reservedTextTokens: 0) == 31)+ }++ @MainActor+ @Test func thecapReachesTheComposerMessageInsteadOfAdviceToRaiseTheContext() {+ let capped = AppModel.imageCapacityMessage(+ capacity: VisionImageTokenBudget.maximumAttachmentsPerTurn,+ context: 262_144)+ #expect(capped.contains("32"))+ #expect(!capped.contains("Raise"),+ "raising the context cannot lift the per-turn cap")+ // Below the cap the context really is the reason, and saying so is how+ // the user knows what to change.+ let contextBound = AppModel.imageCapacityMessage(capacity: 10, context: 4_096)+ #expect(contextBound.contains("4K"))+ #expect(contextBound.contains("Raise"))+ }+@Test func unknownConversationPositionHasNoImageCapacity() {#expect(AppModel.imageAttachmentCapacity(maxContextTokens: AppContextLengthOption.fourK.tokens,diff --git a/Tests/TurboFieldfareApp/Core/State/AppModelTests.swift b/Tests/TurboFieldfareApp/Core/State/AppModelTests.swiftindex c671eca9..172f4027 100644--- a/Tests/TurboFieldfareApp/Core/State/AppModelTests.swift+++ b/Tests/TurboFieldfareApp/Core/State/AppModelTests.swift@@ -32,6 +32,61 @@ import Testing}@Suite struct AppModelTests {++ @MainActor @Test func cacheSelectionClampsContextAndPersistsBothSettings() throws {+ let root = try makeSettingsRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let directory = root.appendingPathComponent("model.gturbo")+ let model = AppModel(modelDirectory: directory, client: MockLifecycleInferenceClient(),+ settingsPersistenceEnabled: true, hostMemoryBytes: 8 << 30)+ model.setMaxContextTokens(131_072)+ model.setExpertCacheSlots(24)+ #expect(model.maxContextTokens == 65_536)+ #expect(model.contextClampNotice?.contains("131,072") == true)+ #expect(!model.contextOptions.contains(.oneTwentyEightK))+ let saved = MacAppSettingsFileStore.loadOrCreate(forModelDirectory: directory)+ #expect(saved.contextTokens == 65_536)+ #expect(saved.expertCacheSlots == 24)+ model.setExpertCacheSlots(16)+ #expect(model.contextOptions.contains(.oneTwentyEightK))+ #expect(model.maxContextTokens == 65_536)+ }++ @MainActor @Test func storedCacheGrowthClampsOnLaunchAndModelChange() throws {+ let root = try makeSettingsRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let first = root.appendingPathComponent("first/model.gturbo")+ let second = root.appendingPathComponent("second/model.gturbo")+ for directory in [first, second] {+ try MacAppSettingsFileStore.save(MacAppSettings(contextTokens: 131_072,+ expertCacheSlots: 24),+ forModelDirectory: directory)+ }+ let model = AppModel(modelDirectory: first, client: MockLifecycleInferenceClient(),+ settingsPersistenceEnabled: true, hostMemoryBytes: 8 << 30)+ #expect(model.maxContextTokens == 65_536)+ #expect(model.contextClampNotice != nil)+ model.setModelURL(second)+ #expect(model.maxContextTokens == 65_536)+ #expect(model.contextClampNotice != nil)+ }++ @MainActor @Test func loadRefusesCacheGrowthThatBypassedThePicker() throws {+ let directory = try makeCompleteModelInstall("cache-context-refusal")+ defer { try? FileManager.default.removeItem(at: directory) }+ let client = MockLifecycleInferenceClient()+ let model = AppModel(modelDirectory: directory, client: client, hostMemoryBytes: 8 << 30)+ model.setMaxContextTokens(131_072)+ model.runtimeOptions.expertCacheSlots = 32+ model.loadModel()+ guard case .failed(let error) = model.loadState else {+ Issue.record("unbacked cache/context combination reached loading")+ return+ }+ #expect("\(error)".contains("16 GB"))+ #expect(client.ensureLoadedCallCount() == 0)+ }+@MainActor@Test func defaultsUseSampledRequest() throws {let model = AppModel()@@ -413,6 +468,135 @@ import Testing#expect(!model.canRun)}+ /// A settings file can carry a context this Mac cannot back — written on a+ /// larger machine, or on a build whose admission rule was looser. Opening+ /// the app on it would put every load into `.failed` with no way back+ /// except a menu the user has to guess at, so it is clamped and said.+ @MainActor+ @Test func unavailableStoredContextIsClampedWithNotice() throws {+ let root = try makeSettingsRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let modelDirectory = root.appendingPathComponent("gemma4.gturbo", isDirectory: true)+ try MacAppSettingsFileStore.save(MacAppSettings(contextTokens: 262_144),+ forModelDirectory: modelDirectory)++ let model = AppModel(modelDirectory: modelDirectory,+ client: MockLifecycleInferenceClient(),+ settingsPersistenceEnabled: true,+ hostMemoryBytes: 8_589_934_592)++ #expect(model.maxContextTokens == 131_072)+ let notice = try #require(model.contextClampNotice,+ "the context was changed without saying so")+ #expect(notice.contains("262,144"))+ #expect(notice.contains("16 GB"))+ #expect(notice.contains("128K"))++ model.setMaxContextTokens(model.maxContextTokens)+ #expect(model.contextClampNotice == notice)++ // Context edits must go through the history-aware setter after the merge;+ // direct assignment clears the notice but loses persistence and redraw.+ model.setMaxContextTokens(65_536)+ #expect(model.contextClampNotice == nil)+ #expect(MacAppSettingsFileStore.loadOrCreate(+ forModelDirectory: modelDirectory).contextTokens == 65_536)+ }++ /// The same clamp on the settings-apply path, which `init` does not cover:+ /// switching model directories adopts that directory's settings, and one+ /// of them can carry a context this Mac cannot back. The notice also has+ /// to survive being set — assigning the context clears it, so an+ /// assignment made after the notice would wipe it.+ @MainActor+ @Test func achangedModelDirectoryClampsItsStoredContextToo() throws {+ let root = try makeSettingsRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let first = root.appendingPathComponent("first/model.gturbo", isDirectory: true)+ let second = root.appendingPathComponent("second/model.gturbo", isDirectory: true)+ try MacAppSettingsFileStore.save(MacAppSettings(contextTokens: 8_192),+ forModelDirectory: first)+ try MacAppSettingsFileStore.save(MacAppSettings(contextTokens: 262_144),+ forModelDirectory: second)+ let model = AppModel(modelDirectory: first,+ client: MockLifecycleInferenceClient(),+ settingsPersistenceEnabled: true,+ hostMemoryBytes: 8_589_934_592)+ try #require(model.contextClampNotice == nil)++ model.setModelURL(second)++ #expect(model.maxContextTokens == 131_072)+ #expect(model.contextClampNotice?.contains("262,144") == true,+ "the clamp on the settings-apply path said nothing")+ }++ @MainActor+ @Test func availableStoredContextIsKept() throws {+ let root = try makeSettingsRoot()+ defer { try? FileManager.default.removeItem(at: root) }+ let modelDirectory = root.appendingPathComponent("gemma4.gturbo", isDirectory: true)+ try MacAppSettingsFileStore.save(MacAppSettings(contextTokens: 262_144),+ forModelDirectory: modelDirectory)++ let model = AppModel(modelDirectory: modelDirectory,+ client: MockLifecycleInferenceClient(),+ settingsPersistenceEnabled: true,+ hostMemoryBytes: 25_769_803_776)++ #expect(model.maxContextTokens == 262_144)+ #expect(model.contextClampNotice == nil)+ }++ /// The refusal has to happen before the load state moves, or the app sends+ /// the decode service a context that gets the service killed part-way+ /// through — which reaches the user as a lost connection, not as a reason.+ @MainActor+ @Test func loadRefusesUnavailableContextBeforeLoading() async throws {+ let directory = try makeCompleteModelInstall("context-refusal")+ defer { try? FileManager.default.removeItem(at: directory) }+ let client = MockLifecycleInferenceClient()+ let model = AppModel(modelDirectory: directory,+ client: client,+ hostMemoryBytes: 8_589_934_592)+ model.setMaxContextTokens(262_144)+ try #require(model.canLoadModel)++ model.loadModel()++ guard case .failed(let error) = model.loadState else {+ Issue.record("an unbacked context was allowed to start loading")+ return+ }+ #expect("\(error)".contains("262,144"))+ #expect(client.ensureLoadedCallCount() == 0,+ "the loader was reached with a context this host cannot back")+ #expect(!model.loadState.isLoading)+ }++ @Test func contextOptionsNoteNamesHiddenSizes() throws {+ let note = try #require(+ AppModel.contextOptionsNote(hostMemoryBytes: 8_589_934_592))+ #expect(note.contains("262,144"))+ #expect(note.contains("16 GB"))+ #expect(note.contains("8 GB"))+ // 128K is offered on this host, so it is not something to explain away.+ #expect(!note.contains("131,072"))+ }++ @Test func contextOptionsNoteIsAbsentWhenEverySizeIsOffered() {+ #expect(AppModel.contextOptionsNote(hostMemoryBytes: 25_769_803_776) == nil)+ }++ private func makeSettingsRoot() throws -> URL {+ let root = FileManager.default.temporaryDirectory+ .appendingPathComponent("AppModelContext-\(UUID().uuidString)",+ isDirectory: true)+ try FileManager.default.createDirectory(at: root,+ withIntermediateDirectories: true)+ return root+ }+@MainActorprivate func readyModel(client: MockInferenceClient) -> AppModel {let model = AppModel(client: client)diff --git a/Tests/TurboFieldfareApp/MacPresentation/ConversationContextPresentationTests.swift b/Tests/TurboFieldfareApp/MacPresentation/ConversationContextPresentationTests.swiftindex 4ba46bc2..3fced02b 100644--- a/Tests/TurboFieldfareApp/MacPresentation/ConversationContextPresentationTests.swift+++ b/Tests/TurboFieldfareApp/MacPresentation/ConversationContextPresentationTests.swift@@ -12,6 +12,17 @@ import Testing== "\u{2014}", "an unknown window must not read as a full one")}+ /// The K here is decimal, deliberately: 65,536 has always printed as "66K"+ /// in this gauge, so the model's native ceiling prints as "262K" rather+ /// than the "256K" the Context menu labels it with. Changing it would move+ /// every existing reading, so it is pinned instead.+ @Test func thefullNativeWindowReadsInTheSameDecimalKAsEveryOtherSize() {+ #expect(ConversationContextPresentation.gauge(kvTokens: 65_536, maxContext: 65_536)+ == "66K/66K")+ #expect(ConversationContextPresentation.gauge(kvTokens: 262_144, maxContext: 262_144)+ == "262K/262K")+ }+/// The committed count only moves when a turn finishes, so a gauge reading/// it sits still through the whole run and then jumps. These pin the live/// figure through each phase of a turn.diff --git a/Tests/TurboFieldfareDecodeService/DecodeLoadAdmissionTests.swift b/Tests/TurboFieldfareDecodeService/DecodeLoadAdmissionTests.swiftnew file mode 100644index 00000000..859c0cc2--- /dev/null+++ b/Tests/TurboFieldfareDecodeService/DecodeLoadAdmissionTests.swift@@ -0,0 +1,83 @@+import Foundation+import Testing+import TurboFieldfare+@testable import TurboFieldfareDecodeService++/// The service is the process the system kills. A 262,144-token KV is charged+/// in full the moment a command buffer binds it — one full-attention layer over+/// sixteen rows already costs 1,085 MiB — so a load this host cannot back does+/// not fail slowly and report itself: it disappears mid-load, and the app can+/// only show a lost connection. Every case here is a load that must be answered+/// before the runner is built.+@Suite struct DecodeLoadAdmissionTests {++ @Test(arguments: [24, 32])+ func cacheGrowthRejects128KOnEightGB(slots: Int) throws {+ let refusal = try #require(DecodeLoadAdmission.refusal(maxContextTokens: 131_072,+ hostMemoryBytes: 8 << 30, environment: [:], expertCacheSlots: slots))+ #expect(refusal.contains("16 GB"))+ #expect(DecodeLoadAdmission.refusal(maxContextTokens: 131_072,+ hostMemoryBytes: 16 << 30, environment: [:], expertCacheSlots: slots) == nil)+ #expect(DecodeLoadAdmission.refusal(maxContextTokens: 131_072,+ hostMemoryBytes: 8 << 30,+ environment: [DecodeLoadAdmission.overrideEnvironmentKey: "1"],+ expertCacheSlots: slots) == nil)+ }++ private let eightGigabyteHost: UInt64 = 8_589_934_592+ private let twentyFourGigabyteHost: UInt64 = 25_769_803_776++ @Test func acontextThisHostCanBackIsAdmitted() {+ #expect(DecodeLoadAdmission.refusal(maxContextTokens: 8_192,+ hostMemoryBytes: eightGigabyteHost,+ environment: [:]) == nil)+ #expect(DecodeLoadAdmission.refusal(maxContextTokens: 262_144,+ hostMemoryBytes: twentyFourGigabyteHost,+ environment: [:]) == nil)+ }++ @Test func acontextThisHostCannotBackIsRefusedWithTheNeed() throws {+ let refusal = try #require(+ DecodeLoadAdmission.refusal(maxContextTokens: 262_144,+ hostMemoryBytes: eightGigabyteHost,+ environment: [:]))+ #expect(refusal.contains("262,144"))+ #expect(refusal.contains("16 GB"))+ #expect(refusal.contains("8 GB"))+ }++ /// The measurement the admission rule came from is only reachable by+ /// running a context the rule refuses, so the override exists — explicitly,+ /// and for nothing else.+ @Test func theoverrideAdmitsAnUnbackedContext() {+ #expect(DecodeLoadAdmission.refusal(+ maxContextTokens: 262_144,+ hostMemoryBytes: eightGigabyteHost,+ environment: [DecodeLoadAdmission.overrideEnvironmentKey: "1"]) == nil)+ }++ @Test(arguments: ["0", "", "true", "yes"])+ func theoverrideIsExactlyOneAndNothingElse(_ value: String) {+ #expect(DecodeLoadAdmission.refusal(+ maxContextTokens: 262_144,+ hostMemoryBytes: eightGigabyteHost,+ environment: [DecodeLoadAdmission.overrideEnvironmentKey: value]) != nil,+ "\(value) was treated as the override")+ }++ /// The model ceiling is not a memory question, so the diagnostic override+ /// must not reach it: a position beyond `max_position_embeddings` is+ /// invalid on a 512 GB machine too.+ @Test func themodelCeilingIsRefusedEvenWithTheOverrideSet() throws {+ let ceiling = ArchConfig.gemma4_26B_A4B.maxPositionEmbeddings+ let refusal = try #require(DecodeLoadAdmission.refusal(+ maxContextTokens: ceiling + 1,+ hostMemoryBytes: twentyFourGigabyteHost,+ environment: [DecodeLoadAdmission.overrideEnvironmentKey: "1"]))+ #expect(refusal.contains("262145"))+ #expect(refusal.contains("262144"))+ #expect(DecodeLoadAdmission.refusal(maxContextTokens: ceiling,+ hostMemoryBytes: twentyFourGigabyteHost,+ environment: [:]) == nil)+ }+}diff --git a/Tests/TurboFieldfareServer/OpenAIValidationTests.swift b/Tests/TurboFieldfareServer/OpenAIValidationTests.swiftindex aedfe67f..fa948bb9 100644--- a/Tests/TurboFieldfareServer/OpenAIValidationTests.swift+++ b/Tests/TurboFieldfareServer/OpenAIValidationTests.swift@@ -912,6 +912,21 @@ struct StreamingStopMatcherTests {@Suite("Server arguments")struct ServerArgumentTests {++ @Test(arguments: [24, 32])+ func cacheGrowthRejects128KOnEightGBUnlessExplicitlyOverridden(slots: Int) throws {+ let input = ["--model", "unused.gturbo", "--max-context", "131072",+ "--expert-cache-slots", String(slots)]+ #expect(throws: ServerArgumentError.self) {+ _ = try ServerArguments.parse(input, hostMemoryBytes: 8 << 30, environment: [:])+ }+ let overridden = try ServerArguments.parse(input, hostMemoryBytes: 8 << 30,+ environment: [ServerArguments.unbackedContextOverrideVariable: "1"])+ #expect(overridden.expertCacheSlots == slots)+ #expect(try ServerArguments.parse(input, hostMemoryBytes: 16 << 30,+ environment: [:]).maxContext == 131_072)+ }+@Test func defaults() throws {let arguments = try ServerArguments.parse(["--model", "model.gturbo"])#expect(arguments.port == 8080)@@ -1006,20 +1021,20 @@ struct ServerArgumentTests {@Test func runtimeFlagsReachTheResolvedConfiguration() throws {let arguments = try ServerArguments.parse(["--model", "model.gturbo",- "--expert-cache-slots", "32",+ "--expert-cache-slots", "24","--expert-cache-policy", "lru","--prefill", "on","--prefill-chunk-tokens", "64","--rdadvise", "adaptive",])- #expect(arguments.expertCacheSlots == 32)+ #expect(arguments.expertCacheSlots == 24)#expect(arguments.expertCachePolicy == .lru)#expect(arguments.prefillPolicy == .chunked)#expect(arguments.prefillChunkTokens == 64)#expect(arguments.rdadvisePolicy == .adaptive)let configuration = try arguments.resolvedRuntimeConfiguration()- #expect(configuration.expertCacheSlots == 32)+ #expect(configuration.expertCacheSlots == 24)#expect(configuration.expertCachePolicy == .lru)#expect(configuration.prefillPolicy == .chunked)#expect(configuration.prefillChunkTokens == 64)@@ -1062,6 +1077,112 @@ struct ServerArgumentTests {}}+ /// A host large enough to back every rung, so these cases test the+ /// allowlist rather than the machine the suite happens to run on.+ private static let sixteenGigabyteHost: UInt64 = 17_179_869_184+ private static let eightGigabyteHost: UInt64 = 8_589_934_592++ @Test(arguments: ServerArguments.allowedMaxContext)+ func everyAllowedContextParses(_ maxContext: Int) throws {+ let arguments = try ServerArguments.parse(+ ["--model", "model.gturbo", "--max-context", String(maxContext)],+ hostMemoryBytes: Self.sixteenGigabyteHost,+ environment: [:])+ #expect(arguments.maxContext == maxContext)+ }++ /// The allowlist is the last thing between a request and the KV allocator,+ /// so a rung above what the checkpoint's positions can address must not be+ /// reachable through it — a 262,145-token context has no RoPE position.+ @Test func everyAllowedContextFitsTheCheckpointCeiling() {+ let ceiling = ArchConfig.gemma4_26B_A4B.maxPositionEmbeddings+ #expect(ServerArguments.allowedMaxContext.allSatisfy { $0 <= ceiling })+ #expect(ServerArguments.allowedMaxContext.max() == ceiling)+ #expect(ServerArguments.allowedMaxContext == ServerArguments.allowedMaxContext.sorted())+ // The help text is the only place an operator reads the list, so it+ // must not drift from the list the parser enforces.+ for context in ServerArguments.allowedMaxContext {+ #expect(ServerArguments.usage.contains(String(context)), "context \(context)")+ }+ }++ @Test(arguments: [262_145, 100_000])+ func rejectsAContextOutsideTheAllowlist(_ maxContext: Int) throws {+ #expect(throws: ServerArgumentError.self) {+ try ServerArguments.parse(+ ["--model", "model.gturbo", "--max-context", String(maxContext)],+ hostMemoryBytes: Self.sixteenGigabyteHost,+ environment: [:])+ }+ }++ /// Refused at argument parsing, before the model starts loading: a 256K KV+ /// on an 8 GB Mac would otherwise fail inside the allocator with an error+ /// that names neither the context nor the memory it needed.+ @Test func aContextTheHostCannotBackIsRefusedWithItsMemoryNeed() throws {+ #expect(throws: ServerArgumentError.self) {+ try ServerArguments.parse(+ ["--model", "model.gturbo", "--max-context", "262144"],+ hostMemoryBytes: Self.eightGigabyteHost,+ environment: [:])+ }+ do {+ _ = try ServerArguments.parse(+ ["--model", "model.gturbo", "--max-context", "262144"],+ hostMemoryBytes: Self.eightGigabyteHost,+ environment: [:])+ Issue.record("a 256K context was admitted on an 8 GB host")+ } catch let error as ServerArgumentError {+ #expect(error.description.contains("262,144"))+ #expect(error.description.contains("needs 16 GB"))+ #expect(error.description.contains("this Mac has 8 GB"))+ #expect(error.description.contains("TURBO_FIELDFARE_ALLOW_UNBACKED_CONTEXT=1"))+ }+ }++ @Test func theSameContextIsAdmittedOnAHostThatBacksIt() throws {+ let arguments = try ServerArguments.parse(+ ["--model", "model.gturbo", "--max-context", "262144"],+ hostMemoryBytes: Self.sixteenGigabyteHost,+ environment: [:])+ #expect(arguments.maxContext == 262_144)+ }++ /// The override exists for measurement runs that deliberately exceed the+ /// rule to record what actually happens; it must admit the exact context+ /// the rule refused, not relax the rule generally.+ @Test func theOverrideAdmitsAnUnbackedContext() throws {+ let arguments = try ServerArguments.parse(+ ["--model", "model.gturbo", "--max-context", "262144"],+ hostMemoryBytes: Self.eightGigabyteHost,+ environment: ["TURBO_FIELDFARE_ALLOW_UNBACKED_CONTEXT": "1"])+ #expect(arguments.maxContext == 262_144)+ }++ /// 128K projects to 2.75 GiB of KV plus the 2 GiB non-KV runtime plus the+ /// 3 GiB host reserve: 8,320,122,880 bytes, which an 8 GB Mac clears by+ /// 269,811,712. Whether that margin survives a real decode is what step 9+ /// of the plan measures; the rule as written admits it, so this case pins+ /// the arithmetic rather than the outcome of that measurement.+ @Test func oneTwentyEightKIsAdmittedOnAnEightGigabyteHost() throws {+ let arguments = try ServerArguments.parse(+ ["--model", "model.gturbo", "--max-context", "131072"],+ hostMemoryBytes: Self.eightGigabyteHost,+ environment: [:])+ #expect(arguments.maxContext == 131_072)+ }++ /// Admission must not move the default: the server still starts at 16,384+ /// on a host that cannot back the new rungs.+ @Test func theDefaultContextIsUnchangedAndAdmittedEverywhere() throws {+ let arguments = try ServerArguments.parse(+ ["--model", "model.gturbo"],+ hostMemoryBytes: Self.eightGigabyteHost,+ environment: [:])+ #expect(arguments.maxContext == 16_384)+ #expect(arguments.maxContext == 16_384)+ }+/// The integers a message names, in order. Comparing these against the/// array the guard tests catches a message that omits a legal value and one/// that names an illegal extra, and cannot be fooled the way adiff --git a/Tests/TurboFieldfareServer/ServerImageTokenBudgetTests.swift b/Tests/TurboFieldfareServer/ServerImageTokenBudgetTests.swiftindex 62a13809..2708cffb 100644--- a/Tests/TurboFieldfareServer/ServerImageTokenBudgetTests.swift+++ b/Tests/TurboFieldfareServer/ServerImageTokenBudgetTests.swift@@ -88,6 +88,21 @@ struct ServerImageTokenBudgetTests {textTokens: 100, maxContext: 4_096))}+ /// The shared budget the server and the app both answer from grew an+ /// absolute per-turn cap when the context ceiling went to 262,144: the+ /// context-derived figure alone would offer about 930 images in one+ /// message. `fits` is unchanged — a request that fits still fits — but any+ /// surface asking "how many may I attach" gets the capped answer.+ @Test func theSharedCapacityIsBoundedAboveTheContextArithmetic() {+ #expect(VisionImageTokenBudget.capacity(+ maxContext: 262_144, reservedTextTokens: 0) == 32)+ #expect(VisionImageTokenBudget.capacity(+ maxContext: 65_536, reservedTextTokens: 0) == 32)+ // Small contexts are still decided by the arithmetic, not the cap.+ #expect(VisionImageTokenBudget.capacity(+ maxContext: 4_096, reservedTextTokens: 0) == 14)+ }+@Test func rejectionNamesTheRealCostRatherThanACount() {let error = ServerImageTokenBudget.rejection(imageCount: 3, softTokenCounts: [280, 280, 280],diff --git a/Tests/TurboFieldfareServer/ServerLogTests.swift b/Tests/TurboFieldfareServer/ServerLogTests.swiftindex 6e1927e9..a46f107c 100644--- a/Tests/TurboFieldfareServer/ServerLogTests.swift+++ b/Tests/TurboFieldfareServer/ServerLogTests.swift@@ -6,6 +6,107 @@ import Testing/// left the request's last line as `generating` forever: reading the log, a/// running request, an abandoned one and a crashed one were indistinguishable.@Suite struct ServerLogTests {+ private func completion(promptTokens: Int,+ cachedTokens: Int,+ completionTokens: Int,+ prefillSeconds: Double,+ decodeSeconds: Double) -> ServerCompletion {+ ServerCompletion(+ content: "ok",+ toolCalls: [],+ finishReason: "stop",+ usage: OpenAIUsage(promptTokens: promptTokens,+ completionTokens: completionTokens,+ totalTokens: promptTokens + completionTokens,+ cachedTokens: cachedTokens),+ prefillSeconds: prefillSeconds,+ decodeSeconds: decodeSeconds)+ }++ /// The two phases have wildly different rates at a long context — minutes+ /// of prefill against sub-second decode — so one aggregate duration hides+ /// which of them a change moved.+ @Test func completedMessageReportsPrefillAndDecodeSeparately() {+ let line = ServerLog.completedMessage(+ id: "chatcmpl-timing",+ duration: .seconds(676),+ completion: completion(promptTokens: 120_013,+ cachedTokens: 0,+ completionTokens: 1,+ prefillSeconds: 675.595,+ decodeSeconds: 0.250))++ #expect(line.contains("prompt=120013"))+ #expect(line.contains("cached=0"))+ #expect(line.contains("pp=675.595s"))+ #expect(line.contains("pp_tok_s=177.640"))+ #expect(line.contains("tg=0.250s"))+ #expect(line.contains("tg_tok_s=4.000"))+ #expect(line.contains("finish=stop"))+ }++ /// A prompt-cache hit prefills only the suffix, so counting the cached+ /// prefix as prefilled would report a prompt rate the runtime never+ /// achieved. Prompt reuse is the default server mode, so this is the+ /// common case rather than an edge one.+ @Test func promptThroughputExcludesCachedTokens() {+ let line = ServerLog.completedMessage(+ id: "chatcmpl-cached",+ duration: .seconds(3),+ completion: completion(promptTokens: 100_000,+ cachedTokens: 75_000,+ completionTokens: 4,+ prefillSeconds: 2.5,+ decodeSeconds: 0.5))++ #expect(line.contains("prompt=100000"))+ #expect(line.contains("cached=75000"))+ // 25,000 computed tokens over 2.5s, not 100,000 over 2.5s.+ #expect(line.contains("pp_tok_s=10000.000"))+ #expect(line.contains("tg_tok_s=8.000"))+ }++ /// A fully cached prompt does no prefill work at all, and a request that+ /// fails before decoding reports no decode time: both rates must read as+ /// zero rather than dividing by a zero elapsed time.+ @Test func zeroDurationsReportZeroRatesInsteadOfDividingByZero() {+ let line = ServerLog.completedMessage(+ id: "chatcmpl-allcached",+ duration: .seconds(1),+ completion: completion(promptTokens: 4_096,+ cachedTokens: 4_096,+ completionTokens: 0,+ prefillSeconds: 0,+ decodeSeconds: 0))++ #expect(line.contains("pp=0.000s"))+ #expect(line.contains("pp_tok_s=0.000"))+ #expect(line.contains("tg=0.000s"))+ #expect(line.contains("tg_tok_s=0.000"))+ #expect(!line.contains("nan"))+ #expect(!line.contains("inf"))+ }++ /// Both counts come from the runtime, so a cached count above the prompt+ /// would log a negative token count and a negative rate instead of the+ /// zero work that was actually done.+ @Test func moreCachedTokensThanPromptTokensClampsToZero() {+ let line = ServerLog.completedMessage(+ id: "chatcmpl-clamp",+ duration: .seconds(2),+ completion: completion(promptTokens: 10,+ cachedTokens: 25,+ completionTokens: 1,+ prefillSeconds: 1,+ decodeSeconds: 1))++ #expect(line.contains("pp_tok_s=0.000"))+ // The request id legitimately contains a hyphen, so assert on the rate+ // fields rather than scanning the whole line for a minus sign.+ #expect(!line.contains("pp_tok_s=-"))+ #expect(!line.contains("tg_tok_s=-"))+ }+@Test func aCancelledRequestReadsAsCancelledRatherThanFailed() {let line = ServerLog.cancelledMessage(id: "chatcmpl-abc",phase: "generating",diff --git a/docs/COMMUNITY_BENCHMARKS.md b/docs/COMMUNITY_BENCHMARKS.mdindex 3f806844..8cae61b0 100644--- a/docs/COMMUNITY_BENCHMARKS.md+++ b/docs/COMMUNITY_BENCHMARKS.md@@ -183,6 +183,9 @@ all affect decode speed.| [dragonwang1019](https://github.com/dragonwang1019) · [issue #101](https://github.com/drumih/turbo-fieldfare/issues/101) | M4 Pro Mac mini | 24 GB | External NVMe SSD | 61 / 516 | 22.256 tok/s | One submitted run || [dragonwang1019](https://github.com/dragonwang1019) · [issue #101](https://github.com/drumih/turbo-fieldfare/issues/101) | M4 Pro Mac mini | 24 GB | External NVMe SSD | 430 / 780 | 28.964 tok/s | One submitted run || [dragonwang1019](https://github.com/dragonwang1019) · [issue #101](https://github.com/drumih/turbo-fieldfare/issues/101) | M4 Pro Mac mini | 24 GB | External NVMe SSD | 3,015 / 617 | 24.209 tok/s | One submitted run |+| [r1tz](https://github.com/r1tz) · [issue #175](https://github.com/drumih/turbo-fieldfare/issues/175) | M4 Pro Mac mini | 24 GB | Not reported | 61 / 489 | 33.343 tok/s | One submitted run |+| [r1tz](https://github.com/r1tz) · [issue #175](https://github.com/drumih/turbo-fieldfare/issues/175) | M4 Pro Mac mini | 24 GB | Not reported | 430 / 760 | 31.236 tok/s | One submitted run |+| [r1tz](https://github.com/r1tz) · [issue #175](https://github.com/drumih/turbo-fieldfare/issues/175) | M4 Pro Mac mini | 24 GB | Not reported | 3,015 / 594 | 25.186 tok/s | One submitted run || [Marcelo Barros](https://github.com/marcelopbarros) · [issue #67](https://github.com/drumih/turbo-fieldfare/issues/67) | M4 Pro MacBook Pro | 24 GB | Internal SSD | 61 / 516 | 34.060 tok/s | Automatic mode || [Marcelo Barros](https://github.com/marcelopbarros) · [issue #67](https://github.com/drumih/turbo-fieldfare/issues/67) | M4 Pro MacBook Pro | 24 GB | Internal SSD | 430 / 780 | 30.954 tok/s | Automatic mode || [Marcelo Barros](https://github.com/marcelopbarros) · [issue #67](https://github.com/drumih/turbo-fieldfare/issues/67) | M4 Pro MacBook Pro | 24 GB | Internal SSD | 3,015 / 617 | 25.292 tok/s | Automatic mode |@@ -217,3 +220,11 @@ match.Each measured case ran in a fresh process with the sampling settings above;all three ended with `stop=endOfTurn`. The reporter reviewed the outputs andreported no loops, repeated blocks or protocol deviations.++[Issue #175](https://github.com/drumih/turbo-fieldfare/issues/175) reports a+12-core M4 Pro Mac mini (Mac16,11), macOS 26.6.2 (25G83), Swift 6.4, and commit+`4c6db1e698ea861609109d4bc517410ff302af46`. The attached prompt hashes match+the frozen community prompts. All three measured runs ended with+`stop=endOfTurn`; the attached outputs finish without obvious loops or+repeated blocks. Storage, energy mode and other active workloads were not+reported. These are individual submitted runs, not repeated-run averages.diff --git a/docs/OPENAI_SERVER.md b/docs/OPENAI_SERVER.mdindex 6b95df30..3d1e9f80 100644--- a/docs/OPENAI_SERVER.md+++ b/docs/OPENAI_SERVER.md@@ -244,9 +244,15 @@ The server supports one model and one choice. It does not support the ResponsesAPI, legacy Completions, embeddings, structured output,batching, log probabilities, or remote model switching.-Context length can be 4K, 8K, 16K, 32K, or 64K. The default is 16K. Larger FP16-KV contexts use more memory. On an 8 GB Mac, run one model process at a time and-watch memory pressure.+Context length can be 4K, 8K, 16K, 32K, 64K, 96K, 128K, 192K, or 256K.+The default is 16K. Before loading the model, the server checks whether the+selected context and expert cache fit its memory estimate for your Mac.+Larger contexts need more memory for the FP16 KV cache. See+[context length and memory](RUNTIME_CONTROLS.md#context-length-and-memory)+for the calculation and diagnostic override, and the+[long-context report](experiments/summaries/10-long-context.md) for measured+results and validation limits. On an 8 GB Mac, run one model process at a+time and watch memory pressure.For long requests, stderr reports the request lifecycle as prepared, queued,generating, completed, or failed. It includes token counts and timing, but notdiff --git a/docs/RUNTIME_CONTROLS.md b/docs/RUNTIME_CONTROLS.mdindex ee8de4a8..a6c5a792 100644--- a/docs/RUNTIME_CONTROLS.md+++ b/docs/RUNTIME_CONTROLS.md@@ -12,7 +12,7 @@ The Mac app and CLI expose these generation controls:| Control | Mac values | CLI flag | Default | Effect || --- | --- | --- | --- | --- || Maximum response | Automatic | `--max-new` | App: remaining context; CLI: 1,024 tokens | The app can use the context space left after the retained conversation and new turn. The CLI uses its explicit or default `--max-new` limit. |-| Maximum context | 4K, 8K, 16K, 32K, 64K | `--max-context` | CLI and app: 8K; server: 16K | Sets conversation or prompt plus response capacity, and 8K is what leaves room for an image and its prompt. The app shows the FP16 KV-memory delta. The server defaults higher still because agent clients routinely send prompts near 8K on their own. |+| Maximum context | 4K, 8K, 16K, 32K, 64K, 128K, 256K, depending on your Mac's RAM and cache settings | `--max-context` | CLI and app: 8K; server: 16K | Sets the combined capacity for the prompt or conversation and the response. The app shows how much FP16 KV-cache memory each size adds. The server defaults to 16K because agent clients routinely send prompts near 8K. || 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. |@@ -112,3 +112,33 @@ During chunked prefill, the phase label reports exact progress, for example`Prefill (128/514)`. Errors and unsupported configurations appear only whenthey occur. RDADVISE remains experimental and is off by default. A measuredresult is a data point, not a performance ceiling.++## Context length and memory++Use the default context unless you need a longer conversation: 8K in the app+and CLI, or 16K in the server.++The model supports up to 256K tokens, but larger contexts need more RAM. The+KV cache is allocated when the model loads, even if the conversation is empty.+The server also offers 96K and 192K.++The memory check includes the KV cache, 2 GiB for the runtime with 16+expert-cache slots, and 3 GiB for macOS and the file cache. Choosing 24 or 32+slots adds about 0.75 or 1.50 GiB. On an 8 GB Mac, neither leaves enough room+for 128K under this estimate.++When a setting exceeds the estimate:++- The app hides it and lowers an incompatible saved setting, with a notice.+- The server refuses to load.+- The CLI warns but continues.++For diagnostic runs, `TURBO_FIELDFARE_ALLOW_UNBACKED_CONTEXT=1` bypasses the+server check.++Passing the check doesn't guarantee enough free memory: it uses total RAM,+and other apps need memory too. Answer quality at 256K and memory use at 128K+on an 8 GB Mac still need testing. See the+[long-context report](experiments/summaries/10-long-context.md).++The app allows up to 32 images per message. The remaining context may fit fewer.diff --git a/docs/experiments/EXPERIMENT_INVENTORY.md b/docs/experiments/EXPERIMENT_INVENTORY.mdindex de8d741e..ccd497ed 100644--- a/docs/experiments/EXPERIMENT_INVENTORY.md+++ b/docs/experiments/EXPERIMENT_INVENTORY.md@@ -50,7 +50,7 @@ resident set size; and **NLL** is negative log-likelihood. See| Decode MoE, INT4, and router | [Persistent MoE, vectorization, router, and rejected geometries](summaries/02-decode-moe-int4-and-router.md) | 18 || Expert cache and layout | [Replacement policy, capacity, prediction, and disk layout](summaries/03-expert-cache-prediction-and-layout.md) | 9 || RDADVISE | [The complete short-win to long-context-rejection arc](summaries/04-rdadvise.md) | 7 |-| Attention and KV cache | [Split attention, MLX geometry, K4/V4, and FP16 ring](summaries/05-attention-and-kv-cache.md) | 14 |+| Attention and KV cache | [Split attention, MLX geometry, K4/V4, and FP16 ring](summaries/05-attention-and-kv-cache.md) | 15 || Prefill | [Chunking, MPP, routed MoE, overlap, attention, and allocation experiments](summaries/06-prefill.md) | 17 || Fusions and orchestration | [Targeted fusions, head variants, queues, and synchronization](summaries/07-fusions-head-and-orchestration.md) | 15 || Sampling and output | [Gumbel sampling, tokenizer caching, and detokenization](summaries/08-sampling-tokenization-and-output.md) | 4 |@@ -141,6 +141,7 @@ resident set size; and **NLL** is negative log-likelihood. See| [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. || [KV-13](summaries/05-attention-and-kv-cache.md#kv-13) — Ring kernel follow-up | Terminal 10.9% isolated median implied only about 0.34% whole-step opportunity. | Rejected; below action gate. || [KV-14](summaries/05-attention-and-kv-cache.md#kv-14) — Prefill attention race | Third barrier fixed one bank but cost 5.1-14.2%; two banks recovered 2.23-6.43%. | Correctness repair. |+| [KV-15](summaries/05-attention-and-kv-cache.md#kv-15) — Grouped full attention | 8.14 to 18.02 tok/s after a 110K-token prompt; all 256 output token IDs matched. One M5 Pro comparison with 32 cache slots. | Default for Gemma 4 full attention. See the [measurement limits](summaries/10-long-context.md#measurement-limits). |### Prefilldiff --git a/docs/experiments/summaries/05-attention-and-kv-cache.md b/docs/experiments/summaries/05-attention-and-kv-cache.mdindex 94d85845..58f2532f 100644--- a/docs/experiments/summaries/05-attention-and-kv-cache.md+++ b/docs/experiments/summaries/05-attention-and-kv-cache.md@@ -5,14 +5,14 @@[Optimization journey](../../OPTIMIZATION_JOURNEY.md) |[Next: Prefill](06-prefill.md)-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.+The runtime uses grouped full attention, split-KV sliding-window 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 |-| Exact split full attention | Production |+| Grouped full attention | Default for Gemma 4; other head shapes use the previous split-KV kernel || FP16 KV ring | Production || Packed K4/V4 and alternate codecs | Rejected and removed |@@ -93,7 +93,7 @@ failed the quality gate. It was rejected and removed.candidate was removed.- **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.+- **Final disposition:** Rejected. The later grouped kernel is covered in [KV-15](#kv-15).- **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).@@ -112,8 +112,8 @@ failed the quality gate. It was rejected and removed.mean delta-NLL threshold.- **What changed the conclusion:** Revalidation against the shipping instructioncheckpoint replaced the earlier promotion result.-- **Final disposition:** Rejected for the instruction checkpoint; exact split is- production.+- **Final disposition:** Rejected for the instruction checkpoint. The later grouped+ kernel is covered in [KV-15](#kv-15).- **Lesson:** Revalidate a strong speed signal when the rejection instrumentwas wrong. See [METH-01](09-validation-and-measurement-lessons.md#meth-01).@@ -254,6 +254,21 @@ failed the quality gate. It was rejected and removed.reader-to-next-writer edge. The surrounding compute path is covered in the[prefill summary](06-prefill.md).+<a id="kv-15"></a>+### KV-15: Grouped full attention with matched reduction order++After a 110,000-token prompt on an M5 Pro with 24 GB of RAM, grouped full+attention reached 18.02 tok/s, up from 8.14 with the previous split-KV kernel.+All 256 generated token IDs matched. Both runs used 32 expert-cache slots+and 256-token prefill chunks. The comparison ran once; neither run caused+new swapouts.++The first grouped implementation failed the short-prompt quality tests.+Preserving the previous kernel's score-reduction and fused multiply-add+order fixed the failure. Grouped attention is now the default for Gemma 4's+full-attention layers. The [long-context report](10-long-context.md) explains+the change, its validation and what remains untested.+[Previous: RDADVISE](04-rdadvise.md) |[Experiment inventory](../EXPERIMENT_INVENTORY.md) |[Optimization journey](../../OPTIMIZATION_JOURNEY.md) |diff --git a/docs/experiments/summaries/10-long-context.md b/docs/experiments/summaries/10-long-context.mdnew file mode 100644index 00000000..544f2dbf--- /dev/null+++ b/docs/experiments/summaries/10-long-context.md@@ -0,0 +1,34 @@+# Speeding up attention for long prompts++The previous full-attention kernel made GPU threads wait for each other+at every cached token. With a long prompt, those synchronization steps+added up, slowing down generation.++The new grouped kernel gives each attention head its own small group of+GPU threads. Heads that share cached data run together, but each can+calculate its scores without waiting for the others. Removing those+repeated waits makes attention faster while still using the full context.++## How I tested it++On an M5 Pro with 24 GB of RAM, I ran both kernels with the same+110,000-token prompt made from repeated prose, then generated 256 tokens+using greedy decoding. Only the attention kernel changed between runs.+Both used 32 expert-cache slots, above the default of 16.++Generation speed went from **8.14 to 18.02 tokens/s**, a 2.21x improvement.+The 256-token answer took 14.21 seconds instead of 31.46, and every output+token ID matched. These times exclude reading the prompt, which still+took about 20 minutes.++## Measurement limits++This was one comparison, with the previous kernel running first and OS+cache state uncontrolled. It used the private benchmark tool and has not+been repeated with the public package or the default cache size.+Matching output on this prompt does not establish quality on other prompts+or at 256K. The [memory guide](../../RUNTIME_CONTROLS.md#context-length-and-memory)+covers context settings and the remaining memory checks.++[Experiment inventory](../EXPERIMENT_INVENTORY.md) |+[Attention and KV cache](05-attention-and-kv-cache.md)