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
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
### Gemma tensor parallel prepares the next token ahead for sampled requests too

- Requests that sample (temperature above 0, with or without logprobs), and greedy requests with logit bias or penalties, now also start the next token's work on the GPU before the last token is read. Each token is still the exact draw for its position and seed, so the output is unchanged (except that a request that already fails because one Mac stopped on its own may stream one extra token first, as on GLM). Greedy requests that ask for logprobs keep the old order.
13 changes: 11 additions & 2 deletions docs/architecture/inference.md
Original file line number Diff line number Diff line change
Expand Up @@ -4858,8 +4858,17 @@ stops, cancellations and retirements.
errors on both ranks: rank 0 refuses the peer's stop, and the worker session
refuses a length finish short of the output count). And a refused growth, which
still keeps the margin's rows, ends the request one token later than before.
Never a token past a stop token, a length end or the owner's stop. Sampled requests, and greedy ones asking for logprobs (a
collective of their own), are built after each token is read.
Never a token past a stop token, a length end or the owner's stop. Sampled
requests, and greedy ones with logit bias or penalties (they draw through the
sampler), are built ahead too: rank 0's draw is
`QwenStageTokenSampler.sample`, the product's `CBv2DefaultSampler`, which
advances its penalty counts with each drawn token on the device and its keyed
step index with each draw, so a draw built before the previous token is read
is still the draw at its output index with the history up to it; each step
keeps its own lazy logprob gather (`takePendingStepLogprobs`). Greedy
requests asking for logprobs read each step first: their vocabulary-split
top-k gather is a collective evaluated on the host after the token is
agreed, which would wait for the step built ahead.
- Prompt prefixes. Each rank keeps its own heads' state at a prompt's chunk
boundaries as the Gemma pipeline keeps a stage's, in the pipeline's memory
tier and the owner's encrypted SSD tier (`Gemma4TensorParallelPrefix`). A
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -152,15 +152,9 @@ final class Gemma4TensorParallelPagedSession {
throw ProbeError("Gemma tensor-parallel decode step differs from its request or pages")
}
let input = MLXArray([Int32(token)]).reshaped([1, 1])
let text = model.textModel
var logits: MLXArray?
let stride = Gemma4TensorParallelModel.layerStride ?? Gemma4TensorParallelModel.decodeLayerStride
let output = try state.run(tokenCount: 1, check: check, forward: { caches, _ in
let row = Gemma4LayerSubmission.$stride.withValue(stride) {
Gemma4BatchDecodeScope.withDecodeFrame(tokens: input, enabled: true) {
text(input, cache: caches.map { $0 as! any KVCache })[0..., -1, 0...]
}
}
let row = decodeRow(input, caches: caches)
logits = row
return select(row)
}, validateOutput: { _ in })
Expand All @@ -182,15 +176,9 @@ final class Gemma4TensorParallelPagedSession {
throw ProbeError("Gemma tensor-parallel decode step differs from its request or pages")
}
let input = selected[0 ..< 1].asType(.int32).reshaped([1, 1])
let text = model.textModel
var logits: MLXArray?
let stride = Gemma4TensorParallelModel.layerStride ?? Gemma4TensorParallelModel.decodeLayerStride
let output = try state.submit(tokenCount: 1, check: check, forward: { caches, _ in
let row = Gemma4LayerSubmission.$stride.withValue(stride) {
Gemma4BatchDecodeScope.withDecodeFrame(tokens: input, enabled: true) {
text(input, cache: caches.map { $0 as! any KVCache })[0..., -1, 0...]
}
}
let row = decodeRow(input, caches: caches)
logits = row
return select(row)
})
Expand All @@ -199,6 +187,17 @@ final class Gemma4TensorParallelPagedSession {
return (logits, output)
}

/// One decode row's logits on `input` (`[1, 1]`) at the decode layer
/// stride: `decode`'s and `submitDecode`'s forward.
private func decodeRow(_ input: MLXArray, caches: [any CBv2AttendingLayerCache]) -> MLXArray {
let stride = Gemma4TensorParallelModel.layerStride ?? Gemma4TensorParallelModel.decodeLayerStride
return Gemma4LayerSubmission.$stride.withValue(stride) {
Gemma4BatchDecodeScope.withDecodeFrame(tokens: input, enabled: true) {
model.textModel(input, cache: caches.map { $0 as! any KVCache })[0..., -1, 0...]
}
}
}

