From 705b80a0c3b1cdb49fb40ff9aa561983b7857d35 Mon Sep 17 00:00:00 2001 From: Ronald Mannak Date: Thu, 5 Nov 2026 19:45:34 -0800 Subject: [PATCH 1/6] Add an optional standalone decode benchmark --- Benchmarks/DecodeBench/Package.swift | 22 ++ .../Sources/decodebench/main.swift | 224 ++++++++++++++++++ 2 files changed, 246 insertions(+) create mode 100644 Benchmarks/DecodeBench/Package.swift create mode 100644 Benchmarks/DecodeBench/Sources/decodebench/main.swift diff --git a/Benchmarks/DecodeBench/Package.swift b/Benchmarks/DecodeBench/Package.swift new file mode 100644 index 0000000000..9595a1f0c3 --- /dev/null +++ b/Benchmarks/DecodeBench/Package.swift @@ -0,0 +1,22 @@ +// swift-tools-version: 6.0 +import PackageDescription + +// Decode throughput of a checkout, built in release. MLX_SWIFT_LM_PATH points the +// benchmark at another checkout, so a change is timed against its base with one build tree. +let library = Context.environment["MLX_SWIFT_LM_PATH"] ?? "../.." + +let package = Package( + name: "DecodeBench", + platforms: [.macOS(.v14)], + dependencies: [.package(name: "mlx-swift-lm", path: library)], + targets: [ + .executableTarget( + name: "decodebench", + dependencies: [ + .product(name: "MLXLLM", package: "mlx-swift-lm"), + .product(name: "MLXLMCommon", package: "mlx-swift-lm"), + .product(name: "BenchmarkHelpers", package: "mlx-swift-lm"), + ] + ) + ] +) diff --git a/Benchmarks/DecodeBench/Sources/decodebench/main.swift b/Benchmarks/DecodeBench/Sources/decodebench/main.swift new file mode 100644 index 0000000000..73f5f66919 --- /dev/null +++ b/Benchmarks/DecodeBench/Sources/decodebench/main.swift @@ -0,0 +1,224 @@ +// Copyright © 2026 Apple Inc. + +// Decode throughput and time to first token on a local model, as medians over rounds: the +// single-sequence `TokenIterator`, and `BatchTokenIterator` at one and four rows. Decode is +// timed after the prefill and the first token; the time to first token covers the prefill. +// Every path must repeat its tokens in every round; how far the paths agree with each other +// is reported. +// +// swift run -c release --package-path Benchmarks/DecodeBench decodebench \ +// [decode tokens: 128] [rounds: 5] [prompt tokens: 145] [sampler: greedy|topp|categorical] +// +// Built with `-Xswiftc -DSINGLE_ONLY` it times `TokenIterator` alone, so it also builds +// against a checkout without `BatchTokenIterator`. + +import BenchmarkHelpers +import Foundation +import MLX +import MLXLLM +import MLXLMCommon + +let arguments = CommandLine.arguments +guard arguments.count > 1 else { + print("usage: decodebench [decode tokens] [rounds] [prompt tokens] [sampler]") + exit(1) +} +let modelDirectory = URL(fileURLWithPath: arguments[1]) +let decodeTokens = arguments.count > 2 ? Int(arguments[2]) ?? 128 : 128 +let rounds = arguments.count > 3 ? Int(arguments[3]) ?? 5 : 5 +let promptLength = arguments.count > 4 ? Int(arguments[4]) ?? 145 : 145 +let samplerName = arguments.count > 5 ? arguments[5] : "greedy" + +let context = try await LLMModelFactory.shared.load( + from: modelDirectory, using: NoOpTokenizerLoader()) +let model = context.model +print("model: \(modelDirectory.lastPathComponent)") +print( + "prompt tokens: \(promptLength), decode tokens: \(decodeTokens), rounds: \(rounds), " + + "sampler: \(samplerName)") + +/// A fresh sampler per run, seeded, so every run of a path draws the same tokens. +@MainActor func makeSampler() -> LogitSampler { + switch samplerName { + case "topp": return TopPSampler(temperature: 0.8, topP: 0.9, seed: 7) + case "categorical": return CategoricalSampler(temperature: 0.8, seed: 7) + case "greedy": return ArgMaxSampler() + default: + print("unknown sampler \(samplerName): greedy, topp or categorical") + exit(1) + } +} + +/// A fixed pseudo-random prompt, so every round and every checkout decodes the same tokens. +@MainActor func prompt(seed: UInt64) -> [Int32] { + var state = seed &* 6_364_136_223_846_793_005 &+ 1_442_695_040_888_963_407 + return (0 ..< promptLength).map { _ in + state = state &* 6_364_136_223_846_793_005 &+ 1_442_695_040_888_963_407 + return Int32(1000 + (state >> 33) % 20000) + } +} + +func seconds(since start: ContinuousClock.Instant) -> Double { + let elapsed = ContinuousClock.now - start + return Double(elapsed.components.seconds) + Double(elapsed.components.attoseconds) / 1e18 +} + +func median(_ values: [Double]) -> Double { + let sorted = values.sorted() + let middle = sorted.count / 2 + return sorted.count % 2 == 0 ? (sorted[middle - 1] + sorted[middle]) / 2 : sorted[middle] +} + +struct Run { + /// Decode tokens per second, counting one row. + let tokensPerSecond: Double + /// Seconds from the start of the run to the first token of every row: the prefill. + let firstToken: Double + /// Every row's tokens, the first one included. + let tokens: [[Int]] +} + +/// Prefills the prompt, then times `decodeTokens` steps of `TokenIterator`. +@MainActor func runSingle(prompt: [Int32]) throws -> Run { + defer { Stream.defaultStream.synchronize() } + let start = ContinuousClock.now + var iterator = try TokenIterator( + input: LMInput(tokens: MLXArray(prompt)), model: model, processor: nil, + sampler: makeSampler(), maxTokens: decodeTokens + 1) + var tokens: [Int] = [] + // The first token comes from the prefill; the steps after it are the decode. + if let first = iterator.next() { tokens.append(first) } + let firstToken = seconds(since: start) + let decodeStart = ContinuousClock.now + while let token = iterator.next() { tokens.append(token) } + return Run( + tokensPerSecond: Double(decodeTokens) / seconds(since: decodeStart), + firstToken: firstToken, tokens: [tokens]) +} + +#if !SINGLE_ONLY +/// Queues the prompts in a `BatchTokenIterator`, takes the first step (the prefill and +/// the first token) and times `decodeTokens` further steps. +@MainActor func runBatched(prompts: [[Int32]]) throws -> Run { + defer { Stream.defaultStream.synchronize() } + let start = ContinuousClock.now + var iterator = BatchTokenIterator( + model: model, sampler: makeSampler(), maxTokens: decodeTokens + 1) + let uids = iterator.insert(prompts: prompts.map { $0.map { Int($0) } }) + var tokens = [[Int]](repeating: [], count: prompts.count) + func record(_ responses: [BatchTokenIterator.Response]) { + for response in responses { + tokens[uids.firstIndex(of: response.uid)!].append(response.token) + } + } + record(try iterator.next()) + let firstToken = seconds(since: start) + let decodeStart = ContinuousClock.now + while true { + let responses = try iterator.next() + if responses.isEmpty { break } + record(responses) + } + return Run( + tokensPerSecond: Double(decodeTokens) / seconds(since: decodeStart), + firstToken: firstToken, tokens: tokens) +} +#endif + +let singlePrompt = prompt(seed: 1) +let fourPrompts = (1 ... 4).map { prompt(seed: UInt64($0)) } + +// Warm up every path once so kernel compilation is not timed. +_ = try runSingle(prompt: singlePrompt) +#if !SINGLE_ONLY +_ = try runBatched(prompts: [singlePrompt]) +_ = try runBatched(prompts: fourPrompts) +#endif + +/// The tokens of a path in its first round, to check every later round against. +var references: [String: [[Int]]] = [:] +var mismatchedRounds: [Int] = [] +@MainActor func check(_ path: String, _ run: Run, round: Int) { + if let reference = references[path] { + if run.tokens != reference, !mismatchedRounds.contains(round) { + mismatchedRounds.append(round) + } + } else { + references[path] = run.tokens + } +} +@MainActor func format(_ run: Run, rows: Int) -> String { + let perRow = String(format: "%.2f tok/s", run.tokensPerSecond) + let rate = + rows == 1 + ? perRow + : perRow + String(format: " per row, %.2f total", Double(rows) * run.tokensPerSecond) + return rate + String(format: " (ttft %.0f ms)", 1000 * run.firstToken) +} + +var single: [Double] = [] +var singleFirst: [Double] = [] +var batchOfOne: [Double] = [] +var batchOfOneFirst: [Double] = [] +var batchOfFour: [Double] = [] +var batchOfFourFirst: [Double] = [] +var agreement: [Int] = [] +var rowAgreement: [Int] = [] +for round in 0 ..< rounds { + #if SINGLE_ONLY + let plain = try runSingle(prompt: singlePrompt) + single.append(plain.tokensPerSecond) + singleFirst.append(plain.firstToken) + check("single", plain, round: round + 1) + print("round \(round + 1) single \(format(plain, rows: 1))") + #else + // Alternate the order so a thermal or background-load slope lands on both paths. + let batchedFirst = round % 2 == 1 + let batched = batchedFirst ? try runBatched(prompts: [singlePrompt]) : nil + let plain = try runSingle(prompt: singlePrompt) + let one = try batched ?? runBatched(prompts: [singlePrompt]) + let four = try runBatched(prompts: fourPrompts) + + single.append(plain.tokensPerSecond) + singleFirst.append(plain.firstToken) + batchOfOne.append(one.tokensPerSecond) + batchOfOneFirst.append(one.firstToken) + batchOfFour.append(four.tokensPerSecond) + batchOfFourFirst.append(four.firstToken) + // Each path must repeat itself across rounds exactly. Between paths the arithmetic + // can differ (four rows run other matmul shapes than one, and a sampler draws a + // batch from one random stream), so their streams can part ways; how far they agree + // is reported, not asserted. + check("single", plain, round: round + 1) + check("batch(1)", one, round: round + 1) + check("batch(4)", four, round: round + 1) + agreement.append(zip(plain.tokens[0], one.tokens[0]).prefix { $0 == $1 }.count) + rowAgreement.append(zip(one.tokens[0], four.tokens[0]).prefix { $0 == $1 }.count) + print( + "round \(round + 1) single \(format(plain, rows: 1)) batch(1) \(format(one, rows: 1))" + + " batch(4) \(format(four, rows: 4)) (\(batchedFirst ? "batched" : "single") first)" + ) + #endif + Memory.clearCache() +} +#if SINGLE_ONLY +print( + String( + format: "median single %.2f tok/s (ttft %.0f ms)", median(single), + 1000 * median(singleFirst))) +#else +print( + String( + format: + "median single %.2f tok/s (ttft %.0f ms) batch(1) %.2f tok/s (ttft %.0f ms) " + + "batch(4) %.2f tok/s per row, %.2f total (ttft %.0f ms)", + median(single), 1000 * median(singleFirst), median(batchOfOne), + 1000 * median(batchOfOneFirst), median(batchOfFour), 4 * median(batchOfFour), + 1000 * median(batchOfFourFirst))) +print( + "single and batch(1) agree on the first \(agreement.min() ?? 0) of \(decodeTokens + 1) tokens; " + + "batch(1) and row 0 of batch(4) on the first \(rowAgreement.min() ?? 0)") +#endif +print( + "each path repeats its tokens in every round: \(mismatchedRounds.isEmpty)" + + (mismatchedRounds.isEmpty ? "" : ", not in rounds \(mismatchedRounds)")) From 3a18939292739c4e628ad680e16abb135b6a7ab8 Mon Sep 17 00:00:00 2001 From: Ronald Mannak Date: Fri, 6 Nov 2026 11:42:24 -0800 Subject: [PATCH 2/6] Add batch sizes and mixed prompt lengths to the decode benchmark Batch sizes are now a comma-separated argument, 1,4,8 by default, each timed and reported per row and in total. A mixed-lengths option gives the rows of a batch prompts that shrink evenly to a sixth of the full length, so all rows but the first are left-padded. Every batch row is compared with an untimed single-sequence run of its own prompt. This replaces the two fixed comparisons (single against batch of one, batch of one against row 0 of the batch of four) with one per row for every size. Agreement stays reported, not asserted. The alternating order now puts every batch size before or after the single run. The SINGLE_ONLY build is unchanged. Co-Authored-By: Claude Opus 5.5 --- .../Sources/decodebench/main.swift | 163 ++++++++++++------ 1 file changed, 109 insertions(+), 54 deletions(-) diff --git a/Benchmarks/DecodeBench/Sources/decodebench/main.swift b/Benchmarks/DecodeBench/Sources/decodebench/main.swift index 73f5f66919..6a82927cab 100644 --- a/Benchmarks/DecodeBench/Sources/decodebench/main.swift +++ b/Benchmarks/DecodeBench/Sources/decodebench/main.swift @@ -1,13 +1,20 @@ // Copyright © 2026 Apple Inc. // Decode throughput and time to first token on a local model, as medians over rounds: the -// single-sequence `TokenIterator`, and `BatchTokenIterator` at one and four rows. Decode is -// timed after the prefill and the first token; the time to first token covers the prefill. -// Every path must repeat its tokens in every round; how far the paths agree with each other -// is reported. +// single-sequence `TokenIterator`, and `BatchTokenIterator` at every batch size asked for. +// Decode is timed after the prefill and the first token; the time to first token covers the +// prefill. Every path must repeat its tokens in every round; how far each batch row agrees +// with a single-sequence run of the same prompt is reported. // // swift run -c release --package-path Benchmarks/DecodeBench decodebench \ -// [decode tokens: 128] [rounds: 5] [prompt tokens: 145] [sampler: greedy|topp|categorical] +// [decode tokens: 128] [rounds: 5] [prompt tokens: 145] [sampler: greedy|topp|categorical] \ +// [batch sizes: 1,4,8] [prompt lengths: equal|mixed] +// +// With `mixed` prompt lengths, the rows of a batch get prompts that shrink evenly from the full +// length to a sixth of it, so every row but the first is left-padded. With the greedy sampler, +// a row whose positions or padding mask are wrong parts ways with its single-sequence run at +// once, while correct rows agree until the different matmul shapes of a batch round a near tie +// the other way. // // Built with `-Xswiftc -DSINGLE_ONLY` it times `TokenIterator` alone, so it also builds // against a checkout without `BatchTokenIterator`. @@ -18,24 +25,43 @@ import MLX import MLXLLM import MLXLMCommon +let usage = + "usage: decodebench [decode tokens] [rounds] [prompt tokens] [sampler] " + + "[batch sizes] [prompt lengths]" let arguments = CommandLine.arguments guard arguments.count > 1 else { - print("usage: decodebench [decode tokens] [rounds] [prompt tokens] [sampler]") + print(usage) exit(1) } let modelDirectory = URL(fileURLWithPath: arguments[1]) let decodeTokens = arguments.count > 2 ? Int(arguments[2]) ?? 128 : 128 -let rounds = arguments.count > 3 ? Int(arguments[3]) ?? 5 : 5 +let rounds = max(1, arguments.count > 3 ? Int(arguments[3]) ?? 5 : 5) let promptLength = arguments.count > 4 ? Int(arguments[4]) ?? 145 : 145 let samplerName = arguments.count > 5 ? arguments[5] : "greedy" +let batchSizes = Set( + (arguments.count > 6 ? arguments[6] : "1,4,8").split(separator: ",").compactMap { Int($0) } + .filter { $0 > 0 } +).sorted() +let lengthsName = arguments.count > 7 ? arguments[7] : "equal" +guard !batchSizes.isEmpty, ["equal", "mixed"].contains(lengthsName) else { + print(usage) + print("batch sizes are a comma-separated list such as 1,4,8; prompt lengths equal or mixed") + exit(1) +} let context = try await LLMModelFactory.shared.load( from: modelDirectory, using: NoOpTokenizerLoader()) let model = context.model print("model: \(modelDirectory.lastPathComponent)") +#if SINGLE_ONLY print( "prompt tokens: \(promptLength), decode tokens: \(decodeTokens), rounds: \(rounds), " + "sampler: \(samplerName)") +#else +print( + "prompt tokens: \(promptLength), decode tokens: \(decodeTokens), rounds: \(rounds), " + + "sampler: \(samplerName), batch sizes: \(batchSizes), prompt lengths: \(lengthsName)") +#endif /// A fresh sampler per run, seeded, so every run of a path draws the same tokens. @MainActor func makeSampler() -> LogitSampler { @@ -50,9 +76,9 @@ print( } /// A fixed pseudo-random prompt, so every round and every checkout decodes the same tokens. -@MainActor func prompt(seed: UInt64) -> [Int32] { +@MainActor func prompt(seed: UInt64, length: Int = promptLength) -> [Int32] { var state = seed &* 6_364_136_223_846_793_005 &+ 1_442_695_040_888_963_407 - return (0 ..< promptLength).map { _ in + return (0 ..< length).map { _ in state = state &* 6_364_136_223_846_793_005 &+ 1_442_695_040_888_963_407 return Int32(1000 + (state >> 33) % 20000) } @@ -123,16 +149,39 @@ struct Run { tokensPerSecond: Double(decodeTokens) / seconds(since: decodeStart), firstToken: firstToken, tokens: tokens) } + +/// The prompts of a batch: row 0 is the single-sequence prompt and every other row has its +/// own. With mixed lengths the rows shrink evenly to a sixth of the full length. +@MainActor func prompts(rows: Int) -> [[Int32]] { + (0 ..< rows).map { row in + guard lengthsName == "mixed", rows > 1 else { return prompt(seed: UInt64(row + 1)) } + let shortest = max(1, promptLength / 6) + let length = promptLength - (promptLength - shortest) * row / (rows - 1) + return prompt(seed: UInt64(row + 1), length: length) + } +} #endif let singlePrompt = prompt(seed: 1) -let fourPrompts = (1 ... 4).map { prompt(seed: UInt64($0)) } // Warm up every path once so kernel compilation is not timed. _ = try runSingle(prompt: singlePrompt) #if !SINGLE_ONLY -_ = try runBatched(prompts: [singlePrompt]) -_ = try runBatched(prompts: fourPrompts) +let batches = batchSizes.map { (rows: $0, prompts: prompts(rows: $0)) } +for batch in batches { + _ = try runBatched(prompts: batch.prompts) + if lengthsName == "mixed", batch.rows > 1 { + print("batch(\(batch.rows)) prompt lengths: \(batch.prompts.map(\.count))") + } +} + +/// Every row's prompt run alone, untimed, to compare the batch rows with. +var singleTokens: [[Int32]: [Int]] = [:] +for batch in batches { + for prompt in batch.prompts where singleTokens[prompt] == nil { + singleTokens[prompt] = try runSingle(prompt: prompt).tokens[0] + } +} #endif /// The tokens of a path in its first round, to check every later round against. @@ -158,12 +207,12 @@ var mismatchedRounds: [Int] = [] var single: [Double] = [] var singleFirst: [Double] = [] -var batchOfOne: [Double] = [] -var batchOfOneFirst: [Double] = [] -var batchOfFour: [Double] = [] -var batchOfFourFirst: [Double] = [] -var agreement: [Int] = [] -var rowAgreement: [Int] = [] +#if !SINGLE_ONLY +var batchRates: [Int: [Double]] = [:] +var batchFirst: [Int: [Double]] = [:] +/// Per batch size, the fewest leading tokens each row shares with its single-sequence run. +var rowAgreement: [Int: [Int]] = [:] +#endif for round in 0 ..< rounds { #if SINGLE_ONLY let plain = try runSingle(prompt: singlePrompt) @@ -172,52 +221,58 @@ for round in 0 ..< rounds { check("single", plain, round: round + 1) print("round \(round + 1) single \(format(plain, rows: 1))") #else - // Alternate the order so a thermal or background-load slope lands on both paths. + // Alternate the order so a thermal or background-load slope lands on every path. let batchedFirst = round % 2 == 1 - let batched = batchedFirst ? try runBatched(prompts: [singlePrompt]) : nil + var runs: [Run] = [] + if batchedFirst { runs = try batches.map { try runBatched(prompts: $0.prompts) } } let plain = try runSingle(prompt: singlePrompt) - let one = try batched ?? runBatched(prompts: [singlePrompt]) - let four = try runBatched(prompts: fourPrompts) + if !batchedFirst { runs = try batches.map { try runBatched(prompts: $0.prompts) } } single.append(plain.tokensPerSecond) singleFirst.append(plain.firstToken) - batchOfOne.append(one.tokensPerSecond) - batchOfOneFirst.append(one.firstToken) - batchOfFour.append(four.tokensPerSecond) - batchOfFourFirst.append(four.firstToken) - // Each path must repeat itself across rounds exactly. Between paths the arithmetic - // can differ (four rows run other matmul shapes than one, and a sampler draws a - // batch from one random stream), so their streams can part ways; how far they agree - // is reported, not asserted. check("single", plain, round: round + 1) - check("batch(1)", one, round: round + 1) - check("batch(4)", four, round: round + 1) - agreement.append(zip(plain.tokens[0], one.tokens[0]).prefix { $0 == $1 }.count) - rowAgreement.append(zip(one.tokens[0], four.tokens[0]).prefix { $0 == $1 }.count) - print( - "round \(round + 1) single \(format(plain, rows: 1)) batch(1) \(format(one, rows: 1))" - + " batch(4) \(format(four, rows: 4)) (\(batchedFirst ? "batched" : "single") first)" - ) + var line = "round \(round + 1) single \(format(plain, rows: 1))" + for (batch, run) in zip(batches, runs) { + batchRates[batch.rows, default: []].append(run.tokensPerSecond) + batchFirst[batch.rows, default: []].append(run.firstToken) + // Each path must repeat itself across rounds exactly. Against a row's single run the + // arithmetic can differ (a batch runs other matmul shapes, and a sampler draws a batch + // from one random stream), so their streams can part ways; how far they agree is + // reported, not asserted. + check("batch(\(batch.rows))", run, round: round + 1) + let agreement = zip(batch.prompts, run.tokens).map { prompt, tokens in + zip(singleTokens[prompt]!, tokens).prefix { $0 == $1 }.count + } + rowAgreement[batch.rows] = + rowAgreement[batch.rows].map { zip($0, agreement).map { min($0, $1) } } ?? agreement + line += " batch(\(batch.rows)) \(format(run, rows: batch.rows))" + } + print(line + " (\(batchedFirst ? "batched" : "single") first)") #endif Memory.clearCache() } -#if SINGLE_ONLY print( - String( - format: "median single %.2f tok/s (ttft %.0f ms)", median(single), - 1000 * median(singleFirst))) -#else -print( - String( - format: - "median single %.2f tok/s (ttft %.0f ms) batch(1) %.2f tok/s (ttft %.0f ms) " - + "batch(4) %.2f tok/s per row, %.2f total (ttft %.0f ms)", - median(single), 1000 * median(singleFirst), median(batchOfOne), - 1000 * median(batchOfOneFirst), median(batchOfFour), 4 * median(batchOfFour), - 1000 * median(batchOfFourFirst))) -print( - "single and batch(1) agree on the first \(agreement.min() ?? 0) of \(decodeTokens + 1) tokens; " - + "batch(1) and row 0 of batch(4) on the first \(rowAgreement.min() ?? 0)") + "median single " + + format( + Run(tokensPerSecond: median(single), firstToken: median(singleFirst), tokens: []), + rows: 1)) +#if !SINGLE_ONLY +for batch in batches { + let run = Run( + tokensPerSecond: median(batchRates[batch.rows]!), + firstToken: median(batchFirst[batch.rows]!), tokens: []) + print("median batch(\(batch.rows)) " + format(run, rows: batch.rows)) +} +for batch in batches { + let agreement = rowAgreement[batch.rows]! + print( + "batch(\(batch.rows)) rows agree with their single runs on the first " + + "\(agreement.min()!) of \(decodeTokens + 1) tokens" + + (batch.rows == 1 ? "" : "; per row \(agreement)")) +} +if samplerName != "greedy" { + print("(a batch draws every row from one random stream, so rows can part ways at once)") +} #endif print( "each path repeats its tokens in every round: \(mismatchedRounds.isEmpty)" From 5c3e71ec30a103903410796918fd85c942b39197 Mon Sep 17 00:00:00 2001 From: Ronald Mannak Date: Sat, 7 Nov 2026 10:17:29 -0800 Subject: [PATCH 3/6] Abort DecodeBench when a batch row fails to join BatchTokenIterator now reports a row that cannot join as a .failed event instead of throwing from next(). DecodeBench ignored that event, so a partial batch could report a rate for rows it never ran. It now rethrows the error, as the run failed before. Co-Authored-By: Claude Opus 5.5 --- .../DecodeBench/Sources/decodebench/main.swift | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/Benchmarks/DecodeBench/Sources/decodebench/main.swift b/Benchmarks/DecodeBench/Sources/decodebench/main.swift index f1ea7069a7..f28bf56b43 100644 --- a/Benchmarks/DecodeBench/Sources/decodebench/main.swift +++ b/Benchmarks/DecodeBench/Sources/decodebench/main.swift @@ -132,16 +132,22 @@ struct Run { model: model, sampler: makeSampler(), maxTokens: decodeTokens + 1) let ids = iterator.insert(prompts: prompts.map { $0.map { Int($0) } }) var tokens = [[Int]](repeating: [], count: prompts.count) - func record(_ events: [BatchEvent]?) { - for case .token(let id, let token) in events ?? [] { - tokens[ids.firstIndex(of: id)!].append(token) + // A row that cannot join ends the run, as an admission error did before the iterator + // reported it as an event: a partial batch would report a rate for rows it never ran. + func record(_ events: [BatchEvent]?) throws { + for event in events ?? [] { + switch event { + case .token(let id, let token): tokens[ids.firstIndex(of: id)!].append(token) + case .failed(_, let error): throw error + case .prefill, .finished: break + } } } - record(try iterator.next()) + try record(try iterator.next()) let firstToken = seconds(since: start) let decodeStart = ContinuousClock.now while let events = try iterator.next() { - record(events) + try record(events) } return Run( tokensPerSecond: Double(decodeTokens) / seconds(since: decodeStart), From b2269b29195eff9b33f020d48b4def89b809771c Mon Sep 17 00:00:00 2001 From: Ronald Mannak Date: Sat, 7 Nov 2026 13:04:14 -0800 Subject: [PATCH 4/6] Time DecodeBench batches by events: first token and steady decode With resumable prefill (PR 91), a BatchTokenIterator step can feed a prefill chunk instead of yielding tokens, and rows join one step apart. DecodeBench timed the first next() as the prefill and every later step as decode, which no longer holds. The time to first token now ends at the first .token event. The decode rate counts only the steady steps: every row decodes, none of them its first token, and no prefill chunk runs. Steps that decode while also feeding a prefill chunk are reported apart, as overlap steps with their mean time. For a model that prefills whole prompts the numbers mean what they meant before. Co-Authored-By: Claude Opus 5.5 --- .../Sources/decodebench/main.swift | 76 ++++++++++++++----- 1 file changed, 56 insertions(+), 20 deletions(-) diff --git a/Benchmarks/DecodeBench/Sources/decodebench/main.swift b/Benchmarks/DecodeBench/Sources/decodebench/main.swift index f28bf56b43..ce717062a5 100644 --- a/Benchmarks/DecodeBench/Sources/decodebench/main.swift +++ b/Benchmarks/DecodeBench/Sources/decodebench/main.swift @@ -3,7 +3,9 @@ // Decode throughput and time to first token on a local model, as medians over rounds: the // single-sequence `TokenIterator`, and `BatchTokenIterator` at every batch size asked for. // Decode is timed after the prefill and the first token; the time to first token covers the -// prefill. Every path must repeat its tokens in every round; how far each batch row agrees +// prefill. A batch's decode rate counts only the steps in which every row decodes and no prompt +// is prefilled; with resumable prefill the steps that also feed a prefill chunk are reported +// apart. Every path must repeat its tokens in every round; how far each batch row agrees // with a single-sequence run of the same prompt is reported. // // swift run -c release --package-path Benchmarks/DecodeBench decodebench \ @@ -98,10 +100,13 @@ func median(_ values: [Double]) -> Double { struct Run { /// Decode tokens per second, counting one row. let tokensPerSecond: Double - /// Seconds from the start of the run to the first token of every row: the prefill. + /// Seconds from the start of the run to the first token: the prefill. let firstToken: Double /// Every row's tokens, the first one included. let tokens: [[Int]] + /// Batch steps that decoded while also feeding a prefill chunk, and their total seconds. + var overlapSteps = 0 + var overlapSeconds = 0.0 } /// Prefills the prompt, then times `decodeTokens` steps of `TokenIterator`. @@ -123,8 +128,11 @@ struct Run { } #if !SINGLE_ONLY -/// Queues the prompts in a `BatchTokenIterator`, takes the first step (the prefill and -/// the first token) and times `decodeTokens` further steps. +/// Queues the prompts in a `BatchTokenIterator` and runs it to the end. The time to first +/// token ends at the first `.token` event. The decode rate counts the steady steps only: every +/// row decodes, none of them its first token, and no prefill chunk runs. With resumable +/// prefill the rows join one step apart, so the steps that also feed a prefill chunk are +/// reported apart from it. @MainActor func runBatched(prompts: [[Int32]]) throws -> Run { defer { Stream.defaultStream.synchronize() } let start = ContinuousClock.now @@ -132,26 +140,48 @@ struct Run { model: model, sampler: makeSampler(), maxTokens: decodeTokens + 1) let ids = iterator.insert(prompts: prompts.map { $0.map { Int($0) } }) var tokens = [[Int]](repeating: [], count: prompts.count) - // A row that cannot join ends the run, as an admission error did before the iterator - // reported it as an event: a partial batch would report a rate for rows it never ran. - func record(_ events: [BatchEvent]?) throws { - for event in events ?? [] { + var firstToken: Double? + var steadySteps = 0 + var steadySeconds = 0.0 + var run = Run(tokensPerSecond: 0, firstToken: 0, tokens: []) + while true { + let stepStart = ContinuousClock.now + guard let events = try iterator.next() else { break } + let stepSeconds = seconds(since: stepStart) + var decoded = 0 + var prefilled = false + var firstTokens = false + for event in events { switch event { - case .token(let id, let token): tokens[ids.firstIndex(of: id)!].append(token) - case .failed(_, let error): throw error - case .prefill, .finished: break + case .token(let id, let token): + let row = ids.firstIndex(of: id)! + firstTokens = firstTokens || tokens[row].isEmpty + tokens[row].append(token) + decoded += 1 + case .prefill: + prefilled = true + // A row that cannot join ends the run, as an admission error did before the + // iterator reported it as an event: a partial batch would report a rate for rows + // it never ran. + case .failed(_, let error): + throw error + case .finished: + break } } - } - try record(try iterator.next()) - let firstToken = seconds(since: start) - let decodeStart = ContinuousClock.now - while let events = try iterator.next() { - try record(events) + if decoded > 0, firstToken == nil { firstToken = seconds(since: start) } + if prefilled, decoded > 0 { + run.overlapSteps += 1 + run.overlapSeconds += stepSeconds + } else if !prefilled, !firstTokens, decoded == prompts.count { + steadySteps += 1 + steadySeconds += stepSeconds + } } return Run( - tokensPerSecond: Double(decodeTokens) / seconds(since: decodeStart), - firstToken: firstToken, tokens: tokens) + tokensPerSecond: Double(steadySteps) / steadySeconds, + firstToken: firstToken ?? seconds(since: start), tokens: tokens, + overlapSteps: run.overlapSteps, overlapSeconds: run.overlapSeconds) } /// The prompts of a batch: row 0 is the single-sequence prompt and every other row has its @@ -206,7 +236,13 @@ var mismatchedRounds: [Int] = [] rows == 1 ? perRow : perRow + String(format: " per row, %.2f total", Double(rows) * run.tokensPerSecond) - return rate + String(format: " (ttft %.0f ms)", 1000 * run.firstToken) + let overlap = + run.overlapSteps == 0 + ? "" + : String( + format: ", %d overlap steps at %.1f ms", run.overlapSteps, + 1000 * run.overlapSeconds / Double(run.overlapSteps)) + return rate + String(format: " (ttft %.0f ms", 1000 * run.firstToken) + overlap + ")" } var single: [Double] = [] From c02bbbc68ac16284246d1ce6fc1086317014033a Mon Sep 17 00:00:00 2001 From: Ronald Mannak Date: Sat, 7 Nov 2026 13:18:06 -0800 Subject: [PATCH 5/6] Stop DecodeBench when a batch has no steady decode steps With resumable prefill the rows join one step apart, so a short run (for example 4 decode tokens at batch size 8) can end its first rows before the last one decodes. No step then decodes every row without a prefill chunk, and the steady decode rate divided zero by zero. DecodeBench now stops with an explanation instead of reporting NaN. Found by Codex. Co-Authored-By: Claude Opus 5.5 --- Benchmarks/DecodeBench/Sources/decodebench/main.swift | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Benchmarks/DecodeBench/Sources/decodebench/main.swift b/Benchmarks/DecodeBench/Sources/decodebench/main.swift index ce717062a5..c1be00c08e 100644 --- a/Benchmarks/DecodeBench/Sources/decodebench/main.swift +++ b/Benchmarks/DecodeBench/Sources/decodebench/main.swift @@ -178,6 +178,15 @@ struct Run { steadySeconds += stepSeconds } } + // With resumable prefill the rows join one step apart, so a short run can end its first + // rows before the last one decodes. + guard steadySteps > 0 else { + print( + "batch(\(prompts.count)): no step decoded every row without a prefill chunk, so there " + + "is no steady decode rate. Ask for more decode tokens than the rows and their " + + "prefill chunks take to join.") + exit(1) + } return Run( tokensPerSecond: Double(steadySteps) / steadySeconds, firstToken: firstToken ?? seconds(since: start), tokens: tokens, From 8a05215813a94500b591396de3d8dc9f95d34aad Mon Sep 17 00:00:00 2001 From: Ronald Mannak Date: Sat, 7 Nov 2026 19:36:14 -0800 Subject: [PATCH 6/6] Add a prefill step and an arrival mode to DecodeBench So developers can tune the prefill chunk size on their own hardware: - An eighth argument sets PrefillParameters.stepSize for both the single-sequence and the batch paths. - Prompt lengths `arrival[:tokens]`: each batch size is a number of active rows decoding prompts of the prompt length; after 16 steps in which every row decoded, a prompt of `tokens` (default 4096) arrives. Per width it reports the newcomer's time to first token, the active rows' p50/p95/max gaps between tokens while the newcomer is admitted, and the tokens each active row emitted while it waited. Rounds replay it, alternating the order of the widths. - A README describes the options and notes that the balance depends on the GPU and the model. On an Apple M5 Max with Llama 3.2 3B 4-bit (1 and 3 active rows, 145-token prompts, a 4096-token arrival), step 512 gives a p95 gap of 78.5-79.3 ms and a 621-649 ms newcomer TTFT; step 256 gives 56.5-57.3 ms and 856-887 ms. Co-Authored-By: Claude Opus 5.5 --- Benchmarks/DecodeBench/README.md | 45 +++++ .../Sources/decodebench/main.swift | 175 +++++++++++++++++- 2 files changed, 210 insertions(+), 10 deletions(-) create mode 100644 Benchmarks/DecodeBench/README.md diff --git a/Benchmarks/DecodeBench/README.md b/Benchmarks/DecodeBench/README.md new file mode 100644 index 0000000000..42dbd77f7b --- /dev/null +++ b/Benchmarks/DecodeBench/README.md @@ -0,0 +1,45 @@ +# DecodeBench + +Decode throughput and time to first token on a local model. It compares the single-sequence `TokenIterator` with `BatchTokenIterator` at each batch size asked for, and reports medians over rounds. It loads a model directory you already have and downloads nothing. + +``` +swift run -c release --package-path Benchmarks/DecodeBench decodebench \ + [decode tokens: 128] [rounds: 5] [prompt tokens: 145] [sampler: greedy|topp|categorical] \ + [batch sizes: 1,4,8] [prompt lengths: equal|mixed|arrival[:tokens]] \ + [prefill step: the model's default] +``` + +- **Decode rate:** counts only the batch steps in which every row decodes and no prompt is prefilled. With resumable prefill, the steps that also feed a prefill chunk are reported as overlap steps. +- **Time to first token:** covers the prefill. +- **Prompt lengths:** + - `equal` gives every row a prompt of the prompt length. + - `mixed` shrinks the rows' prompts evenly from the full length to a sixth of it, so every row but the first is left-padded. +- **Prefill step:** sets `PrefillParameters.stepSize` for both paths. +- **Checks:** every path must repeat its tokens in every round. The output also reports how far each batch row agrees with a single-sequence run of its prompt. + +## Choosing a prefill step: `arrival` + +When a long prompt joins rows that are decoding, `BatchTokenIterator` prefills it one chunk per step, after each decode step, for models that support resumable prefill. The prefill step sets the balance between the two: +- Smaller chunks give the decoding rows shorter gaps between tokens. +- But they admit the new prompt more slowly, mainly because small chunks use the GPU less efficiently. + +How it works: +- Each batch size is a number of active rows, with prompts of the prompt length. +- After 16 steps in which every row decoded, a prompt of `tokens` arrives (default 4096). +- The rounds replay this, and the order of the widths alternates from round to round. + +``` +decodebench 128 5 145 greedy 1,3 arrival:4096 512 +decodebench 128 5 145 greedy 1,3 arrival:4096 256 +``` + +It reports, per width: +- the newcomer's time to first token, from its insertion; +- the active rows' gaps between tokens while the newcomer is admitted (p50, p95, max), from its insertion to its first token; +- how many tokens each active row emitted while it waited. + +Compare step sizes in separate runs, and alternate their order (for example 512, 256, 256, 512) so a thermal slope lands on both. + +The results depend on the GPU and the model. The library's default of 512 was chosen on an Apple M5 Max, so measure on the hardware that will run the model before changing it. + +Built with `-Xswiftc -DSINGLE_ONLY`, DecodeBench times `TokenIterator` alone, so it also builds against a checkout without `BatchTokenIterator`. That build has no `arrival` mode. diff --git a/Benchmarks/DecodeBench/Sources/decodebench/main.swift b/Benchmarks/DecodeBench/Sources/decodebench/main.swift index c1be00c08e..ac4f0d13b1 100644 --- a/Benchmarks/DecodeBench/Sources/decodebench/main.swift +++ b/Benchmarks/DecodeBench/Sources/decodebench/main.swift @@ -10,7 +10,8 @@ // // swift run -c release --package-path Benchmarks/DecodeBench decodebench \ // [decode tokens: 128] [rounds: 5] [prompt tokens: 145] [sampler: greedy|topp|categorical] \ -// [batch sizes: 1,4,8] [prompt lengths: equal|mixed] +// [batch sizes: 1,4,8] [prompt lengths: equal|mixed|arrival[:tokens]] \ +// [prefill step: the model's default] // // With `mixed` prompt lengths, the rows of a batch get prompts that shrink evenly from the full // length to a sixth of it, so every row but the first is left-padded. With the greedy sampler, @@ -18,6 +19,17 @@ // once, while correct rows agree until the different matmul shapes of a batch round a near tie // the other way. // +// `arrival` measures a long prompt joining rows that are decoding. Each batch size is a number +// of active rows with prompts of the prompt length; after 16 steps in which every row decoded, +// a prompt of `tokens` (default 4096) arrives. It reports the active rows' gaps between tokens +// while the newcomer is admitted (from its insertion to its first token), the newcomer's time +// to first token, and how many tokens each active row emitted while it waited. The prefill step +// sets the balance: smaller chunks shorten the gaps but admit the newcomer more slowly. The +// balance depends on the GPU and the model, so measure it on the hardware that will run it. +// +// The prefill step is `PrefillParameters.stepSize` for both the single-sequence and the batch +// paths. +// // Built with `-Xswiftc -DSINGLE_ONLY` it times `TokenIterator` alone, so it also builds // against a checkout without `BatchTokenIterator`. @@ -29,7 +41,7 @@ import MLXLMCommon let usage = "usage: decodebench [decode tokens] [rounds] [prompt tokens] [sampler] " - + "[batch sizes] [prompt lengths]" + + "[batch sizes] [prompt lengths: equal|mixed|arrival[:tokens]] [prefill step]" let arguments = CommandLine.arguments guard arguments.count > 1 else { print(usage) @@ -45,9 +57,21 @@ let batchSizes = Set( .filter { $0 > 0 } ).sorted() let lengthsName = arguments.count > 7 ? arguments[7] : "equal" -guard !batchSizes.isEmpty, ["equal", "mixed"].contains(lengthsName) else { +/// The arriving prompt's length in `arrival` mode, else nil. +let arrivalLength: Int? = + lengthsName == "arrival" + ? 4096 + : lengthsName.hasPrefix("arrival:") ? Int(lengthsName.dropFirst("arrival:".count)) : nil +let prefillStep = arguments.count > 8 ? Int(arguments[8]) : nil +let prefill = PrefillParameters(stepSize: prefillStep) +guard !batchSizes.isEmpty, + ["equal", "mixed"].contains(lengthsName) || (arrivalLength ?? 0) > 0, + arguments.count <= 8 || (prefillStep ?? 0) > 0 +else { print(usage) - print("batch sizes are a comma-separated list such as 1,4,8; prompt lengths equal or mixed") + print( + "batch sizes are a comma-separated list such as 1,4,8; prompt lengths equal, mixed, " + + "arrival or arrival:; the prefill step a positive number of tokens") exit(1) } @@ -58,11 +82,12 @@ print("model: \(modelDirectory.lastPathComponent)") #if SINGLE_ONLY print( "prompt tokens: \(promptLength), decode tokens: \(decodeTokens), rounds: \(rounds), " - + "sampler: \(samplerName)") + + "sampler: \(samplerName), prefill step: \(prefillStep.map(String.init) ?? "default")") #else print( "prompt tokens: \(promptLength), decode tokens: \(decodeTokens), rounds: \(rounds), " - + "sampler: \(samplerName), batch sizes: \(batchSizes), prompt lengths: \(lengthsName)") + + "sampler: \(samplerName), batch sizes: \(batchSizes), prompt lengths: \(lengthsName), " + + "prefill step: \(prefillStep.map(String.init) ?? "default")") #endif /// A fresh sampler per run, seeded, so every run of a path draws the same tokens. @@ -86,11 +111,17 @@ print( } } -func seconds(since start: ContinuousClock.Instant) -> Double { - let elapsed = ContinuousClock.now - start +func seconds( + from start: ContinuousClock.Instant, to end: ContinuousClock.Instant = ContinuousClock.now +) -> Double { + let elapsed = end - start return Double(elapsed.components.seconds) + Double(elapsed.components.attoseconds) / 1e18 } +func seconds(since start: ContinuousClock.Instant) -> Double { + seconds(from: start) +} + func median(_ values: [Double]) -> Double { let sorted = values.sorted() let middle = sorted.count / 2 @@ -115,7 +146,7 @@ struct Run { let start = ContinuousClock.now var iterator = try TokenIterator( input: LMInput(tokens: MLXArray(prompt)), model: model, processor: nil, - sampler: makeSampler(), maxTokens: decodeTokens + 1) + sampler: makeSampler(), prefill: prefill, maxTokens: decodeTokens + 1) var tokens: [Int] = [] // The first token comes from the prefill; the steps after it are the decode. if let first = iterator.next() { tokens.append(first) } @@ -137,7 +168,7 @@ struct Run { defer { Stream.defaultStream.synchronize() } let start = ContinuousClock.now var iterator = BatchTokenIterator( - model: model, sampler: makeSampler(), maxTokens: decodeTokens + 1) + model: model, sampler: makeSampler(), maxTokens: decodeTokens + 1, prefill: prefill) let ids = iterator.insert(prompts: prompts.map { $0.map { Int($0) } }) var tokens = [[Int]](repeating: [], count: prompts.count) var firstToken: Double? @@ -203,6 +234,130 @@ struct Run { return prompt(seed: UInt64(row + 1), length: length) } } + +/// One `arrival` replay: what the active rows and the newcomer saw while it was admitted. +struct Arrival { + /// Seconds between the active rows' consecutive tokens, from the newcomer's insertion to + /// its first token. Every active row decodes in every step, so one gap per step. + var gaps: [Double] = [] + /// Seconds from the newcomer's insertion to its first token. + var firstToken: Double? + /// Tokens each active row emitted in that time. + var waitingTokens = 0 + /// Every row's tokens, the newcomer's last. + var tokens: [[Int]] +} + +/// Steps in which every active row decodes before the newcomer arrives. +let arrivalAfter = 16 + +/// `rows` rows decode prompts of the prompt length; after `arrivalAfter` steps a prompt of +/// `length` tokens arrives, and every row runs to its limit. +@MainActor func runArrival(rows: Int, length: Int) throws -> Arrival { + defer { Stream.defaultStream.synchronize() } + var iterator = BatchTokenIterator( + model: model, sampler: makeSampler(), maxTokens: decodeTokens + 1, prefill: prefill) + let active = iterator.insert( + prompts: (0 ..< rows).map { prompt(seed: UInt64($0 + 1)).map { Int($0) } }) + var newcomer: Int? + var inserted: ContinuousClock.Instant? + var previous: ContinuousClock.Instant? + var steps = 0 + var arrival = Arrival(tokens: [[Int]](repeating: [], count: rows + 1)) + while let events = try iterator.next() { + let now = ContinuousClock.now + var activeTokens = 0 + var newcomerToken = false + for event in events { + switch event { + case .token(let id, let token): + if id == newcomer { + arrival.tokens[rows].append(token) + newcomerToken = true + } else { + arrival.tokens[active.firstIndex(of: id)!].append(token) + activeTokens += 1 + } + case .failed(_, let error): + throw error + case .prefill, .finished: + break + } + } + let admitting = inserted != nil && arrival.firstToken == nil + if admitting { + // A gap counts only while every active row still decodes. + guard activeTokens == rows, let previous else { + print( + "arrival(\(rows)): an active row ended before the newcomer's first token. " + + "Ask for more decode tokens.") + exit(1) + } + arrival.gaps.append(seconds(from: previous, to: now)) + arrival.waitingTokens += 1 + if newcomerToken { arrival.firstToken = seconds(since: inserted!) } + } + if activeTokens > 0 { previous = now } + if newcomer == nil, activeTokens == rows { + steps += 1 + if steps == arrivalAfter { + newcomer = iterator.insert( + prompt: prompt(seed: 100, length: length).map { Int($0) }) + inserted = ContinuousClock.now + } + } + } + guard arrival.firstToken != nil else { + print("arrival(\(rows)): the newcomer never arrived. Ask for more decode tokens.") + exit(1) + } + return arrival +} + +/// The `fraction` percentile of `values`, interpolating linearly between ranks. +func percentile(_ values: [Double], _ fraction: Double) -> Double { + let sorted = values.sorted() + let rank = fraction * Double(sorted.count - 1) + let lower = Int(rank.rounded(.down)) + let upper = min(lower + 1, sorted.count - 1) + return sorted[lower] + (sorted[upper] - sorted[lower]) * (rank - Double(lower)) +} + +if let arrivalLength { + // Warm up every width once so kernel compilation is not timed. + for rows in batchSizes { _ = try runArrival(rows: rows, length: arrivalLength) } + var replays: [Int: [Arrival]] = [:] + var repeated = true + for round in 0 ..< rounds { + // Alternate the order so a thermal or background-load slope lands on every width. + for rows in round % 2 == 0 ? batchSizes : Array(batchSizes.reversed()) { + let replay = try runArrival(rows: rows, length: arrivalLength) + repeated = repeated && replay.tokens == (replays[rows]?.first?.tokens ?? replay.tokens) + replays[rows, default: []].append(replay) + print( + String( + format: "round %d arrival(%d): newcomer ttft %.0f ms, active p95 gap %.1f ms, " + + "%d tokens per active row while it waited", round + 1, rows, + 1000 * replay.firstToken!, 1000 * percentile(replay.gaps, 0.95), + replay.waitingTokens)) + Memory.clearCache() + } + } + for rows in batchSizes { + let runs = replays[rows]! + let gaps = runs.flatMap(\.gaps) + print( + String( + format: "median arrival(%d): newcomer ttft %.0f ms; active rows' gaps while it " + + "is admitted p50 %.1f ms, p95 %.1f ms, max %.1f ms (%d gaps); %.0f tokens " + + "per active row while it waited", rows, + 1000 * median(runs.map { $0.firstToken! }), 1000 * percentile(gaps, 0.5), + 1000 * percentile(gaps, 0.95), 1000 * gaps.max()!, gaps.count, + median(runs.map { Double($0.waitingTokens) }))) + } + print("each width repeats its tokens in every round: \(repeated)") + exit(0) +} #endif let singlePrompt = prompt(seed: 1)