Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion docs/architecture/inference.md
Original file line number Diff line number Diff line change
Expand Up @@ -4785,7 +4785,10 @@ Oracles run on synthetic checkpoints with the 26B's structure scaled down:
prefill width rounds some rows unlike its 512-row half.

`tp-check gemma run --path paged` runs `full`, `simulated` and `tp` through the
resident runtime's own request path instead of the SDK's legacy caches.
resident runtime's own request path instead of the SDK's legacy caches;
`--layer-stride N` submits each decode step every N layers instead of the
product's `decodeLayerStride` (1), so a pair can measure the stride before the
product's changes (Qwen's measured choice is 8, `QwenTensorParallelLaunch`).
`tp-check gemma lanes` serves several requests together through the batch
driver and checks each against itself alone.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import MLX
// darkbloom-cluster-tp-check gemma run --mode full|split-sum|simulated|shard|tp --model-dir DIR --request FILE --report FILE
// [--record-top K] [--backend ring|socket|jaccl] [--reduction native|sealed-bench] [--shard-rank R]
// [--pack yes|no] [--path legacy|paged] [--prefix none|repeat] [--deadline-seconds S]
// [--layer-stride N (paged path, full/shard/tp: decode submitted every N layers, 0 = whole step; default the product's)]
// darkbloom-cluster-tp-check gemma compare --reference FILE --candidate FILE [--bitwise yes|no] [--near-tie-ulps U]
// darkbloom-cluster-tp-check gemma allsum [--backend ring|socket|jaccl] [--count N]
// darkbloom-cluster-tp-check gemma lanes --mode simulated|tp --model-dir DIR --report FILE [--lanes N] [--outputs N]
Expand Down Expand Up @@ -147,7 +148,8 @@ enum GemmaCheck {
["native", "sealed-bench"].contains(fields["--reduction"] ?? "native"),
["yes", "no"].contains(fields["--pack"] ?? "yes"),
["legacy", "paged"].contains(fields["--path"] ?? "legacy"),
["none", "repeat"].contains(fields["--prefix"] ?? "none") else {
["none", "repeat"].contains(fields["--prefix"] ?? "none"),
fields["--layer-stride"].map({ Int($0).map { (0 ... 64).contains($0) } ?? false }) ?? true else {
throw Failure("gemma run needs --mode full|split-sum|simulated|shard|tp, --model-dir, --request, a new --report and bounded options")
}
let paged = (fields["--path"] ?? "legacy") == "paged"
Expand All @@ -159,6 +161,10 @@ enum GemmaCheck {
let sealed = (fields["--reduction"] ?? "native") == "sealed-bench"
guard !sealed || mode == "tp" else { throw Failure("--reduction sealed-bench applies to a tp rank only") }
let pack = (fields["--pack"] ?? "yes") == "yes"
let layerStride = fields["--layer-stride"].flatMap { Int($0) }
guard layerStride == nil || (paged && Gemma4TensorParallelModel.benchLayerStrideApplies(mode: mode)) else {
throw Failure("--layer-stride applies to the paged path of a full, shard or tp rank (simulated ranks run on their own threads)")
}
try ProcessForcedExit.routeTerminationSignals()
ProcessNativeMemoryRelease.installForForcedExit()
try ProcessDeadline.arm(uptimeNanoseconds: DispatchTime.now().uptimeNanoseconds + UInt64(deadline) * 1_000_000_000,
Expand Down Expand Up @@ -198,7 +204,7 @@ enum GemmaCheck {
reduction = g
note("rank \(g.rank) of \(g.size) over \(backend.rawValue)\(backend.correctnessOnly ? " (correctness only, not a pair timing)" : "")")
// Everything that changes the collectives is agreed before loading.
let workload = "\(configurationSHA)|\(request.promptTokenIDsSHA256)|\(request.outputCount)|\(request.chunkSize)|top=\(recordTop)|pack=\(pack)|sealed=\(sealed)|paged=\(paged)|prefix=\(repeatPrefix)|\(Gemma4TensorParallelPlan.arithmeticAgreementFields.joined(separator: ","))"
let workload = "\(configurationSHA)|\(request.promptTokenIDsSHA256)|\(request.outputCount)|\(request.chunkSize)|top=\(recordTop)|pack=\(pack)|sealed=\(sealed)|paged=\(paged)|prefix=\(repeatPrefix)|stride=\(layerStride.map(String.init) ?? "product")|\(Gemma4TensorParallelPlan.arithmeticAgreementFields.joined(separator: ","))"
guard try g.digestsEqual(fnv(workload)) else {
throw Failure("the ranks disagree on the workload, the model configuration or the arithmetic contract")
}
Expand All @@ -216,7 +222,7 @@ enum GemmaCheck {
packFeedForward: pack)
note("loaded in \(String(format: "%.2f", model.loadSeconds)) s, \(model.loadedParameterBytes) parameter bytes")
if let group { guard try group.agree([7]) else { throw Failure("load barrier failed") } }
let generation: Gemma4TensorParallelModel.Generation
var generation: Gemma4TensorParallelModel.Generation!
var pairAgrees: Bool?
var prefixOutcome: (reused: Int, equalsCold: Bool)?
func bitsEqual(_ a: Gemma4TensorParallelModel.Generation, _ b: Gemma4TensorParallelModel.Generation) -> Bool {
Expand All @@ -225,45 +231,52 @@ enum GemmaCheck {
&& bits(a.topLogprobs) == bits(b.topLogprobs)
&& a.finalLogits.map { $0.map(\.bitPattern) } == b.finalLogits.map { $0.map(\.bitPattern) }
}
if repeatPrefix {
let prompt = request.promptTokenIDs, count = request.outputCount, chunk = request.chunkSize
let runs: [(cold: Gemma4TensorParallelModel.Generation, restored: Gemma4TensorParallelModel.Generation, reused: Int)]
if let pair {
try Gemma4TensorParallelModel.withLayerStride(layerStride) {
if repeatPrefix {
let prompt = request.promptTokenIDs, count = request.outputCount, chunk = request.chunkSize
let runs: [(cold: Gemma4TensorParallelModel.Generation, restored: Gemma4TensorParallelModel.Generation, reused: Int)]
if let pair {
let ranks = Ranks([model, try Gemma4TensorParallelModel.load(modelDirectory: modelDirectory,
role: .shard(rank: 1), reduction: pair.reduction(rank: 1), packFeedForward: pack)])
runs = try Gemma4TensorParallelLocalPair.run(device: Device.defaultDevice()) { rank in
let value = try ranks.models[rank].generatePagedRepeatingPrefix(prompt: prompt, outputCount: count,
chunk: chunk, recordTop: recordTop)
return (value.cold, value.restored, value.reusedPromptTokens)
}
pairAgrees = bitsEqual(runs[0].restored, runs[1].restored)
} else {
let value = try model.generatePagedRepeatingPrefix(prompt: prompt, outputCount: count, chunk: chunk,
recordTop: recordTop)
runs = [(value.cold, value.restored, value.reusedPromptTokens)]
}
generation = runs[0].restored
prefixOutcome = (runs[0].reused, runs.allSatisfy { $0.reused > 0 && bitsEqual($0.restored, $0.cold) })
note("prefix repeat: reused \(runs[0].reused) prompt tokens; restored equals cold bit for bit: \(prefixOutcome!.equalsCold)")
} else if let pair {
let ranks = Ranks([model, try Gemma4TensorParallelModel.load(modelDirectory: modelDirectory,
role: .shard(rank: 1), reduction: pair.reduction(rank: 1), packFeedForward: pack)])
runs = try Gemma4TensorParallelLocalPair.run(device: Device.defaultDevice()) { rank in
let value = try ranks.models[rank].generatePagedRepeatingPrefix(prompt: prompt, outputCount: count,
chunk: chunk, recordTop: recordTop)
return (value.cold, value.restored, value.reusedPromptTokens)
let prompt = request.promptTokenIDs, count = request.outputCount, chunk = request.chunkSize
let both = try Gemma4TensorParallelLocalPair.run(device: Device.defaultDevice()) { rank in
paged ? try ranks.models[rank].generatePaged(prompt: prompt, outputCount: count, chunk: chunk, recordTop: recordTop)
: try ranks.models[rank].generate(prompt: prompt, outputCount: count, chunk: chunk, recordTop: recordTop)
}
pairAgrees = bitsEqual(runs[0].restored, runs[1].restored)
func bits(_ rows: [[Float]]) -> [[UInt32]] { rows.map { $0.map(\.bitPattern) } }
pairAgrees = both[0].tokenIDs == both[1].tokenIDs && bits(both[0].topLogits) == bits(both[1].topLogits)
&& bits(both[0].topLogprobs) == bits(both[1].topLogprobs)
&& both[0].finalLogits.map { $0.map(\.bitPattern) } == both[1].finalLogits.map { $0.map(\.bitPattern) }
generation = both[0]
} else {
let value = try model.generatePagedRepeatingPrefix(prompt: prompt, outputCount: count, chunk: chunk,
recordTop: recordTop)
runs = [(value.cold, value.restored, value.reusedPromptTokens)]
}
generation = runs[0].restored
prefixOutcome = (runs[0].reused, runs.allSatisfy { $0.reused > 0 && bitsEqual($0.restored, $0.cold) })
note("prefix repeat: reused \(runs[0].reused) prompt tokens; restored equals cold bit for bit: \(prefixOutcome!.equalsCold)")
} else if let pair {
let ranks = Ranks([model, try Gemma4TensorParallelModel.load(modelDirectory: modelDirectory,
role: .shard(rank: 1), reduction: pair.reduction(rank: 1), packFeedForward: pack)])
let prompt = request.promptTokenIDs, count = request.outputCount, chunk = request.chunkSize
let both = try Gemma4TensorParallelLocalPair.run(device: Device.defaultDevice()) { rank in
paged ? try ranks.models[rank].generatePaged(prompt: prompt, outputCount: count, chunk: chunk, recordTop: recordTop)
: try ranks.models[rank].generate(prompt: prompt, outputCount: count, chunk: chunk, recordTop: recordTop)
generation = paged
? try model.generatePaged(prompt: request.promptTokenIDs, outputCount: request.outputCount,
chunk: request.chunkSize, recordTop: recordTop)
: try model.generate(prompt: request.promptTokenIDs, outputCount: request.outputCount,
chunk: request.chunkSize, recordTop: recordTop)
}
func bits(_ rows: [[Float]]) -> [[UInt32]] { rows.map { $0.map(\.bitPattern) } }
pairAgrees = both[0].tokenIDs == both[1].tokenIDs && bits(both[0].topLogits) == bits(both[1].topLogits)
&& bits(both[0].topLogprobs) == bits(both[1].topLogprobs)
&& both[0].finalLogits.map { $0.map(\.bitPattern) } == both[1].finalLogits.map { $0.map(\.bitPattern) }
generation = both[0]
} else {
generation = paged
? try model.generatePaged(prompt: request.promptTokenIDs, outputCount: request.outputCount,
chunk: request.chunkSize, recordTop: recordTop)
: try model.generate(prompt: request.promptTokenIDs, outputCount: request.outputCount,
chunk: request.chunkSize, recordTop: recordTop)
}
if !generation.stepSeconds.isEmpty {
let steps = generation.stepSeconds.sorted()
note(String(format: "decode stride=%@ step_ms_p50=%.3f step_ms_min=%.3f steps=%d", layerStride.map(String.init) ?? "product",
steps[steps.count / 2] * 1000, steps[0] * 1000, steps.count))
}
var report = Report(mode: mode, role: mode == "simulated" ? "simulated-tp2" : role.label,
rank: group?.rank ?? (mode == "shard" ? shardRank : 0),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,17 @@ extension Gemma4TensorParallelModel {
static let decodeLayerStride = 1
/// A bench or test's own stride (0: the whole step in one evaluation).
@TaskLocal static var layerStride: Int?
/// Runs `body` with a bench's own decode layer stride (`layerStride`; nil:
/// the product's `decodeLayerStride`), to compare strides on a pair
/// (`darkbloom-cluster-tp-check gemma run --layer-stride`).
public static func withLayerStride<R>(_ stride: Int?, _ body: () throws -> R) rethrows -> R {
try $layerStride.withValue(stride, operation: body)
}
/// The bench modes a `withLayerStride` stride reaches: ranks that decode
/// on the calling thread (`full`, `shard`, `tp`). `simulated` runs both
/// ranks on `Gemma4TensorParallelLocalPair`'s own threads, which never see
/// the stride, so a stride there is refused instead of silently ignored.
public static func benchLayerStrideApplies(mode: String) -> Bool { ["full", "shard", "tp"].contains(mode) }

/// Greedy generation as `generate`, on this model's paged KV through the
/// resident runtime's own request path (`Gemma4TensorParallelPagedSession`,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,17 +104,29 @@ struct Gemma4TensorParallelRuntimeTests {
defer { try? FileManager.default.removeItem(at: directory) }
let model = try Gemma4TensorParallelModel.load(modelDirectory: directory, role: .full, reduction: nil)
func run(_ stride: Int) throws -> Gemma4TensorParallelModel.Generation {
try Gemma4TensorParallelModel.$layerStride.withValue(stride) {
try Gemma4TensorParallelModel.withLayerStride(stride) {
try model.generatePaged(prompt: Self.prompt, outputCount: 6, chunk: 16, recordTop: 4)
}
}
let whole = try run(0), layered = try run(1), pairs = try run(2)
for other in [layered, pairs] {
// Strides a bench compares (`tp-check gemma run --layer-stride`), on the synthetic model's 10 layers.
let whole = try run(0)
for other in try [1, 2, 5, 8].map(run) {
#expect(other.tokenIDs == whole.tokenIDs && Self.bits(other.topLogits) == Self.bits(whole.topLogits))
#expect(other.finalLogits.map { $0.map(\.bitPattern) } == whole.finalLogits.map { $0.map(\.bitPattern) })
}
}

/// A bench's own decode layer stride holds for its body only.
@Test func aBenchsLayerStrideHoldsForItsBodyOnly() {
#expect(Gemma4TensorParallelModel.layerStride == nil)
Gemma4TensorParallelModel.withLayerStride(8) { #expect(Gemma4TensorParallelModel.layerStride == 8) }
Gemma4TensorParallelModel.withLayerStride(nil) { #expect(Gemma4TensorParallelModel.layerStride == nil) }
#expect(Gemma4TensorParallelModel.layerStride == nil)
// Only ranks that decode on the calling thread see it: `simulated` is refused.
#expect(["full", "shard", "tp"].allSatisfy { Gemma4TensorParallelModel.benchLayerStrideApplies(mode: $0) })
#expect(!["simulated", "split-sum", ""].contains { Gemma4TensorParallelModel.benchLayerStrideApplies(mode: $0) })
}

/// Batch lanes: three requests of different lengths decode together on
/// each rank's three-lane host (two open, the third joins two steps later,
/// each leaves at its own end). Every row of every step equals that
Expand Down
Loading