/// One decode step of each of `sessions` (distinct requests on one model's
/// host), a row each, in one forward under the explicit batch decode scope
/// (`Gemma4BatchDecodeScope`: every row keeps each projection's singleton
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import DarkbloomClusterProtocol
import Foundation
import MLX
import MLXLMCommon

/// One request on one rank of a Gemma 4 tensor-parallel pair, as the resident
/// runtime serves it alone: the prompt in chunks of the request's own size
Expand All @@ -9,11 +10,14 @@ import MLX
/// parallel's step order). Each step's token and both ranks' stop flags
/// are agreed in the step's own evaluation (`Gemma4TensorParallelChoice`);
/// both ranks submit the same collectives in the same order whatever either
/// decides, and end after the same step. A greedy request's step is built
/// one ahead, on the previous step's lazy agreed token
/// decides, and end after the same step. Each step is built one ahead, on
/// the previous step's lazy agreed token
/// (`Gemma4TensorParallelPagedSession.submitDecode`), so the GPU and the
/// collectives run it while the host reads the previous one; a step built
/// after the request ended is evaluated and never committed or published.
/// collectives run it while the host reads the previous one: greedy and
/// sampled requests (rank 0's keyed draw is the one made at its output index
/// with the history up to it), but not a greedy request asking for logprobs
/// (`pipelines`). A step built after the request ended is evaluated; its
/// token is never committed or published.
///
/// Rank 0 publishes each token at once and reads the owner's answer to it
/// after the next step ran; a stop answer is acted on one step later (the
Expand Down Expand Up @@ -42,19 +46,45 @@ struct Gemma4TensorParallelRequestLoop {
var pagesRefused: Bool
}

/// Whether `choice`'s steps are built one ahead: greedy requests without
/// logprobs (as GLM's `pipelined: sampler == nil`).
static func pipelines(_ choice: Gemma4TensorParallelChoice) -> Bool { choice.sampler == nil }
/// One built step: its logits, its agreement (`Gemma4TensorParallelChoice.build`)
/// and, on rank 0 of a sampled request asking for them, its draw's
/// logprobs as graph nodes (kept with the step, as the next step's draw
/// may be built before this one is read).
struct Step {
let logits: MLXArray
let selected: MLXArray
let logprobs: CBv2StepLogprobs?
}

/// Whether `choice`'s steps are built one ahead: greedy and sampled
/// requests alike (each draw is keyed on its output index and its
/// history on the device, `QwenStageTokenSampler.sample`). A greedy
/// request asking for logprobs reads each step before building the next:
/// its logprobs come from a vocabulary-split top-k gather, a collective
/// evaluated on the host after the step's token is agreed, which would
/// wait for the step built ahead and gain nothing.
static func pipelines(_ choice: Gemma4TensorParallelChoice) -> Bool {
if let buildsAhead { return buildsAhead }
return choice.gathersRow || choice.sampler?.wire.capturedLogprobs == nil
}
/// Tests only: a test's own order (nil: `pipelines`'s). The product never sets it.
@TaskLocal static var buildsAhead: Bool?

