Skip to content

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

Speed up long-context prefill on Apple10 (#16)

Andrey Mikhaylovf8abc4422e33
diff --git a/README.md b/README.md
index 398ad5a7..8a40eb71 100644
--- a/README.md
+++ b/README.md
@@ -40,7 +40,7 @@ RAM.
The runtime, streaming installer, CLI, and native Mac app are written in Swift
and Metal. TurboFieldfare is model-specific rather than a wrapper around MLX or
llama.cpp. The curated [experiment record](docs/experiments/EXPERIMENT_INVENTORY.md)
-summarizes 102 measured results across kernels, caching, I/O, prefill, and
+summarizes 103 measured results across kernels, caching, I/O, prefill, and
decode.
## Try it
@@ -340,7 +340,7 @@ instruction checkpoint on Apple Silicon Macs with at least 8 GB of RAM.
The [experiments that shaped TurboFieldfare](docs/OPTIMIZATION_JOURNEY.md)
explain the largest wins, the plausible ideas that failed, and the early
results that reversed under stronger validation. The detailed
-[experiment record](docs/experiments/EXPERIMENT_INVENTORY.md) keeps all 102
+[experiment record](docs/experiments/EXPERIMENT_INVENTORY.md) keeps all 103
audited entries as optional evidence.
Useful entry points:
diff --git a/Sources/TurboFieldfare/Kernels/Attention/PrefillAttention.swift b/Sources/TurboFieldfare/Kernels/Attention/PrefillAttention.swift
index 28117011..3afa3bf2 100644
--- a/Sources/TurboFieldfare/Kernels/Attention/PrefillAttention.swift
+++ b/Sources/TurboFieldfare/Kernels/Attention/PrefillAttention.swift
@@ -43,10 +43,14 @@ struct PrefillAttentionParams: Sendable, Equatable {
final class PrefillAttention {
private let context: MetalContext
private let psoCausalTiled: MTLComputePipelineState
+ private let psoFullTensorOps2DValidityV2: MTLComputePipelineState?
init(context: MetalContext) throws {
self.context = context
self.psoCausalTiled = try context.pipeline("attention_prefill_causal_tiled")
+ self.psoFullTensorOps2DValidityV2 = context.device.supportsFamily(.apple10)
+ ? try? context.pipeline("attention_prefill_full_tensorops_2d_validity_v2")
+ : nil
}
func encodeCausal(commandBuffer: MTLCommandBuffer,
@@ -55,13 +59,39 @@ final class PrefillAttention {
v: MTLBuffer, vOffset: Int = 0,
out: MTLBuffer, outOffset: Int = 0,
params: PrefillAttentionParams,
- kvRingCapacity: UInt32 = 0) {
+ kvRingCapacity: UInt32 = 0,
+ path: RuntimePrefillAttentionPath = .causalTiled) {
validate(params)
- let pipeline = causalTiledPipeline(kvRingCapacity: kvRingCapacity)
+ let requestsTensorOps = path == .fullTensorOps2DPreferred
+ || path == .fullTensorOps2DValidityV2
+ // The pinned model uses 512/16/2 only for full attention; its
+ // sliding-window layers use 256/16/8. A future model that reuses this
+ // shape for sliding attention must add a full-visibility check here.
+ let tensorOpsShape = requestsTensorOps
+ && kvRingCapacity == 0
+ && params.headDim == 512
+ && params.numQHeads == 16
+ && params.numKVHeads == 2
+ && params.scale == 1.0
+ let tensorOpsPipeline = tensorOpsShape ? psoFullTensorOps2DValidityV2 : nil
+ let useTensorOps = tensorOpsPipeline != nil
+ let pipeline: MTLComputePipelineState
+ if let tensorOpsPipeline {
+ pipeline = tensorOpsPipeline
+ } else if tensorOpsShape && path == .fullTensorOps2DValidityV2 {
+ preconditionFailure(
+ "TensorOps 2D prefill attention requires Apple10 MPP tensor support")
+ } else {
+ // Explicit mode also falls back for incompatible shapes. Benchmark
+ // fixtures must use 512/16/2 to prove that TensorOps ran.
+ pipeline = causalTiledPipeline(kvRingCapacity: kvRingCapacity)
+ }
let headDim = Int(params.headDim)
let threadWidth = max(1, pipeline.threadExecutionWidth)
- let threadCount = roundUp(max(threadWidth, headDim), toMultipleOf: threadWidth)
+ let threadCount = useTensorOps
+ ? 128
+ : roundUp(max(threadWidth, headDim), toMultipleOf: threadWidth)
precondition(threadCount <= pipeline.maxTotalThreadsPerThreadgroup,
"tiled prefill attention requires headDim <= maxTotalThreadsPerThreadgroup")
@@ -73,8 +103,15 @@ final class PrefillAttention {
enc.setBuffer(out, offset: outOffset, index: 3)
var p = params
enc.setBytes(&p, length: MemoryLayout<PrefillAttentionParams>.stride, index: 4)
+ let groups = useTensorOps
+ ? MTLSize(width: Int(params.queryCount),
+ height: Int(params.numQHeads) / 8,
+ depth: 1)
+ : MTLSize(width: Int(params.queryCount),
+ height: Int(params.numQHeads),
+ depth: 1)
enc.dispatchThreadgroups(
- MTLSize(width: Int(params.queryCount), height: Int(params.numQHeads), depth: 1),
+ groups,
threadsPerThreadgroup: MTLSize(width: threadCount, height: 1, depth: 1))
enc.endEncoding()
}
diff --git a/Sources/TurboFieldfare/Metal/Prefill/prefill.metal b/Sources/TurboFieldfare/Metal/Prefill/prefill.metal
index 742ff410..94fd146b 100644
--- a/Sources/TurboFieldfare/Metal/Prefill/prefill.metal
+++ b/Sources/TurboFieldfare/Metal/Prefill/prefill.metal
@@ -1,6 +1,11 @@
#include <metal_stdlib>
using namespace metal;
+#if defined(__HAVE_TENSOR__)
+#include <MetalPerformancePrimitives/MetalPerformancePrimitives.h>
+using namespace mpp::tensor_ops;
+#endif
+
constant constexpr uint kPrefillGroupSize = 64;
constant constexpr uint kPrefillRmsMaxSimdGroups = 8;
constant constexpr uint kPrefillPostMaxD = 4096;
@@ -891,3 +896,272 @@ kernel void attention_prefill_causal_tiled(
out_row[d] = row_sum > 0.0f ? half(acc / row_sum) : half(0.0f);
}
}
+
+#if defined(__HAVE_TENSOR__)
+
+constant constexpr int kPrefillTensorOpsOutputs = 8;
+constant constexpr int kPrefillTensorOpsKeys = 64;
+constant constexpr int kPrefillTensorOpsHeadDim = 512;
+
+static inline void attention_prefill_full_tensorops_2d_validity_v2_impl(
+ device const half* Q,
+ device half* K,
+ device half* V,
+ device half* O,
+ constant PrefillAttentionParams& p,
+ uint3 tg,
+ uint lid,
+ uint threads,
+ threadgroup half* query_tile,
+ threadgroup float* score_tile,
+ threadgroup float* weight_tile,
+ threadgroup float* row_max,
+ threadgroup float* row_sum,
+ threadgroup float* row_old_scale
+) {
+ constexpr auto qk_desc = matmul2d_descriptor(
+ kPrefillTensorOpsOutputs,
+ kPrefillTensorOpsKeys,
+ kPrefillTensorOpsHeadDim,
+ false, true, false);
+ constexpr auto pv_desc = matmul2d_descriptor(
+ kPrefillTensorOpsOutputs,
+ kPrefillTensorOpsHeadDim,
+ kPrefillTensorOpsKeys,
+ false, false, false);
+ matmul2d<qk_desc, execution_simdgroups<4>> qk_op;
+ matmul2d<pv_desc, execution_simdgroups<4>> pv_op;
+
+ using device_half_tensor =
+ tensor<device half, dextents<int32_t, 2>, tensor_inline>;
+ using threadgroup_half_tensor =
+ tensor<threadgroup half, dextents<int32_t, 2>, tensor_inline>;
+ using threadgroup_float_tensor =
+ tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>;
+
+ const uint query_start = tg.x;
+ const uint qh_start = tg.y * uint(kPrefillTensorOpsOutputs);
+ const uint valid_query_rows =
+ min(1u, p.queryCount - min(query_start, p.queryCount));
+ const uint q_per_kv = p.numQHeads / p.numKVHeads;
+ const uint kvh = qh_start / q_per_kv;
+
+ for (uint linear = lid;
+ linear < uint(kPrefillTensorOpsOutputs * kPrefillTensorOpsHeadDim);
+ linear += threads) {
+ const uint output_row =
+ linear / uint(kPrefillTensorOpsHeadDim);
+ const uint d = linear % uint(kPrefillTensorOpsHeadDim);
+ if (valid_query_rows != 0u) {
+ query_tile[linear] = Q[
+ query_start * p.qTokenStrideElements
+ + (qh_start + output_row) * p.headDim
+ + d];
+ } else {
+ query_tile[linear] = half(0.0f);
+ }
+ }
+ if (lid < uint(kPrefillTensorOpsOutputs)) {
+ row_max[lid] = -INFINITY;
+ row_sum[lid] = 0.0f;
+ row_old_scale[lid] = 0.0f;
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ threadgroup_half_tensor query_tensor(
+ query_tile,
+ dextents<int32_t, 2>(
+ kPrefillTensorOpsHeadDim,
+ kPrefillTensorOpsOutputs),
+ array<int32_t, 2>({1, kPrefillTensorOpsHeadDim}));
+ threadgroup_float_tensor weight_tensor(
+ weight_tile,
+ dextents<int32_t, 2>(
+ kPrefillTensorOpsKeys,
+ kPrefillTensorOpsOutputs),
+ array<int32_t, 2>({1, kPrefillTensorOpsKeys}));
+ device_half_tensor key_tensor(
+ K + kvh * p.headDim,
+ dextents<int32_t, 2>(
+ int32_t(p.headDim),
+ int32_t(p.kvValidCount)),
+ array<int32_t, 2>({1, int32_t(p.kvTokenStrideElements)}));
+ device_half_tensor value_tensor(
+ V + kvh * p.headDim,
+ dextents<int32_t, 2>(
+ int32_t(p.headDim),
+ int32_t(p.kvValidCount)),
+ array<int32_t, 2>({1, int32_t(p.kvTokenStrideElements)}));
+
+ auto query_slice = query_tensor.slice(0, 0);
+ auto first_value_slice = value_tensor.slice(0, 0);
+ auto output_accumulator =
+ pv_op.get_destination_cooperative_tensor<
+ decltype(weight_tensor), decltype(first_value_slice), float>();
+ #pragma clang loop unroll(full)
+ for (int element = 0;
+ element < output_accumulator.get_capacity();
+ ++element) {
+ if (output_accumulator.is_valid_element(element)) {
+ output_accumulator[element] = 0.0f;
+ }
+ }
+
+ // This full-attention kernel starts at key zero and ignores slidingWindow.
+ // The Swift selector must dispatch it only when every prior key is visible.
+ const uint last =
+ min(p.kvValidCount, p.startPosition + query_start + valid_query_rows);
+ for (uint key_start = 0u;
+ key_start < last;
+ key_start += uint(kPrefillTensorOpsKeys)) {
+ auto key_slice = key_tensor.slice(0, int32_t(key_start));
+ auto score_product =
+ qk_op.get_destination_cooperative_tensor<
+ decltype(query_slice), decltype(key_slice), float>();
+ #pragma clang loop unroll(full)
+ for (int element = 0;
+ element < score_product.get_capacity();
+ ++element) {
+ if (score_product.is_valid_element(element)) {
+ score_product[element] = 0.0f;
+ }
+ }
+ qk_op.run(query_slice, key_slice, score_product);
+
+ #pragma clang loop unroll(full)
+ for (int element = 0;
+ element < score_product.get_capacity();
+ ++element) {
+ if (!score_product.is_valid_element(element)) continue;
+ const auto position =
+ score_product.get_multidimensional_index(element);
+ const uint key_column = uint(position[0]);
+ const uint output_row = uint(position[1]);
+ score_tile[
+ output_row * uint(kPrefillTensorOpsKeys) + key_column] =
+ score_product[element] * p.scale;
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ if (lid < uint(kPrefillTensorOpsOutputs)) {
+ const uint output_row = lid;
+ const uint causal_last = valid_query_rows != 0u
+ ? min(p.kvValidCount, p.startPosition + query_start + 1u)
+ : 0u;
+ const uint visible =
+ causal_last > key_start
+ ? min(uint(kPrefillTensorOpsKeys), causal_last - key_start)
+ : 0u;
+
+ float tile_max = -INFINITY;
+ for (uint key = 0u; key < visible; ++key) {
+ tile_max = max(
+ tile_max,
+ score_tile[
+ output_row * uint(kPrefillTensorOpsKeys) + key]);
+ }
+ const float next_max = max(row_max[output_row], tile_max);
+ const float old_scale = row_sum[output_row] > 0.0f
+ ? fast::exp(row_max[output_row] - next_max)
+ : 0.0f;
+ float tile_sum = 0.0f;
+ for (uint key = 0u;
+ key < uint(kPrefillTensorOpsKeys);
+ ++key) {
+ const float weight = key < visible
+ ? fast::exp(
+ score_tile[
+ output_row * uint(kPrefillTensorOpsKeys) + key]
+ - next_max)
+ : 0.0f;
+ weight_tile[
+ output_row * uint(kPrefillTensorOpsKeys) + key] = weight;
+ tile_sum += weight;
+ }
+ row_old_scale[output_row] = old_scale;
+ row_sum[output_row] =
+ row_sum[output_row] * old_scale + tile_sum;
+ row_max[output_row] = next_max;
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+
+ auto value_slice = value_tensor.slice(0, int32_t(key_start));
+ auto output_product =
+ pv_op.get_destination_cooperative_tensor<
+ decltype(weight_tensor), decltype(value_slice), float>();
+ #pragma clang loop unroll(full)
+ for (int element = 0;
+ element < output_product.get_capacity();
+ ++element) {
+ if (output_product.is_valid_element(element)) {
+ output_product[element] = 0.0f;
+ }
+ }
+ pv_op.run(weight_tensor, value_slice, output_product);
+ #pragma clang loop unroll(full)
+ for (int element = 0;
+ element < output_accumulator.get_capacity();
+ ++element) {
+ if (!output_accumulator.is_valid_element(element)
+ || !output_product.is_valid_element(element)) {
+ continue;
+ }
+ const auto position =
+ output_accumulator.get_multidimensional_index(element);
+ const uint output_row = uint(position[1]);
+ output_accumulator[element] =
+ fma(
+ 1.0f,
+ output_product[element],
+ output_accumulator[element] * row_old_scale[output_row]);
+ }
+ threadgroup_barrier(mem_flags::mem_threadgroup);
+ }
+
+ #pragma clang loop unroll(full)
+ for (int element = 0;
+ element < output_accumulator.get_capacity();
+ ++element) {
+ if (!output_accumulator.is_valid_element(element)) continue;
+ const auto position =
+ output_accumulator.get_multidimensional_index(element);
+ const uint d = uint(position[0]);
+ const uint output_row = uint(position[1]);
+ if (valid_query_rows != 0u) {
+ const float denominator = row_sum[output_row];
+ O[
+ query_start * p.oTokenStrideElements
+ + (qh_start + output_row) * p.headDim
+ + d] = denominator > 0.0f
+ ? half(output_accumulator[element] / denominator)
+ : half(0.0f);
+ }
+ }
+}
+
+kernel void attention_prefill_full_tensorops_2d_validity_v2(
+ device const half* Q [[buffer(0)]],
+ device half* K [[buffer(1)]],
+ device half* V [[buffer(2)]],
+ device half* O [[buffer(3)]],
+ constant PrefillAttentionParams& p [[buffer(4)]],
+ uint3 tg [[threadgroup_position_in_grid]],
+ uint lid [[thread_index_in_threadgroup]],
+ uint3 threads3 [[threads_per_threadgroup]]
+) {
+ threadgroup half query_tile[
+ kPrefillTensorOpsOutputs * kPrefillTensorOpsHeadDim];
+ threadgroup float score_tile[
+ kPrefillTensorOpsOutputs * kPrefillTensorOpsKeys];
+ threadgroup float weight_tile[
+ kPrefillTensorOpsOutputs * kPrefillTensorOpsKeys];
+ threadgroup float row_max[kPrefillTensorOpsOutputs];
+ threadgroup float row_sum[kPrefillTensorOpsOutputs];
+ threadgroup float row_old_scale[kPrefillTensorOpsOutputs];
+ attention_prefill_full_tensorops_2d_validity_v2_impl(
+ Q, K, V, O, p, tg, lid, threads3.x,
+ query_tile, score_tile, weight_tile,
+ row_max, row_sum, row_old_scale);
+}
+
+#endif
diff --git a/Sources/TurboFieldfare/Runtime/Configuration/RuntimeConfiguration.swift b/Sources/TurboFieldfare/Runtime/Configuration/RuntimeConfiguration.swift
index 4da2dbcc..d7b0c543 100644
--- a/Sources/TurboFieldfare/Runtime/Configuration/RuntimeConfiguration.swift
+++ b/Sources/TurboFieldfare/Runtime/Configuration/RuntimeConfiguration.swift
@@ -8,6 +8,12 @@ public enum RuntimePrefillPolicy: String, Codable, Sendable {
case chunked
}
+public enum RuntimePrefillAttentionPath: String, Codable, Sendable {
+ case causalTiled = "causal-tiled"
+ case fullTensorOps2DPreferred = "full-tensorops-2d-preferred"
+ case fullTensorOps2DValidityV2 = "full-tensorops-2d-validity-v2"
+}
+
public enum RuntimeExpertCachePolicy: String, Codable, Sendable {
case lfu
case lru
@@ -22,6 +28,7 @@ public struct RuntimeConfiguration: Sendable, Equatable {
public let rdadvisePolicy: RDAdvicePolicyMode
public let prefillPolicy: RuntimePrefillPolicy
public let prefillChunkTokens: Int
+ public let prefillAttentionPath: RuntimePrefillAttentionPath
public let headPath: RuntimeHeadPath
public init(expertCacheSlots: Int = 16,
@@ -29,6 +36,7 @@ public struct RuntimeConfiguration: Sendable, Equatable {
rdadvisePolicy: RDAdvicePolicyMode = .off,
prefillEnabled: Bool = true,
prefillChunkTokens: Int = 128,
+ prefillAttentionPath: RuntimePrefillAttentionPath = .fullTensorOps2DPreferred,
forceLogitsHead: Bool = false) {
precondition(Self.allowedExpertCacheSlots.contains(expertCacheSlots),
"unsupported expert-cache slot count")
@@ -39,6 +47,7 @@ public struct RuntimeConfiguration: Sendable, Equatable {
self.rdadvisePolicy = rdadvisePolicy
self.prefillPolicy = prefillEnabled ? .chunked : .off
self.prefillChunkTokens = prefillChunkTokens
+ self.prefillAttentionPath = prefillAttentionPath
self.headPath = forceLogitsHead ? .logits : .fusedRows
}
diff --git a/Sources/TurboFieldfare/Runtime/Inference/RealForwardRunner.swift b/Sources/TurboFieldfare/Runtime/Inference/RealForwardRunner.swift
index 16706f5d..4d33a6cd 100644
--- a/Sources/TurboFieldfare/Runtime/Inference/RealForwardRunner.swift
+++ b/Sources/TurboFieldfare/Runtime/Inference/RealForwardRunner.swift
@@ -219,6 +219,7 @@ public final class RealForwardRunner: ChunkedPrefillRunner, ContextWindowReporti
/// callers that sample from the logits buffer (non-greedy configs) must pass
/// `forceLogitsHead: true` or they read a never-written buffer.
private let useFusedGreedyHead: Bool
+ private let prefillAttentionPath: RuntimePrefillAttentionPath
public let rdadviseEnabled: Bool
public let rdadvisePolicyMode: RDAdvicePolicyMode
private var rdadviseSkipUntilPosition: Int = -1
@@ -232,6 +233,7 @@ public final class RealForwardRunner: ChunkedPrefillRunner, ContextWindowReporti
self.cfg = model.config
self.maxContext = maxContext
self.useFusedGreedyHead = runtimeConfiguration.headPath == .fusedRows
+ self.prefillAttentionPath = runtimeConfiguration.prefillAttentionPath
let useFP16Ring = runtimeConfiguration.fp16RingEnabled
self.rdadvisePolicyMode = runtimeConfiguration.rdadvisePolicy
self.rdadviseAdaptiveState = RDAdviceAdaptivePolicyState(
@@ -881,7 +883,8 @@ public final class RealForwardRunner: ChunkedPrefillRunner, ContextWindowReporti
v: valueBuffer,
out: scratch.attentionOutput,
params: params,
- kvRingCapacity: activeRingCapacity)
+ kvRingCapacity: activeRingCapacity,
+ path: prefillAttentionPath)
} else {
throw PrefillError.chunkedUnsupported(
"chunked prefill attention requires FP16 KV")
diff --git a/Tests/TurboFieldfare/Core/Kernels/Attention/PrefillAttentionTests.swift b/Tests/TurboFieldfare/Core/Kernels/Attention/PrefillAttentionTests.swift
index f8db64c2..92edb3d4 100644
--- a/Tests/TurboFieldfare/Core/Kernels/Attention/PrefillAttentionTests.swift
+++ b/Tests/TurboFieldfare/Core/Kernels/Attention/PrefillAttentionTests.swift
@@ -130,6 +130,66 @@ import TurboFieldfareValidationSupport
}
}
+ @Test(arguments: [
+ 1,
+ 63, 64, 65,
+ 127, 128, 129,
+ 255, 256, 257,
+ 1_023, 1_024, 1_025,
+ ])
+ func tensorOps2DFullAttentionMatchesReferenceAtTileBoundaries(_ visibleKeys: Int) throws {
+ let context = try MetalContext()
+ // Hosted CI has no Apple10 GPU, so it returns without dispatching this
+ // kernel. Run this suite on Apple10 before changing the TensorOps path.
+ guard context.device.supportsFamily(.apple10) else { return }
+ let fixture = Self.makeFixture(start: visibleKeys - 1,
+ chunk: 1,
+ window: 0,
+ seed: 0xA870 + UInt64(visibleKeys),
+ headDim: 512,
+ qHeads: 16,
+ kvHeads: 2)
+ let candidate = try Self.runKernel(
+ fixture,
+ path: .fullTensorOps2DValidityV2)
+ let repeated = try Self.runKernel(
+ fixture,
+ path: .fullTensorOps2DValidityV2)
+ let reference = Self.reference(fixture)
+ let maxAbs = RelError.maxAbsDiff(candidate, reference)
+ let rel = RelError.compute(actual: candidate, reference: reference)
+ #expect(candidate == repeated,
+ "TensorOps 2D full attention is not byte-stable at \(visibleKeys) keys")
+ #expect(maxAbs <= 2e-2,
+ "TensorOps 2D maxAbs=\(maxAbs) rel=\(rel) keys=\(visibleKeys)")
+ #expect(rel <= 2e-2,
+ "TensorOps 2D rel=\(rel) maxAbs=\(maxAbs) keys=\(visibleKeys)")
+ }
+
+ @Test func preferredTensorOpsPathUsesSafeHardwareFallback() throws {
+ let context = try MetalContext()
+ let fixture = Self.makeFixture(start: 128,
+ chunk: 1,
+ window: 0,
+ seed: 0xA872,
+ headDim: 512,
+ qHeads: 16,
+ kvHeads: 2)
+ let preferred = try Self.runKernel(
+ fixture,
+ path: .fullTensorOps2DPreferred)
+ let reference = Self.reference(fixture)
+ let maxAbs = RelError.maxAbsDiff(preferred, reference)
+ let rel = RelError.compute(actual: preferred, reference: reference)
+ #expect(maxAbs <= 2e-2,
+ "preferred TensorOps maxAbs=\(maxAbs) rel=\(rel)")
+ #expect(rel <= 2e-2,
+ "preferred TensorOps rel=\(rel) maxAbs=\(maxAbs)")
+ if !context.device.supportsFamily(.apple10) {
+ let baseline = try Self.runKernel(fixture, path: .causalTiled)
+ #expect(preferred == baseline)
+ }
+ }
private static func makeFixture(start: Int,
chunk: Int,
@@ -179,8 +239,11 @@ import TurboFieldfareValidationSupport
#expect(rel <= 2e-2, "\(label) rel=\(rel) maxAbs=\(maxAbs)")
}
- private static func runKernel(_ fixture: Fixture,
- kvRingCapacity: UInt32 = 0) throws -> [Float] {
+ private static func runKernel(
+ _ fixture: Fixture,
+ kvRingCapacity: UInt32 = 0,
+ path: RuntimePrefillAttentionPath = .causalTiled
+ ) throws -> [Float] {
let ctx = try MetalContext()
let prefill = try PrefillAttention(context: ctx)
let qPrefix = 17
@@ -224,7 +287,8 @@ import TurboFieldfareValidationSupport
out: outBuf,
outOffset: oPrefix * MemoryLayout<Float16>.size,
params: params,
- kvRingCapacity: kvRingCapacity)
+ kvRingCapacity: kvRingCapacity,
+ path: path)
cb.commit()
cb.waitUntilCompleted()
diff --git a/Tests/TurboFieldfare/Core/Runtime/Configuration/RuntimeConfigurationTests.swift b/Tests/TurboFieldfare/Core/Runtime/Configuration/RuntimeConfigurationTests.swift
index 7d044bb2..c897da73 100644
--- a/Tests/TurboFieldfare/Core/Runtime/Configuration/RuntimeConfigurationTests.swift
+++ b/Tests/TurboFieldfare/Core/Runtime/Configuration/RuntimeConfigurationTests.swift
@@ -11,6 +11,7 @@ import Testing
#expect(!runtime.rdadviseEnabled)
#expect(runtime.prefillPolicy == .chunked)
#expect(runtime.prefillChunkTokens == 128)
+ #expect(runtime.prefillAttentionPath == .fullTensorOps2DPreferred)
#expect(runtime.headPath == .fusedRows)
}
@@ -21,11 +22,13 @@ import Testing
rdadvisePolicy: .adaptive,
prefillEnabled: false,
prefillChunkTokens: 64,
+ prefillAttentionPath: .causalTiled,
forceLogitsHead: true)
#expect(runtime.expertCacheSlots == 32)
#expect(runtime.modelExpertCachePolicy == .lru)
#expect(runtime.rdadviseEnabled)
#expect(runtime.prefillConfig == .off)
+ #expect(runtime.prefillAttentionPath == .causalTiled)
#expect(runtime.headPath == .logits)
}
diff --git a/docs/OPTIMIZATION_JOURNEY.md b/docs/OPTIMIZATION_JOURNEY.md
index f417c948..1fdc81f0 100644
--- a/docs/OPTIMIZATION_JOURNEY.md
+++ b/docs/OPTIMIZATION_JOURNEY.md
@@ -196,6 +196,22 @@ about 0.4% of the remaining prefill time.
The optimization worked, but the affected kernels were now too small to
matter.
+Full attention became expensive for a different reason. Gemma 4 shares one
+K/V head across eight query heads, but the tiled kernel handled each query head
+separately. It launched eight threadgroups and read the same K/V data eight
+times.
+
+TensorOps processes all eight heads at once, making attention 11x faster at
+64K.
+
+The full runtime kept much of that gain. On the same 32K input, prefill fell
+from 491.09 to 204.29 seconds, a 2.404x speedup without increasing memory use.
+
+We nearly threw this result away because the new reduction order changed the
+final logits slightly. Better checks showed the differences were harmless.
+
+TensorOps is now the Apple10 path. Earlier GPUs keep tiled attention.
+
## Sampling removed repeated vocabulary scans
Sampling revealed an algorithmic problem rather than a slow kernel.
diff --git a/docs/experiments/EXPERIMENT_INVENTORY.md b/docs/experiments/EXPERIMENT_INVENTORY.md
index b7861456..634baaf5 100644
--- a/docs/experiments/EXPERIMENT_INVENTORY.md
+++ b/docs/experiments/EXPERIMENT_INVENTORY.md
@@ -51,13 +51,13 @@ resident set size; and **NLL** is negative log-likelihood. See
| 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 |
-| Prefill | [Chunking, MPP, routed MoE, overlap, and allocation experiments](summaries/06-prefill.md) | 16 |
+| 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 |
| Validation methodology | [False rejections, holdouts, thermal state, and benchmark artifacts](summaries/09-validation-and-measurement-lessons.md) | 9 |
-| **Total** | | **102** |
+| **Total** | | **103** |
-## All 102 experiments
+## All 103 experiments
### Model installation and expert I/O
@@ -162,6 +162,7 @@ resident set size; and **NLL** is negative log-likelihood. See
| [PF-14](summaries/06-prefill.md#pf-14) — QMM TG reuse | Families +3.2-9.7%; current opportunity about 0.41%. | Rejected. |
| [PF-15](summaries/06-prefill.md#pf-15) — Batched routed MoE | Isolated +30.91%; balanced end to end about +2%. | Reversed rejection; production. |
| [PF-16](summaries/06-prefill.md#pf-16) — Long endpoint gate | Delta-NLL +0.002588; top-1 16/16; RSS 888.3 MiB. | Production; validation result. |
+| [PF-17](summaries/06-prefill.md#pf-17) — Apple10 TensorOps full attention | Isolated 11.24x at 16K and 11.63x at 64K; 32K end to end 2.404x. | Production on Apple10; tiled fallback elsewhere. |
### Fusions, head, and orchestration
@@ -196,7 +197,7 @@ resident set size; and **NLL** is negative log-likelihood. See
| ID | Lesson | Consequence |
| --- | --- | --- |
-| [METH-01](summaries/09-validation-and-measurement-lessons.md#meth-01) | Reordered floating-point work needs a distributional quality oracle. | Corrected false rejections of MLX attention, staged MPP, and batched MoE. |
+| [METH-01](summaries/09-validation-and-measurement-lessons.md#meth-01) | Reordered floating-point work needs a distributional quality oracle. | Corrected false rejections of MLX attention, staged MPP, batched MoE, and TensorOps prefill attention. |
| [METH-02](summaries/09-validation-and-measurement-lessons.md#meth-02) | Claimed-lossless work still needs exact identity. | Retained strict gates for cache, storage, and load-width changes. |
| [METH-03](summaries/09-validation-and-measurement-lessons.md#meth-03) | Test production-shaped offsets. | Found the live 2-byte INT4 alignment defect. |
| [METH-04](summaries/09-validation-and-measurement-lessons.md#meth-04) | Prove synchronization scope. | Repaired one reused scratch bank; audited other paths by ownership and queue order. |
diff --git a/docs/experiments/summaries/06-prefill.md b/docs/experiments/summaries/06-prefill.md
index f22f593d..18521883 100644
--- a/docs/experiments/summaries/06-prefill.md
+++ b/docs/experiments/summaries/06-prefill.md
@@ -13,6 +13,7 @@ failed the M2 long-row gate.
| Current result | Disposition |
| --- | --- |
| Chunk 128, staged affine MPP, and batched routed MoE | Production |
+| Apple10 TensorOps full attention | Production on Apple10; tiled fallback elsewhere |
| Shared/fetch overlap v3 | Rejected and removed |
| Shared INT8 QMM, deeper lookahead, and argument-buffer rings | Rejected on M2 |
@@ -266,6 +267,28 @@ failed the M2 long-row gate.
- **Lesson:** Long endpoint sweeps
separate a local tie from a systematic quality change.
+<a id="pf-17"></a>
+### PF-17: Apple10 TensorOps full-prefill attention
+
+- **Hypothesis:** One threadgroup could process all eight Q heads in a full
+ attention GQA group, reuse K/V reads, and map QK/PV onto cooperative matrix
+ operations.
+- **Variants tested:** Production tiled attention, four-head grouped online
+ softmax, and an eight-head TensorOps path with FP32 QK/PV accumulation.
+- **Evidence:** TensorOps was 11.24x faster at isolated 16K and 11.63x at 64K.
+ Same-input 32K prefill fell from 491.09 to 204.29 seconds, a 2.404x
+ end-to-end speedup, with identical post-prefill RSS. Direct attention
+ reference checks passed through 64K, and frozen MLX-relative endpoints
+ matched top-1 at 8K/16K/32K/64K.
+- **What changed the conclusion:** Exact production-logit identity falsely
+ rejected a valid floating-point reduction order. Direct attention error and
+ independent MLX quality gates isolated top-k routing amplification instead
+ of a shader semantic defect.
+- **Final disposition:** Production on Apple10; automatic causal-tiled fallback
+ on earlier GPU families and a named rollback remain.
+- **Lesson:** Reordered floating-point kernels need a direct numerical oracle
+ plus model-quality gates, not identity with one reduction order.
+
[Previous: Attention and KV cache](05-attention-and-kv-cache.md) |
[Experiment inventory](../EXPERIMENT_INVENTORY.md) |
[Optimization journey](../../OPTIMIZATION_JOURNEY.md) |
diff --git a/docs/experiments/summaries/09-validation-and-measurement-lessons.md b/docs/experiments/summaries/09-validation-and-measurement-lessons.md
index fa094adc..69b2ea6a 100644
--- a/docs/experiments/summaries/09-validation-and-measurement-lessons.md
+++ b/docs/experiments/summaries/09-validation-and-measurement-lessons.md
@@ -24,7 +24,7 @@ from representative holdouts.
- **Hypothesis:** Exact cross-process tokens or raw logits could validate any
candidate.
- **Variants tested:** That oracle was applied to MLX attention,
- staged MPP INT4 prefill, and batched routed MoE.
+ staged MPP INT4 prefill, batched routed MoE, and TensorOps prefill attention.
- **Evidence:** Each candidate
had a strong speed signal but crossed known near ties under reordered
floating-point work. Reference-relative delta-NLL, top-k agreement, and
@@ -32,7 +32,7 @@ from representative holdouts.
- **What changed the conclusion:** The validation
contract, not the candidates, was wrong.
- **Final disposition:** Methodology
- corrected; three false rejections reversed.
+ corrected; four false rejections reversed.
- **Lesson:** Numerical equivalence
is a distributional claim, not a bit-identity claim.