diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedAttentionKernel.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedAttentionKernel.swift index b7cdbed199..5373f4794d 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedAttentionKernel.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedAttentionKernel.swift @@ -53,6 +53,9 @@ struct PagedAttentionKernelKey: Hashable { var partitionTokens: Int /// Pass A only: fuse the decode KV write into the kernel. var hasWrite: Bool = false + /// Pass A only: merge-record heads per round of the side-by-side form + /// (`paged_attention_part_side_impl`); 0 is the plain form. + var sideHeadsPerRound: Int = 0 var kernelName: String { let d: String @@ -72,6 +75,7 @@ struct PagedAttentionKernelKey: Hashable { + "_n\(simdgroups)_t\(partitionTokens)" + "_sink\(hasSinks ? 1 : 0)_cap\(hasSoftcap ? 1 : 0)" + (hasWrite ? "_w1" : "") + + (sideHeadsPerRound > 0 ? "_side\(sideHeadsPerRound)" : "") } } @@ -126,6 +130,45 @@ enum PagedAttentionMSL { thread_index_in_simdgroup); """ + /// Side-by-side pass A (`paged_attention_part_side_impl`): one + /// threadgroup holds every head group of a kv head. Same inputs and + /// outputs as `partBody` / `partBodyNoWrite`. + static let partBodySide: String = """ + const int kvh = kcache_shape[1]; + const int maxp = tables_shape[1]; + const int maxpart = threadgroups_per_grid.z; + if (thread_position_in_grid.x == 0 && thread_position_in_grid.y == 0 + && thread_position_in_grid.z == 0) { + fence[0] = wfence[0] + 1; + } + threadgroup float q_smem[GQA * D]; + threadgroup float red_smem[NSG * HRED * (D + 2)]; + const cbv2::PagedSlabAccessor cache{kcache, vcache, (size_t)kvh * S * D}; + cbv2::paged_attention_part_side_impl( + q, knew, vnew, cache, tables, seqinfo, params, + kvh, maxp, maxpart, q_smem, red_smem, partials, meta, + threadgroup_position_in_grid, + thread_position_in_threadgroup, + simdgroup_index_in_threadgroup, + thread_index_in_simdgroup); + """ + + static let partBodySideNoWrite: String = """ + const int kvh = kcache_shape[1]; + const int maxp = tables_shape[1]; + const int maxpart = threadgroups_per_grid.z; + threadgroup float q_smem[GQA * D]; + threadgroup float red_smem[NSG * HRED * (D + 2)]; + const cbv2::PagedSlabAccessor cache{kcache, vcache, (size_t)kvh * S * D}; + cbv2::paged_attention_part_side_impl( + q, q, q, cache, tables, seqinfo, params, + kvh, maxp, maxpart, q_smem, red_smem, partials, meta, + threadgroup_position_in_grid, + thread_position_in_threadgroup, + simdgroup_index_in_threadgroup, + thread_index_in_simdgroup); + """ + /// Bulk in-place KV write: scatters `[KVH, N, D]` tiles into the slabs /// and emits the next fence in the group's write chain. static let writeBody: String = """ @@ -462,6 +505,68 @@ public enum PagedAttentionKernel { return nil } + /// Threads of one side-by-side threadgroup at most: the measured shapes + /// (27B full attention, Gemma 4 global layers) run 512. + static let sideBySideMaxThreads = 512 + + /// Exact threadgroup bytes of the side-by-side pass A: every query head + /// of the kv head staged, plus NSG merge records of `headsPerRound` heads. + public static func sideBySideThreadgroupBytes( + headDim: Int, gqa: Int, simdgroups: Int, headsPerRound: Int + ) -> Int { + let qSmem = gqa * headDim + let redSmem = simdgroups * headsPerRound * (headDim + mergeRecordMetaFloats) + return (qSmem + redSmem) * MemoryLayout.size + } + + /// Merge-record heads per round (the kernel's HRED) of the side-by-side + /// pass A for one shape: the largest divisor of `headsPerThreadgroup` + /// whose buffers fit the threadgroup-memory cap. Nil when a kv head's + /// query heads already share one threadgroup, or the form does not fit. + public static func sideBySideHeadsPerRound(headDim: Int, gqa: Int) -> Int? { + guard ineligibilityReason(headDim: headDim, gqa: gqa) == nil, + let nsg = simdgroupsPerThreadgroup(headDim: headDim, gqa: gqa) + else { return nil } + let hpt = headsPerThreadgroup(headDim: headDim, gqa: gqa) + let splits = gqa / hpt + guard splits > 1, 32 * nsg * splits <= sideBySideMaxThreads else { return nil } + return stride(from: hpt, through: 1, by: -1).first { + hpt % $0 == 0 + && sideBySideThreadgroupBytes( + headDim: headDim, gqa: gqa, simdgroups: nsg, headsPerRound: $0) + <= threadgroupMemoryLimit + } + } + + /// Attended length from which decode takes the side-by-side pass A; 0 is + /// off, the default. Both forms give the same bits; the side-by-side form + /// reads a partition's keys and values once per kv head instead of once + /// per head group. Per attention layer it was faster at long context on an + /// M5 Ultra (1.08x for the 27B shape and 1.22x for Gemma 4 global layers at + /// 65,536 tokens, slower for Gemma below 32,768), but whole decode steps on + /// an M5 Max were not faster, so it stays opt-in until the engine is timed: + /// `DARKBLOOM_CBV2_PAGED_SIDE_BY_SIDE_TOKENS=49152` takes it from that length. + public static let sideBySideMinimumTokens = sideBySideMinimum( + environment: ProcessInfo.processInfo.environment) + static let sideBySideEnvironmentKey = "DARKBLOOM_CBV2_PAGED_SIDE_BY_SIDE_TOKENS" + static let sideBySideDefaultTokens = 0 + + static func sideBySideMinimum(environment: [String: String]) -> Int { + guard let raw = environment[sideBySideEnvironmentKey], + let value = Int(raw.trimmingCharacters(in: .whitespaces)), value >= 0 + else { return sideBySideDefaultTokens } + return value + } + + /// HRED of the side-by-side pass A for one decode dispatch, or nil for + /// the plain form. + static func sideBySideForDispatch( + headDim: Int, gqa: Int, maxAttendLength: Int, minimumTokens: Int + ) -> Int? { + guard minimumTokens > 0, maxAttendLength >= minimumTokens else { return nil } + return sideBySideHeadsPerRound(headDim: headDim, gqa: gqa) + } + private final class KernelCache: @unchecked Sendable { private var kernels: [PagedAttentionKernelKey: MLXFast.MLXFastKernel] = [:] private let lock = NSLock() @@ -487,7 +592,8 @@ public enum PagedAttentionKernel { "params", "wfence", ], outputNames: ["partials", "meta", "fence"], - source: PagedAttentionMSL.partBody, + source: key.sideHeadsPerRound > 0 + ? PagedAttentionMSL.partBodySide : PagedAttentionMSL.partBody, header: source, ensureRowContiguous: true, mutableInputs: ["kcache", "vcache"] @@ -499,7 +605,8 @@ public enum PagedAttentionKernel { "q", "kcache", "vcache", "tables", "seqinfo", "params", "wfence", ], outputNames: ["partials", "meta"], - source: PagedAttentionMSL.partBodyNoWrite, + source: key.sideHeadsPerRound > 0 + ? PagedAttentionMSL.partBodySideNoWrite : PagedAttentionMSL.partBodyNoWrite, header: source, ensureRowContiguous: true ) @@ -648,7 +755,8 @@ public enum PagedAttentionKernel { pageSize: Int, writeFence: MLXArray, kernelSource: String, - stream: StreamOrDevice = .default + stream: StreamOrDevice = .default, + sideBySideMinimumTokens: Int = PagedAttentionKernel.sideBySideMinimumTokens ) throws(CBv2PagedKVWriteError) -> (out: MLXArray, nextWriteFence: MLXArray?) { var q = queries if q.ndim == 4 { @@ -714,29 +822,36 @@ public enum PagedAttentionKernel { // `ceilingDivide`, not `(a + b - 1) / b`: `maxAttendLength` is // caller-supplied, and this is the site that motivated the helper. let maxParts = ceilingDivide(maxAttendLength, ptok) + let side = sideBySideForDispatch( + headDim: headDim, gqa: gqa, maxAttendLength: maxAttendLength, + minimumTokens: sideBySideMinimumTokens) let partKey = PagedAttentionKernelKey( pass: .part, dtype: dtype, headDim: headDim, pageSize: pageSize, gqa: gqa, simdgroups: nsg, hasSinks: false, hasSoftcap: softcap, - partitionTokens: ptok, hasWrite: hasWrite) + partitionTokens: ptok, hasWrite: hasWrite, sideHeadsPerRound: side ?? 0) let tg = 32 * nsg + var partTemplate: [(String, any KernelTemplateArg)] = [ + ("T", dtype), + ("D", headDim), + ("S", pageSize), + ("GQA", gqa), + ("HPT", hpt), + ("NSG", nsg), + ("PTOK", ptok), + ("HAS_SOFTCAP", softcap), + ] + if let side { partTemplate.append(("HRED", side)) } // MLX passes arrays smaller than 8 elements in Metal's constant address // space; the merge implementation expects a device pointer. Keep even // a one-head/one-partition probe on the same legal interface. let metaShape = [max(8, b * queryHeads * maxParts * 2)] + // Same grid either way: the side-by-side form's threadgroup holds all + // `splits` head groups of a kv head. let partOut = kernel(for: partKey, source: kernelSource)( partInputs, - template: [ - ("T", dtype), - ("D", headDim), - ("S", pageSize), - ("GQA", gqa), - ("HPT", hpt), - ("NSG", nsg), - ("PTOK", ptok), - ("HAS_SOFTCAP", softcap), - ], + template: partTemplate, grid: (kvHeads * splits * tg, b, maxParts), - threadGroup: (tg, 1, 1), + threadGroup: (side == nil ? tg : tg * splits, 1, 1), outputShapes: hasWrite ? [[b, queryHeads, maxParts, headDim], metaShape, [1]] : [[b, queryHeads, maxParts, headDim], metaShape], diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedSegmentAttention.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedSegmentAttention.swift index 2dcb08c3ac..689730071c 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedSegmentAttention.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/PagedSegmentAttention.swift @@ -37,6 +37,28 @@ enum PagedSegmentAttention { """ } + /// `body` with the side-by-side pass A: one threadgroup holds every head + /// group of a kv head (`PagedAttentionKernel.sideBySideHeadsPerRound`). + static func sideBody(bindings: Int) -> String { + let pointers = (0 ..< bindings).map { "segment\($0)" }.joined(separator: ", ") + return """ + const device int32_t* record = records + threadgroup_position_in_grid.y * STRIDE; + const cbv2::PagedSegmentAccessor cache{ + {\(pointers)}, value_offsets, record, (size_t)KVH * S * D}; + const uint3 position(threadgroup_position_in_grid.x, record[0], record[1]); + if (thread_position_in_grid.x == 0 && thread_position_in_grid.y == 0) { + fence[0] = previous[0] + 1; + } + threadgroup float q_smem[GQA * D]; + threadgroup float red_smem[NSG * HRED * (D + 2)]; + cbv2::paged_attention_part_side_impl( + q, knew, vnew, cache, seqinfo, seqinfo, params, KVH, 0, record[6], + q_smem, red_smem, partials, meta, + position, thread_position_in_threadgroup, simdgroup_index_in_threadgroup, + thread_index_in_simdgroup); + """ + } + private static func kernel( key: PagedAttentionKernelKey, bindings: Int, kvHeads: Int, source: String, allocatesScratch: Bool = false @@ -50,7 +72,9 @@ enum PagedSegmentAttention { name: name, inputNames: inputNames(bindings: bindings, allocatesScratch: allocatesScratch), outputNames: ["fence"] + (allocatesScratch ? ["partials", "meta"] : []), - source: body(bindings: bindings), header: source, ensureRowContiguous: true, + source: key.sideHeadsPerRound > 0 + ? sideBody(bindings: bindings) : body(bindings: bindings), + header: source, ensureRowContiguous: true, mutableInputs: (allocatesScratch ? [] : ["partials", "meta"]) + (key.hasWrite ? (0 ..< bindings).map { "segment\($0)" } : [])) kernels[name] = made @@ -83,7 +107,8 @@ enum PagedSegmentAttention { sinks: MLXArray?, params: MLXArray, softcap: Bool, source: String, dispatchCache: PagedSegmentDispatchCache? = nil, zeroFilledScratch: Bool = false, - seqinfoCache: PagedSegmentSeqinfoCache? = nil + seqinfoCache: PagedSegmentSeqinfoCache? = nil, + sideBySideMinimumTokens: Int = PagedAttentionKernel.sideBySideMinimumTokens ) -> MLXArray { var q = queries.ndim == 4 ? queries.squeezed(axis: 2) : queries guard !group.writeValidation.isFaulted else { return q } @@ -138,10 +163,14 @@ enum PagedSegmentAttention { var partials: MLXArray? = zeroFilledScratch ? MLXArray.zeros(partialsShape, dtype: .float32) : nil var meta: MLXArray? = zeroFilledScratch ? MLXArray.zeros([metaCount], dtype: .float32) : nil + let side = PagedAttentionKernel.sideBySideForDispatch( + headDim: d, gqa: gqa, maxAttendLength: maxLength, + minimumTokens: sideBySideMinimumTokens) let partKey = PagedAttentionKernelKey( pass: .part, dtype: dtype, headDim: d, pageSize: group.pageSize, gqa: gqa, simdgroups: nsg, hasSinks: false, hasSoftcap: softcap, - partitionTokens: ptok, hasWrite: newKeys != nil) + partitionTokens: ptok, hasWrite: newKeys != nil, sideHeadsPerRound: side ?? 0) + let threads = side == nil ? 32 * nsg : 32 * nsg * splits for (bucket, metadata) in zip(plan.buckets, prepared.metadata) { let segments = bucket.segmentIDs.map { group.segments[$0]! } let bindingCount = bucket.bindingClass @@ -154,26 +183,27 @@ enum PagedSegmentAttention { [q, k, v] + backing + [ seqinfo, params, group.writeFence, metadata.valueOffsets, metadata.records, ] - let template: [(String, any KernelTemplateArg)] = [ + var template: [(String, any KernelTemplateArg)] = [ ("T", dtype), ("D", d), ("S", group.pageSize), ("KVH", kvh), ("GQA", gqa), ("HPT", hpt), ("NSG", nsg), ("PTOK", ptok), ("HAS_WRITE", newKeys != nil), ("HAS_SOFTCAP", softcap), ("SEGMENTS", bindingCount), ("STRIDE", PagedSegmentDispatchPlan.recordStride), ] + if let side { template.append(("HRED", side)) } let grid = (kvh * splits * 32 * nsg, bucket.workCount, 1) if let partials, let meta { group.writeFence = kernel( key: partKey, bindings: bindingCount, kvHeads: kvh, source: source)( inputs + [partials, meta], template: template, grid: grid, - threadGroup: (32 * nsg, 1, 1), outputShapes: [[1]], outputDTypes: [.int32])[ + threadGroup: (threads, 1, 1), outputShapes: [[1]], outputDTypes: [.int32])[ 0] } else { let outputs = kernel( key: partKey, bindings: bindingCount, kvHeads: kvh, source: source, allocatesScratch: true)( - inputs, template: template, grid: grid, threadGroup: (32 * nsg, 1, 1), + inputs, template: template, grid: grid, threadGroup: (threads, 1, 1), outputShapes: [[1], partialsShape, [metaCount]], outputDTypes: [.int32, .float32, .float32]) group.writeFence = outputs[0] diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/pagedattention.metal b/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/pagedattention.metal index b0e6b1e6d4..e2ea425cba 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/pagedattention.metal +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/pagedattention.metal @@ -485,6 +485,204 @@ inline void paged_attention_part_cached_impl( } } +// Pass A, side-by-side form (PagedAttentionKernel.sideBySideHeadsPerRound). +// When HPT < GQA, the plain form launches GQA/HPT threadgroups for each +// (sequence, kv head, partition), and each one loads the partition's keys +// and values. This form puts those head groups next to each other in one +// threadgroup: head group g owns simdgroups [g * NSG, (g + 1) * NSG) and +// keeps the plain form's token stride, online softmax and simdgroup merge +// order. The head-group count does not enter a head's arithmetic, so each +// partial and (m, l) has the plain form's bits. Merge records go through +// threadgroup memory HRED heads at a time. Dense native callers only: no +// query rotation, packed basis, mask or visible range. +template < + typename T, int D, int S, int GQA, int HPT, int NSG, int PTOK, int HRED, bool HAS_WRITE, + bool HAS_SOFTCAP, typename Cache> +inline void paged_attention_part_side_impl( + const device T* q, + const device T* knew, + const device T* vnew, + thread const Cache& cache, + const device int32_t* tables, + const device int32_t* seqinfo, + const device float* params, + const int kvh, + const int maxp, + const int maxpart, + threadgroup float* q_smem, // [GQA * D] + threadgroup float* red_smem, // [NSG * HRED * (D + 2)] + device float* partials, + device float* meta, + uint3 tgpig, + uint3 tpitg, + uint sgitg, + uint lane +) { + static_assert(GQA % HPT == 0, "HPT must divide GQA"); + static_assert(HPT % HRED == 0, "HRED must divide HPT"); + constexpr int SPLITS = GQA / HPT; // head groups in this threadgroup + constexpr int EPT = D / 32; + constexpr int TG = 32 * NSG * SPLITS; + constexpr int GROUP_TG = 32 * NSG; // one head group: the plain form's threadgroup + constexpr int NSGT = NSG * SPLITS; + constexpr int RSTRIDE = D + 2; + constexpr int ROUNDS = HPT / HRED; + + const int kv_head = tgpig.x; + const int b = tgpig.y; + const int part = tgpig.z; + const int lin = tpitg.x; + const int hgroup = (int)sgitg / NSG; + const int sg = (int)sgitg % NSG; + + const device int32_t* info = seqinfo + b * 8; + const int attend_start = info[0]; + const int attend_len = info[1]; + const int table_len = info[2]; + + const int lo = part * PTOK; + if (lo >= attend_len) { + return; + } + const int hi = min(attend_len, lo + PTOK); + + const device int32_t* table = tables + (size_t)b * (size_t)maxp; + const float softcap = params[0]; + const float scale = params[1]; + + // Fused decode write: head group 0 stores the step's K/V tile, as the + // plain form's hgroup-0 threadgroup does (single writer per byte). + const size_t tile_src = ((size_t)b * (size_t)kvh + (size_t)kv_head) * D; + if (HAS_WRITE && hgroup == 0 && part == (attend_len - 1) / PTOK) { + const int wpage = info[3]; + const int wslot = info[4]; + const auto page = cache.write_page(wpage); + const size_t dst = ((size_t)kv_head * S + (size_t)wslot) * D; + page.template write(dst, knew + tile_src, vnew + tile_src, lin); + } + + // Stage the scaled queries of every query head of this kv head. + const int q_head0 = kv_head * GQA; + const int64_t qr = (int64_t)(kvh * GQA) * D; + const int64_t qh = D; + for (int i = lin; i < GQA * D; i += TG) { + const int64_t offset = (int64_t)b * qr + (q_head0 + i / D) * qh + (i % D); + const float value = float(q[offset]); + q_smem[i] = value * scale; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + const threadgroup float* group_q = q_smem + (size_t)(hgroup * HPT) * D; + + float m[HPT]; + float l[HPT]; + float acc[HPT][EPT]; +#pragma unroll + for (int g = 0; g < HPT; g++) { + m[g] = -FLT_MAX; + l[g] = 0.0f; +#pragma unroll + for (int e = 0; e < EPT; e++) { + acc[g][e] = 0.0f; + } + } + + float kf[EPT]; + float vf[EPT]; + for (int i = lo + sg; i < hi; i += NSG) { + if (HAS_WRITE && i == attend_len - 1) { + load_row(knew + tile_src, lane, kf); + load_row(vnew + tile_src, lane, vf); + } else { + const int pos = attend_start + i; + const int lpage = pos / S; + const int slot = pos % S; + const auto page = cache.read_page(table, lpage, table_len); + const size_t base = ((size_t)kv_head * S + (size_t)slot) * D; + page.template load(base, lane, kf, vf); + } + +#pragma unroll + for (int g = 0; g < HPT; g++) { + float partial = 0.0f; +#pragma unroll + for (int e = 0; e < EPT; e++) { + partial += group_q[g * D + lane * EPT + e] * kf[e]; + } + float qk = simd_sum(partial); + if (HAS_SOFTCAP) { + qk = softcap * precise::tanh(qk / softcap); + } + qk *= M_LOG2E_F; + + const float m_new = max(m[g], qk); + const float corr = exp2(m[g] - m_new); + const float p = exp2(qk - m_new); + l[g] = l[g] * corr + p; +#pragma unroll + for (int e = 0; e < EPT; e++) { + acc[g][e] = acc[g][e] * corr + p * vf[e]; + } + m[g] = m_new; + } + } + + // Publish and merge HRED heads of one head group at a time, the + // simdgroup states in index order as in the plain form. +#pragma unroll + for (int hg = 0; hg < SPLITS; hg++) { +#pragma unroll + for (int r = 0; r < ROUNDS; r++) { + if (hgroup == hg) { + threadgroup float* mine = red_smem + (size_t)(sg * HRED) * RSTRIDE; +#pragma unroll + for (int k = 0; k < HRED; k++) { +#pragma unroll + for (int e = 0; e < EPT; e++) { + mine[k * RSTRIDE + lane * EPT + e] = acc[r * HRED + k][e]; + } + if (lane == 0) { + mine[k * RSTRIDE + D] = m[r * HRED + k]; + mine[k * RSTRIDE + D + 1] = l[r * HRED + k]; + } + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + + for (int k = (int)sgitg; k < HRED; k += NSGT) { + float pm = -FLT_MAX; + for (int s = 0; s < NSG; s++) { + pm = max(pm, red_smem[(size_t)(s * HRED + k) * RSTRIDE + D]); + } + float pl = 0.0f; + for (int s = 0; s < NSG; s++) { + const float ms = red_smem[(size_t)(s * HRED + k) * RSTRIDE + D]; + const float ls = red_smem[(size_t)(s * HRED + k) * RSTRIDE + D + 1]; + pl += ls * exp2(ms - pm); + } + + const size_t slot = + ((size_t)b * (size_t)(kvh * GQA) + (size_t)(q_head0 + hg * HPT + r * HRED + k)) + * (size_t)maxpart + + (size_t)part; + device float* prow = partials + slot * D; + for (int e = (int)lane; e < D; e += 32) { + float v = 0.0f; + for (int s = 0; s < NSG; s++) { + const float ms = red_smem[(size_t)(s * HRED + k) * RSTRIDE + D]; + v += red_smem[(size_t)(s * HRED + k) * RSTRIDE + e] * exp2(ms - pm); + } + prow[e] = v; + } + if (lane == 0) { + meta[slot * 2] = pm; + meta[slot * 2 + 1] = pl; + } + } + threadgroup_barrier(mem_flags::mem_threadgroup); + } + } +} + template < typename T, int D, int S, int GQA, int HPT, int NSG, int PTOK, bool HAS_WRITE, bool HAS_SOFTCAP> diff --git a/Tests/MLXLMTests/Kernel/Cache/PagedSideBySideKernelTests.swift b/Tests/MLXLMTests/Kernel/Cache/PagedSideBySideKernelTests.swift new file mode 100644 index 0000000000..3970233a14 --- /dev/null +++ b/Tests/MLXLMTests/Kernel/Cache/PagedSideBySideKernelTests.swift @@ -0,0 +1,182 @@ +import Foundation +import MLX +import MLXRandom +import Testing + +@testable import MLXLMCommon + +extension KernelTests { + + /// The side-by-side pass A (`paged_attention_part_side_impl`) gives the + /// plain pass A's output and slab bytes: same partitions, same per-head + /// arithmetic and order. + @Suite(.serialized) + struct PagedSideBySideKernelTests { + private func bytes(_ array: MLXArray) -> Data { array.asData(access: .copy).data } + + /// Random pages in a shuffled physical order; one row per entry of + /// `lengths` (cached tokens before this step). + private struct DirectCase { + let kSlab: MLXArray + let vSlab: MLXArray + let tables: MLXArray + let rows: [PagedAttentionKernel.SeqInfoRow] + } + + private func directCase( + dtype: DType, headDim: Int, kvHeads: Int, lengths: [Int], seed: UInt64 + ) -> DirectCase { + let pageSize = 16 + let pages = lengths.map { ($0 + pageSize) / pageSize } + let total = pages.reduce(0, +) + var physical = Array(0 ..< total) + var state = seed + for i in stride(from: total - 1, to: 0, by: -1) { + state = state &* 6_364_136_223_846_793_005 &+ 1_442_695_040_888_963_407 + physical.swapAt(i, Int((state >> 33) % UInt64(i + 1))) + } + let width = max(8, pages.max()!) + var table: [Int32] = [] + var rows: [PagedAttentionKernel.SeqInfoRow] = [] + var next = 0 + for (row, length) in lengths.enumerated() { + let mine = physical[next ..< next + pages[row]].map { Int32($0) } + next += pages[row] + table += mine + Array(repeating: 0, count: width - mine.count) + rows.append( + .init( + attendStart: 0, attendLength: length + 1, tableLength: pages[row], + writePage: mine[length / pageSize], writeSlot: length % pageSize)) + } + let shape = [total, kvHeads, pageSize, headDim] + let k = MLXRandom.normal(shape, key: MLXRandom.key(seed)).asType(dtype) + let v = MLXRandom.normal(shape, key: MLXRandom.key(seed + 1)).asType(dtype) + return DirectCase( + kSlab: k, vSlab: v, tables: MLXArray(table, [lengths.count, width]), rows: rows) + } + + @Test( + arguments: [DType.bfloat16, .float16], + [[256, 2, 6], [512, 1, 8], [128, 1, 16]]) + func directDecodeKeepsThePlainBits(dtype: DType, shape: [Int]) throws { + let (d, kvh, gqa) = (shape[0], shape[1], shape[2]) + let lengths = [700, 1537, 2050] + let b = lengths.count + let q = MLXRandom.normal([b, kvh * gqa, d], key: MLXRandom.key(11)).asType(dtype) + let kNew = MLXRandom.normal([b, kvh, d], key: MLXRandom.key(12)).asType(dtype) + let vNew = MLXRandom.normal([b, kvh, d], key: MLXRandom.key(13)).asType(dtype) + let source = try PagedAttentionResources.loadSourceForCurrentProcess() + for softcap in [false, true] { + let params = MLXArray([ + Float(softcap ? 30 : 0), 1 / Float(d).squareRoot(), 0, 0, 0, 0, 0, 0, + ]) + for write in [false, true] { + var outs: [Data] = [] + var slabs: [(Data, Data)] = [] + for minimum in [0, 1] { + let c = directCase( + dtype: dtype, headDim: d, kvHeads: kvh, lengths: lengths, seed: 21) + let rows = + write + ? c.rows + : c.rows.map { + var r = $0 + r.writePage = 0 + r.writeSlot = 0 + return r + } + let (info, maxLength) = PagedAttentionKernel.seqinfo(rows) + let result = try PagedAttentionKernel.decode( + queries: q, newKeys: write ? kNew : nil, newValues: write ? vNew : nil, + kSlab: c.kSlab, vSlab: c.vSlab, tables: c.tables, seqinfo: info, + maxAttendLength: maxLength, sinks: nil, params: params, + softcap: softcap, + pageSize: 16, writeFence: MLXArray([Int32(0)]), + kernelSource: source, sideBySideMinimumTokens: minimum) + eval(result.out, c.kSlab, c.vSlab) + outs.append(bytes(result.out)) + slabs.append((bytes(c.kSlab), bytes(c.vSlab))) + } + #expect( + outs[0] == outs[1], + "d\(d) gqa\(gqa) \(dtype) softcap \(softcap) write \(write)" + ) + #expect(slabs[0].0 == slabs[1].0 && slabs[0].1 == slabs[1].1) + } + } + } + + @Test(arguments: [DType.bfloat16, .float16]) + func segmentedDecodeKeepsThePlainBits(dtype: DType) throws { + let kind = CBv2LayerKind(attention: .full, headDim: 256, kvHeads: 2, queryHeads: 12) + let pageBytes = 2 * 16 * 256 * 2 * dtype.size + var config = PagedKVPoolConfig( + capacityBytes: 128 << 20, dtype: dtype, maxPrefillChunk: 512, + nominalMaxSequenceLength: 2048, maxBufferLength: 16 << 20) + config.segmentSizeBytes = pageBytes * 5 + let plain = try PagedKVBackend(layerKinds: [kind], config: config) + let side = try PagedKVBackend(layerKinds: [kind], config: config) + var plainStates: [[CBv2SequenceKV?]] = [] + var sideStates: [[CBv2SequenceKV?]] = [] + defer { + for state in plainStates { plain.release(state) } + for state in sideStates { side.release(state) } + } + var plainRows: [PagedSequenceKV] = [] + var sideRows: [PagedSequenceKV] = [] + for (index, count) in [613, 1100].enumerated() { + let a = try plain.makeSequenceState( + layerKinds: [kind], promptLength: 0, maxLength: 2048) + let b = try side.makeSequenceState( + layerKinds: [kind], promptLength: 0, maxLength: 2048) + plainStates.append(a) + sideStates.append(b) + let rowA = try #require(a[0] as? PagedSequenceKV) + let rowB = try #require(b[0] as? PagedSequenceKV) + let k = MLXRandom.normal([2, count, 256], key: MLXRandom.key(UInt64(40 + index))) + .asType(dtype) + let v = MLXRandom.normal([2, count, 256], key: MLXRandom.key(UInt64(50 + index))) + .asType(dtype) + rowA.write(keys: k, values: v) + rowB.write(keys: k, values: v) + plainRows.append(rowA) + sideRows.append(rowB) + } + let plainGroup = plain.pool.group(plainRows[0].groupKey) + let sideGroup = side.pool.group(sideRows[0].groupKey) + let params = MLXArray([Float(0), 0.0625, 0, 0, 0, 0, 0, 0]) + for step in 0 ..< 3 { + let q = MLXRandom.normal([2, 12, 256], key: MLXRandom.key(UInt64(60 + step))) + .asType( + dtype) + let k = MLXRandom.normal([2, 2, 256], key: MLXRandom.key(UInt64(70 + step))).asType( + dtype) + let v = MLXRandom.normal([2, 2, 256], key: MLXRandom.key(UInt64(80 + step))).asType( + dtype) + func rows(_ list: [PagedSequenceKV]) -> [PagedSegmentDispatchPlan.Row] { + list.map { row in + let target = row.prepareDecodeWrite() + return .init( + pages: row.table, + info: row.seqInfoRow( + attending: row.decodeAttendRange, writeTarget: target)) + } + } + let expected = PagedSegmentAttention.decode( + queries: q, newKeys: k, newValues: v, group: plainGroup, rows: rows(plainRows), + sinks: nil, params: params, softcap: false, source: plain.pool.kernelSource, + sideBySideMinimumTokens: 0) + let got = PagedSegmentAttention.decode( + queries: q, newKeys: k, newValues: v, group: sideGroup, rows: rows(sideRows), + sinks: nil, params: params, softcap: false, source: side.pool.kernelSource, + sideBySideMinimumTokens: 1) + eval(expected, got) + #expect(bytes(got) == bytes(expected), "step \(step)") + for (a, b) in zip(plainRows, sideRows) { + #expect(bytes(b.snapshot().keys) == bytes(a.snapshot().keys)) + #expect(bytes(b.snapshot().values) == bytes(a.snapshot().values)) + } + } + } + } +} diff --git a/Tests/MLXLMTests/Unit/Paged/PagedSideBySideRuleTests.swift b/Tests/MLXLMTests/Unit/Paged/PagedSideBySideRuleTests.swift new file mode 100644 index 0000000000..0faeaf6040 --- /dev/null +++ b/Tests/MLXLMTests/Unit/Paged/PagedSideBySideRuleTests.swift @@ -0,0 +1,64 @@ +import Foundation +import Testing + +@testable import MLXLMCommon + +extension UnitTests { + + /// The sizing and the length rule of the side-by-side paged pass A + /// (`paged_attention_part_side_impl`). + @Suite + struct PagedSideBySideRuleTests { + @Test func sizingFollowsTheHeadSplit() throws { + // Qwen 3.5 27B full attention: 3 heads per threadgroup, 2 head groups. + #expect(PagedAttentionKernel.sideBySideHeadsPerRound(headDim: 256, gqa: 6) == 3) + // Gemma 4 global layers: 4 head groups; one merge record head per round fits 32 KB. + #expect(PagedAttentionKernel.sideBySideHeadsPerRound(headDim: 512, gqa: 8) == 1) + #expect(PagedAttentionKernel.sideBySideHeadsPerRound(headDim: 128, gqa: 16) == 8) + // A kv head's query heads already share one threadgroup. + #expect(PagedAttentionKernel.sideBySideHeadsPerRound(headDim: 128, gqa: 8) == nil) + #expect(PagedAttentionKernel.sideBySideHeadsPerRound(headDim: 64, gqa: 4) == nil) + for (d, gqa) in [(256, 6), (512, 8), (128, 16)] { + let hred = try #require( + PagedAttentionKernel.sideBySideHeadsPerRound(headDim: d, gqa: gqa)) + let nsg = try #require( + PagedAttentionKernel.simdgroupsPerThreadgroup(headDim: d, gqa: gqa)) + let hpt = PagedAttentionKernel.headsPerThreadgroup(headDim: d, gqa: gqa) + #expect(32 * nsg * (gqa / hpt) <= PagedAttentionKernel.sideBySideMaxThreads) + #expect( + PagedAttentionKernel.sideBySideThreadgroupBytes( + headDim: d, gqa: gqa, simdgroups: nsg, headsPerRound: hred) + <= PagedAttentionKernel.threadgroupMemoryLimit) + } + } + + /// `sideBySideThreadgroupBytes` mirrors the buffers the side-by-side + /// bodies declare. + @Test func sideBodiesDeclareTheSizedBuffers() { + let bodies = [ + PagedAttentionMSL.partBodySide, PagedAttentionMSL.partBodySideNoWrite, + PagedSegmentAttention.sideBody(bindings: 2), + ] + for body in bodies { + #expect(body.contains("threadgroup float q_smem[GQA * D];")) + #expect(body.contains("threadgroup float red_smem[NSG * HRED * (D + 2)];")) + #expect(body.contains("paged_attention_part_side_impl")) + } + } + + @Test func minimumLengthComesFromTheEnvironment() { + let key = PagedAttentionKernel.sideBySideEnvironmentKey + let fallback = PagedAttentionKernel.sideBySideDefaultTokens + #expect(PagedAttentionKernel.sideBySideMinimum(environment: [:]) == fallback) + #expect(PagedAttentionKernel.sideBySideMinimum(environment: [key: "0"]) == 0) + #expect(PagedAttentionKernel.sideBySideMinimum(environment: [key: "8192"]) == 8192) + #expect(PagedAttentionKernel.sideBySideMinimum(environment: [key: "-1"]) == fallback) + #expect(PagedAttentionKernel.sideBySideMinimum(environment: [key: "x"]) == fallback) + let rule = PagedAttentionKernel.sideBySideForDispatch + #expect(rule(256, 6, 100_000, 0) == nil) + #expect(rule(256, 6, 100, 101) == nil) + #expect(rule(256, 6, 101, 101) == 3) + #expect(rule(128, 8, 100_000, 1) == nil) + } + } +} diff --git a/changelog.d/paged-attention-side-by-side.md b/changelog.d/paged-attention-side-by-side.md new file mode 100644 index 0000000000..43644c5e4f --- /dev/null +++ b/changelog.d/paged-attention-side-by-side.md @@ -0,0 +1,13 @@ +### Opt-in: read a long context once per kv head in paged decode + +- With large head dims, a kv head's query heads split over several pass-A + threadgroups (the Qwen 3.5 27B's full attention, Gemma 4's global layers), + and each threadgroup reads the partition's keys and values. With + `DARKBLOOM_CBV2_PAGED_SIDE_BY_SIDE_TOKENS=`, decode from n attended + tokens runs those head groups side by side in one threadgroup and reads them + once. The partitions and each head's order of operations are unchanged, so + the output has the same bits (checked on GPUs in tests and in the engine at + 65,536 and 131,072 tokens). Off by default: per attention layer it was + faster at long context on an M5 Ultra (1.08x for the 27B shape and 1.22x for + Gemma 4 global layers at 65,536 tokens), but whole decode steps on an M5 Max + were not faster. diff --git a/fork.yaml b/fork.yaml index 269935269c..3f6e8c9656 100644 --- a/fork.yaml +++ b/fork.yaml @@ -134,9 +134,15 @@ def: core (`PagedKernelSmokePlan`); owners that drive their own steps check, finish and discard them through `PagedKVBackend` as the engine does. `docs/runtime-kv-quantization.md` defines the storage and completion contracts. + When a kv head's query heads split over several pass-A threadgroups (large head dims), + decode can run them side by side in one threadgroup (`paged_attention_part_side_impl`, + opt-in: `DARKBLOOM_CBV2_PAGED_SIDE_BY_SIDE_TOKENS=` from n attended tokens): same + partitions and per-head order, so the same bits, and the partition's keys and values + are read once per kv head. Packed pages and verify windows keep the plain form. globs: - "Libraries/MLXLMCommon/ContinuousBatchingV2/Paged/**" - "docs/runtime-kv-quantization.md" + - "changelog.d/paged-attention-side-by-side.md" - title: "Prefix checkpoints" description: | Complete and historical prefix checkpoints: capture, codec, manifest coding/memory, tensor @@ -1020,7 +1026,7 @@ def: The Fork Tests workflow runs them before it stages the Metal library. `Unit/Vision/` tests the media geometry helpers, the decoders of the vision-language configurations, the Qwen4 video prompt expansion, and the Nemotron Super image configuration checks, image preprocessing, vision preparation, video frame sampling, timestamps, tubelet labels and frame grid, and EVS token selection. `Unit/Qwen35A3B/` tests the configuration checks of the Qwen3.5 A3B artifact contract. - `Unit/Paged/` tests that the paged-attention Metal source is looked up once for each process, the page allocator's tiers and placement, and the decode dispatches per step over busy-provider arrival and retirement traces. + `Unit/Paged/` tests that the paged-attention Metal source is looked up once for each process, the page allocator's tiers and placement, the decode dispatches per step over busy-provider arrival and retirement traces, and the sizing and length rule of the side-by-side paged pass A. `Unit/MTP/` tests the owner-wide MTP round bounds over every planned decode width and the deepest round a depth table allows. `Unit/Common/`, `Unit/Embedders/`, `Unit/Tool/ToolCallProcessorFrameStreamingTests.swift`, `Unit/Tool/ToolCallStreamingTests.swift` and `Unit/Tool/ToolCallStreamingDifferentialTests.swift` test the stop-sequence state machine, `UserInput`, the model and embedder containers with stub models, the embedder registries and load errors, the streaming tool-call states and calls exposed while they are generated, the last against the complete-frame parse for seeded template-rendered calls at token-like chunk boundaries. `TestTokenizer.swift` keeps the random test tokenizer that upstream removed (a86ee6a7); many fork tests use it. @@ -1041,7 +1047,7 @@ def: `Kernel/Common/` tests model container generation, the embedder factory load, the wired memory measurement and the image array input. `Kernel/LLM/` also tests a table of dense text models (MiniCPM, OLMo 2, GLM-4, Gemma, Starcoder 2, Phi, ERNIE 4.5, Cohere, Lille, MiMo and the Gemma 4 wrapper) and the DeepSeek-V4 MTP head. `Kernel/LLM/ClassicTextModelForwardPassTests.swift` runs the table checks on the configuration variants of SmolLM3, Exaone 4, OLMoE, OLMo 3, PhiMoE, Phi-3, NanoChat, Granite, OpenELM and Gemma 2. - `Kernel/LLM/` tests Laguna, Qwen3-Next, Qwen3-MoE, Qwen 2, Qwen 3, Qwen 3.5 MoE, DeepSeek V4, BitNet, Gemma 3n and the loader of the Nemotron-H 3.5 MTP head. `Kernel/Cache/` tests the KV caches, the masks, the quantized attention, the fused causal prompt route of the CBv2 layer caches, and the paged KV group's page bookkeeping under random operations. `Kernel/RoPE/` tests the RoPE scaling types against reference rotations. + `Kernel/LLM/` tests Laguna, Qwen3-Next, Qwen3-MoE, Qwen 2, Qwen 3, Qwen 3.5 MoE, DeepSeek V4, BitNet, Gemma 3n and the loader of the Nemotron-H 3.5 MTP head. `Kernel/Cache/` tests the KV caches, the masks, the quantized attention, the fused causal prompt route of the CBv2 layer caches, the paged KV group's page bookkeeping under random operations, and that the side-by-side paged pass A gives the plain pass A's output and slab bytes. `Kernel/RoPE/` tests the RoPE scaling types against reference rotations. More text cases cover Apertus, InternLM2, Mistral 3 text, MiniMax, Bailing MoE, GLM-4 MoE, AfMoE, LFM2, LFM2 MoE, MiMo V2 Flash, GLM-4 MoE Lite, Granite MoE hybrid, Falcon H1, Jamba, Baichuan M1 and DeepSeek V3. `Kernel/Vision/` tests vision-language models (Qwen2-VL, Qwen2.5-VL, GLM-OCR, LFM2-VL, Idefics3, Mistral 3, Pixtral, Gemma 3, FastVLM, PaliGemma) with random pixels, and the interpolation Metal kernels. `Kernel/Quantization/` tests the ModelOpt NVFP4 and FP8 projections, including the opt-in lazy decode and lazy FP8 helpers, the graph paths against the eager reference, both activation overflow policies, and the Nemotron Super E4M3 codec, FP8 KV cache and rewindable MTP FP8 KV history. `ModelOptGraphBenchmarkTests` times one Super layer of each kind at the dimensions of a real `config.json` only when `MODELOPT_GRAPH_BENCH_CONFIG` is set.