func run(channel: ClusterCommittedTokenChannel, check: () throws -> Void) throws -> Outcome {
let rank = choice.rank, prompt = request.promptTokenIDs
let sampler = choice.sampler
// A restored prefix ends on the chunk grid: the rest runs the chunks a cold request runs there.
var offset = session.committedTokens
var current: (logits: MLXArray, selected: MLXArray)?
/// A built step, with rank 0's sampled draw's logprobs taken now.
func built(_ step: (logits: MLXArray, selected: MLXArray)) -> Step {
let logprobs = rank == 0 && choice.gathersRow ? sampler?.takePendingStepLogprobs() : nil
return Step(logits: step.logits, selected: step.selected, logprobs: logprobs)
}
var current: Step?
while offset < prompt.count {
let end = min(prompt.count, offset + request.chunkSize)
current = try session.prefill(prompt, range: offset ..< end, check: check) { choice.build($0, stop: 0) } ?? current
current = try session.prefill(prompt, range: offset ..< end, check: check) { choice.build($0, stop: 0) }
.map(built) ?? current
offset = end
}
guard let step = current else { throw ProbeError("Gemma tensor-parallel prompt produced no logits") }
Expand Down Expand Up @@ -87,18 +117,15 @@ struct Gemma4TensorParallelRequestLoop {
}
}
try withoutActuallyEscaping(check) { check in
// Greedy steps are built one ahead (`TensorParallelOneTokenLoop`, GLM's step order): the next step is
// submitted on this step's lazy agreed token before the host reads it. A sampled step, and a greedy one
// whose logprobs come from a collective of their own, is built after its token is read.
let steps = TensorParallelOneTokenLoop<(logits: MLXArray, selected: MLXArray)>(
outputCount: request.outputCount, stopTokenIDs: request.stopTokenIDs, pipelined: Self.pipelines(choice),
// Steps are built one ahead (`TensorParallelOneTokenLoop`, GLM's step order): the next step is submitted
// on this step's lazy agreed token before the host reads it (`pipelines`).
let pipelined = Self.pipelines(choice)
let steps = TensorParallelOneTokenLoop<Step>(
outputCount: request.outputCount, stopTokenIDs: request.stopTokenIDs, pipelined: pipelined,
step: { current, stop in
if Self.pipelines(choice) {
return try session.submitDecode(after: current.selected, check: check) { choice.build($0, stop: stop) }
}
return try session.decode(try choice.read(current.selected).token, check: check) {
choice.build($0, stop: stop)
}
let select: (MLXArray) -> MLXArray = { choice.build($0, stop: stop) }
return try built(pipelined ? session.submitDecode(after: current.selected, check: check, select: select)
: session.decode(choice.read(current.selected).token, check: check, select: select))
},
read: { current in
let agreed = try choice.read(current.selected)
Expand All @@ -121,10 +148,10 @@ struct Gemma4TensorParallelRequestLoop {
guard let count = logprobCount else { return }
if choice.gathersRow {
if rank == 0, stopKeep == 0 {
guard let drawn = sampler?.takePendingLogprobs() else {
guard let drawn = current.logprobs else {
throw ProbeError("Gemma tensor-parallel token has no logprobs")
}
stepLogprobs = drawn
stepLogprobs = QwenStageTokenSampler.tokenLogprobs(drawn)
}
} else {
let maximum = try choice.read(current.selected).maximum
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,13 @@ final class QwenStageTokenSampler {
var nextOutputIndex: Int { selected.count }

/// Graph only: one token `[1]` (int32) from a selected row `[1, V]`, drawn
/// at output index `nextOutputIndex`. Follow with `commit`.
/// at output index `nextOutputIndex`. Follow with `commit`. The next draw
/// may be built before this one is read and committed (one step ahead):
/// the product's sampler advances its penalty counts with each drawn
/// token on the device and its keyed step index with each draw
/// (`CBv2DefaultSampler`, `SamplerV2.commit`); `selected` only configures
/// it at the first draw. So each draw is the one made at its output index
/// with the history up to it, whenever the host reads the tokens.
func sample(_ logits: MLXArray) -> MLXArray {
let token = sampler.sample(logits: logits, params: [parameters], requestIDs: [stream], stepIndex: selected.count,
pendingSampledTokens: nil,
Expand All @@ -82,6 +88,16 @@ final class QwenStageTokenSampler {
return pendingLogprobs.map(Self.tokenLogprobs)
}

/// The last `sample`'s logprobs as graph nodes, once: a caller that draws
/// the next step before it reads this one (`TensorParallelOneTokenLoop`)
/// keeps each step's gather with its step and reads it with
/// `tokenLogprobs` after the step's token was agreed. Nil when the
/// request asks for none.
func takePendingStepLogprobs() -> CBv2StepLogprobs? {
defer { pendingLogprobs = nil }
return pendingLogprobs
}

/// The current round's verify window (`verifyRound`), kept for its
/// logprobs when the request asks for them.
private var verifiedWindow: MLXArray?
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -372,6 +372,8 @@ struct Gemma4TensorParallelRuntimeTests {
var ownerStopsAt: Int?
/// Rank 1 stops on its own after this many committed tokens.
var rankOneStopsAfter: Int?
/// The loop's step order (nil: the product's, `Gemma4TensorParallelRequestLoop.pipelines`).
var buildsAhead: Bool?
}

private struct LoopResult: Sendable {
Expand Down Expand Up @@ -403,7 +405,8 @@ struct Gemma4TensorParallelRuntimeTests {
published.append(token); logprobs.append(captured); committed = ordinal + 1
}, answer: { value.ownerStopsAt.map { committed - 1 != $0 } ?? true })
var localTokens = 0
let outcome = try Gemma4TensorParallelRequestLoop(session: session, request: request,
let outcome = try Gemma4TensorParallelRequestLoop.$buildsAhead.withValue(value.buildsAhead) {
try Gemma4TensorParallelRequestLoop(session: session, request: request,
choice: Gemma4TensorParallelChoice(selection: model.selection, sampler: request.sampler, rank: rank),
exchange: { values in
let summed = reduction.allSum(MLXArray(values.map(Float.init)))
Expand All @@ -413,6 +416,7 @@ struct Gemma4TensorParallelRuntimeTests {
localTokens += 1
return rank == 1 && value.rankOneStopsAfter.map { localTokens >= $0 } == true
}).run(channel: channel, check: {})
}
try session.retire()
return LoopResult(tokens: outcome.tokens, finish: outcome.finish, clientStopped: outcome.clientStopped,
published: published, logprobs: logprobs)
Expand Down Expand Up @@ -475,19 +479,48 @@ struct Gemma4TensorParallelRuntimeTests {
#expect(race[0].clientStopped && race[0].published == Array(drawn.prefix(raceAt)))
}

/// A greedy request's steps are built one ahead (`TensorParallelOneTokenLoop`,
/// GLM's order; its two-rank order and endings are the model-free
/// TensorParallelPlanChecks'); a request whose sampler draws, or asks for
/// logprobs (a collective of their own), is built after each token is read.
/// The tokens are the read-then-build oracle's
/// (`theRequestLoopEndsBothRanksAfterTheSameStep`).
/// Greedy and sampled requests build their steps one ahead
/// (`TensorParallelOneTokenLoop`, GLM's order; its two-rank order and
/// endings are the model-free TensorParallelPlanChecks'). A greedy request
/// asking for logprobs (a top-k gather of its own, read on the host)
/// reads each step first. The tokens are the read-then-build order's
/// (`theRequestLoopEndsBothRanksAfterTheSameStep`,
/// `sampledStepsBuiltAheadTakeTheReadThenBuildTokens`).
@Test func greedyRequestsBuildTheirStepsAhead() throws {
let selection = Gemma4TensorParallelSelection(vocabularyRange: 0 ..< 512, vocabularySize: 512, reduction: nil)
#expect(Gemma4TensorParallelRequestLoop.pipelines(.init(selection: selection, sampler: nil, rank: 0)))
for temperature: Float in [0, 1] {
let choice = Gemma4TensorParallelChoice(selection: selection,
sampler: try Self.sampler(temperature: temperature, topLogprobs: 2), rank: 0)
#expect(!Gemma4TensorParallelRequestLoop.pipelines(choice))
func pipelines(temperature: Float, topLogprobs: Int) throws -> Bool {
Gemma4TensorParallelRequestLoop.pipelines(Gemma4TensorParallelChoice(selection: selection,
sampler: try Self.sampler(temperature: temperature, topLogprobs: topLogprobs), rank: 0))
}
#expect(try pipelines(temperature: 1, topLogprobs: 0))
#expect(try pipelines(temperature: 1, topLogprobs: 2))
#expect(try !pipelines(temperature: 0, topLogprobs: 2))
}

/// Sampled requests, with logprobs and with history-dependent transforms,
/// built one ahead: on two ranks the same tokens, finish and published
/// logprobs as the read-then-build order, plainly and when the owner
/// stops early (keyed draws: each token is the draw at its output index).
@Test func sampledStepsBuiltAheadTakeTheReadThenBuildTokens() throws {
let directory = try Self.synthetic()
defer { try? FileManager.default.removeItem(at: directory) }
let pair = Pair()
let models = Box(try (0 ..< 2).map {
try Gemma4TensorParallelModel.load(modelDirectory: directory, role: .shard(rank: $0), reduction: pair.reduction(rank: $0))
})
let drawn = ClusterWorkerSampling(temperature: 1.0, topP: 0.95, topK: 0, minP: 0, repetitionPenalty: 1.2,
repetitionContextSize: 64, frequencyPenalty: 0.3, presencePenalty: 0, seed: 0x5eed, stream: 0xab,
logitBias: [], topLogprobs: 3)
for ownerStopsAt in [nil, 3] as [Int?] {
let ahead = try Self.loop(models, LoopCase(sampling: drawn, ownerStopsAt: ownerStopsAt, buildsAhead: true), outputs: 12)
let plain = try Self.loop(models, LoopCase(sampling: drawn, ownerStopsAt: ownerStopsAt, buildsAhead: false), outputs: 12)
for (a, b) in zip(ahead, plain) {
#expect(a.tokens == b.tokens && a.finish == b.finish && a.published == b.published)
#expect(a.logprobs.map { $0?.logprob } == b.logprobs.map { $0?.logprob })
}
#expect(ahead[0].tokens == ahead[1].tokens && !ahead[0].tokens.isEmpty)
#expect(ahead[0].logprobs.allSatisfy { $0?.top.count == 3 })
}
}

Expand Down
Loading
Loading