Skip to content

Get up and running with Kimi, GLM, MiniMax, DeepSeek, gpt-oss, Qwen, Gemma and other models.

mlxrunner: run one target forward per MTP decode step

Jesse Gross42c330283b88
diff --git a/x/mlxrunner/mtp_test.go b/x/mlxrunner/mtp_test.go
index bde9e607e..73c6c2545 100644
--- a/x/mlxrunner/mtp_test.go
+++ b/x/mlxrunner/mtp_test.go
@@ -263,13 +263,12 @@ func TestAcceptMTPDraftsGreedyAcceptAll(t *testing.T) {
caches, _ := newMTPTestCaches(1)
candidates := scriptedCandidates(r, []int32{2, 3, 4})
- baseLogits := oneHotLogits([]int32{2}).Squeeze(1) // target prediction after the seed token 1
position := caches[0].Offset()
spec := testSpeculationSession(r, caches)
current := sampler.Result{Token: mlx.FromValues([]int32{1}, 1)}
- results, accepted, err := spec.accept(&position, current, oneHotLogits([]int32{1}), baseLogits, candidates)
+ results, accepted, err := spec.accept(&position, current, candidates)
if err != nil {
t.Fatalf("accept: %v", err)
}
@@ -280,11 +279,11 @@ func TestAcceptMTPDraftsGreedyAcceptAll(t *testing.T) {
if got := resultIDs(results); !slices.Equal(got, []int{2, 3, 4, 5}) {
t.Fatalf("results = %v, want [2 3 4 5]", got)
}
- if position != 3 {
- t.Fatalf("position = %d, want 3", position)
+ if position != 4 {
+ t.Fatalf("position = %d, want 4 (current + accepted)", position)
}
- if got := caches[0].Offset(); got != 3 {
- t.Fatalf("cache offset = %d, want 3 (all drafts kept)", got)
+ if got := caches[0].Offset(); got != 4 {
+ t.Fatalf("cache offset = %d, want 4 (current + all drafts kept)", got)
}
}
@@ -298,13 +297,12 @@ func TestAcceptMTPDraftsGreedyMismatch(t *testing.T) {
caches, _ := newMTPTestCaches(1)
candidates := scriptedCandidates(r, []int32{2, 7})
- baseLogits := oneHotLogits([]int32{2}).Squeeze(1)
position := caches[0].Offset()
spec := testSpeculationSession(r, caches)
current := sampler.Result{Token: mlx.FromValues([]int32{1}, 1)}
- results, accepted, err := spec.accept(&position, current, oneHotLogits([]int32{1}), baseLogits, candidates)
+ results, accepted, err := spec.accept(&position, current, candidates)
if err != nil {
t.Fatalf("accept: %v", err)
}
@@ -316,11 +314,11 @@ func TestAcceptMTPDraftsGreedyMismatch(t *testing.T) {
if got := resultIDs(results); !slices.Equal(got, []int{2, 3}) {
t.Fatalf("results = %v, want [2 3]", got)
}
- if position != 1 {
- t.Fatalf("position = %d, want 1", position)
+ if position != 2 {
+ t.Fatalf("position = %d, want 2 (current + accepted)", position)
}
- if got := caches[0].Offset(); got != 1 {
- t.Fatalf("cache offset = %d, want 1 (rolled back to accepted)", got)
+ if got := caches[0].Offset(); got != 2 {
+ t.Fatalf("cache offset = %d, want 2 (rolled back to accepted)", got)
}
}
@@ -335,13 +333,12 @@ func TestAcceptMTPDraftsGreedyEOS(t *testing.T) {
caches, _ := newMTPTestCaches(1)
candidates := scriptedCandidates(r, []int32{2, eos})
- baseLogits := oneHotLogits([]int32{2}).Squeeze(1)
position := caches[0].Offset()
spec := testSpeculationSession(r, caches)
current := sampler.Result{Token: mlx.FromValues([]int32{1}, 1)}
- results, accepted, err := spec.accept(&position, current, oneHotLogits([]int32{1}), baseLogits, candidates)
+ results, accepted, err := spec.accept(&position, current, candidates)
if err != nil {
t.Fatalf("accept: %v", err)
}
@@ -356,11 +353,11 @@ func TestAcceptMTPDraftsGreedyEOS(t *testing.T) {
if len(results) != accepted {
t.Fatalf("results has %d tokens, want exactly the %d accepted with no bonus after EOS", len(results), accepted)
}
- if position != 1 {
- t.Fatalf("position = %d, want 1 (kept draft committed, EOS dropped)", position)
+ if position != 2 {
+ t.Fatalf("position = %d, want 2 (current + kept draft, EOS dropped)", position)
}
- if got := caches[0].Offset(); got != 1 {
- t.Fatalf("cache offset = %d, want 1 (one behind the recorded outputs, EOS dropped)", got)
+ if got := caches[0].Offset(); got != 2 {
+ t.Fatalf("cache offset = %d, want 2 (one behind the recorded outputs, EOS dropped)", got)
}
}
@@ -407,9 +404,9 @@ func TestRunMTPDecodeGreedy(t *testing.T) {
}
// The target writes the caches contiguously: the seed token at offset 1,
- // the round's current token at offset 2, then the 4-token validation
- // forward at offset 3.
- wantForwards := []forwardCall{{offset: 1, n: 1}, {offset: 2, n: 1}, {offset: 3, n: 4}}
+ // then one fused forward validating the current token and the 4 drafts
+ // together at offset 2.
+ wantForwards := []forwardCall{{offset: 1, n: 1}, {offset: 2, n: 5}}
model := r.Model.(*fakeMTPModel)
if !slices.Equal(model.forwards, wantForwards) {
t.Fatalf("target forwards = %v, want %v", model.forwards, wantForwards)
@@ -468,6 +465,65 @@ func TestRunMTPDecodeSampled(t *testing.T) {
}
}
+func TestRunMTPDecodeWarmDrafter(t *testing.T) {
+ skipIfNoMLX(t)
+ // A drafter warmed by a prefill report proposes in the very first round:
+ // the last prompt token seeds the decode loop and is forwarded fused
+ // with the drafts, so generation runs no plain forward at all.
+ const eos int32 = 7
+ predict := map[int32]int32{1: 2, 2: 3, 3: 4, 4: eos, eos: 0}
+ r := mtpTestRunner(t, predict, []int32{eos}, sampler.Options{})
+ draft := &fakeMTPDraft{predict: predict}
+ r.spec = newSpeculation(r, draft)
+
+ caches, _ := newMTPTestCaches(1)
+ session, ch := newMTPTestSession(caches)
+ position := 1 // one prefill token already processed
+
+ req := Request{
+ Responses: ch,
+ Tokens: []int32{0},
+ CompletionRequest: CompletionRequest{Options: api.Options{Runner: api.Runner{DraftNumPredict: 4}, NumPredict: 20}},
+ SamplerOpts: sampler.Options{},
+ }
+ spec := r.spec.open(req, caches)
+ // The prefill chunk's committed report: token 0 at slot 0 with its
+ // hidden row, leaving the drafter ready to propose from slot 1.
+ spec.committed(mlx.FromValues([]int32{0}, 1, 1), oneHotLogits([]int32{1}), 0)
+
+ d := spec.decoder([]int32{1}, position)
+ if err := r.decode(context.Background(), req, session, d, 0); err != nil {
+ t.Fatalf("decode: %v", err)
+ }
+ d.close()
+
+ content, final := collectResponses(ch)
+ if content != "234" {
+ t.Fatalf("content = %q, want %q", content, "234")
+ }
+ if final.DoneReason != 0 {
+ t.Fatalf("DoneReason = %d, want 0 (EOS)", final.DoneReason)
+ }
+ if got := []int32{2, 3, 4, eos}; !slices.Equal(session.outputs, got) {
+ t.Fatalf("session outputs = %v, want %v", session.outputs, got)
+ }
+
+ // One fused forward validates the seed token and all 4 proposals
+ // together at the seed token's slot.
+ wantForwards := []forwardCall{{offset: 1, n: 5}}
+ model := r.Model.(*fakeMTPModel)
+ if !slices.Equal(model.forwards, wantForwards) {
+ t.Fatalf("target forwards = %v, want %v", model.forwards, wantForwards)
+ }
+
+ // Warm drafting anchors at the last reported slot (0) and extends the
+ // seed token through the proposal chain.
+ wantDraft := []draftCall{{0, 1}, {0, 2}, {0, 3}, {0, 4}}
+ if !slices.Equal(draft.calls, wantDraft) {
+ t.Fatalf("draft calls = %v, want %v", draft.calls, wantDraft)
+ }
+}
+
func TestDecodePlain(t *testing.T) {
skipIfNoMLX(t)
// The same chain with no speculationSession: decode's pipelined loop runs,
diff --git a/x/mlxrunner/speculate.go b/x/mlxrunner/speculate.go
index baf9811e3..f0039303c 100644
--- a/x/mlxrunner/speculate.go
+++ b/x/mlxrunner/speculate.go
@@ -228,12 +228,12 @@ func (s *speculationSession) close() {
s.drafter.close()
}
-// speculativeDecoder decodes one speculative round per call: it forwards
-// the current token — emitted by the previous call, so a token that ends
-// generation is never forwarded — has the engine draft and validate ahead
-// of it, and returns the round's accepted tokens followed by the engine's
-// next token. The last returned token becomes the next call's current; the
-// seed token primes current and is never returned.
+// speculativeDecoder decodes one speculative round per call: the engine
+// forwards the current token — emitted by the previous call, so a token
+// that ends generation is never forwarded — fused with the drafter's
+// proposals, and the call returns the round's accepted tokens followed by
+// the engine's next token. The last returned token becomes the next call's
+// current; the seed token primes current and is never returned.
type speculativeDecoder struct {
s *speculationSession
position int
@@ -253,17 +253,7 @@ func (s *speculationSession) decoder(seed []int32, position int) decoder {
}
func (st *speculativeDecoder) next(remaining int) ([]sampler.Result, error) {
- s := st.s
- r := s.spec.r
-
- hidden := r.Model.Forward(&batch.Batch{
- InputIDs: tokenInput(st.current.Token),
- SeqOffsets: []int32{int32(st.position)},
- SeqQueryLens: []int32{1},
- }, s.spec.caches)
- st.position++
-
- results, next, err := s.round(&st.position, st.current, hidden, remaining)
+ results, next, err := st.s.round(&st.position, st.current, remaining)
if err != nil {
return nil, err
}
@@ -288,11 +278,10 @@ func (st *speculativeDecoder) close() {
st.s.logStats()
}
-// round runs one speculative decode round for the just-forwarded current
-// token and its hidden state: draft candidates after it, validate them
-// against the target, and return the accepted run and the bonus or
-// resampled next token.
-func (s *speculationSession) round(position *int, current sampler.Result, hidden *mlx.Array, remaining int) (results []sampler.Result, next sampler.Result, err error) {
+// round runs one speculative decode round: fuse the current token with the
+// drafter's proposals in one target forward, validate the proposals, and
+// return the accepted run and the bonus or resampled next token.
+func (s *speculationSession) round(position *int, current sampler.Result, remaining int) (results []sampler.Result, next sampler.Result, err error) {
r := s.spec.r
s.stats.iterations++
@@ -302,22 +291,27 @@ func (s *speculationSession) round(position *int, current sampler.Result, hidden
// 0 and the last token decodes plainly.
maxDraft := min(s.limit, remaining-1)
candidates := s.drafter.propose(current.Token, maxDraft)
- baseLogits := lastLogits(r.Model.Unembed(hidden))
if candidates == nil {
- s.drafter.committed(tokenInput(current.Token), lastHiddenRow(hidden), *position-1)
- return nil, r.Sampler.Sample([]int{pipelineSlot}, baseLogits), nil
+ // Nothing to validate: a plain single-token round.
+ tok := tokenInput(current.Token)
+ hidden := r.Model.Forward(&batch.Batch{
+ InputIDs: tok,
+ SeqOffsets: []int32{int32(*position)},
+ SeqQueryLens: []int32{1},
+ }, s.spec.caches)
+ *position++
+ s.drafter.committed(tok, hidden, *position-1)
+ return nil, r.Sampler.Sample([]int{pipelineSlot}, lastLogits(r.Model.Unembed(hidden))), nil
}
draftCount := candidates.tokens.Dim(1)
- // hidden survives the sweep alongside the candidates: the post-accept
- // report fuses it into the committed stream.
- candidateArrays := append([]*mlx.Array{baseLogits, hidden}, candidates.Arrays()...)
+ candidateArrays := candidates.Arrays()
mlx.Pin(candidateArrays...)
mlx.Sweep()
defer mlx.Unpin(candidateArrays...)
s.stats.drafted += draftCount
- results, accepted, err := s.accept(position, current, hidden, baseLogits, candidates)
+ results, accepted, err := s.accept(position, current, candidates)
if err != nil {
return nil, sampler.Result{}, err
}
@@ -436,11 +430,11 @@ func commitSpeculation(caches []cache.Cache, accepted, draftCount, before int) {
// already capped to the remaining budget, so an accepted run never
// overshoots, and a legitimate token past the budget is left for decode to
// drop rather than cut here.
-func (s *speculationSession) accept(position *int, current sampler.Result, hidden, baseLogits *mlx.Array, candidates *draftCandidates) (results []sampler.Result, accepted int, err error) {
+func (s *speculationSession) accept(position *int, current sampler.Result, candidates *draftCandidates) (results []sampler.Result, accepted int, err error) {
r := s.spec.r
before := *position
draftCount := candidates.tokens.Dim(1)
- scheduleSpeculation(s.spec.targets, before, draftCount)
+ scheduleSpeculation(s.spec.targets, before+1, draftCount)
// Every exit between schedule and commit must drain the snapshot
// schedule and roll the speculative writes back out of the live caches:
@@ -452,17 +446,21 @@ func (s *speculationSession) accept(position *int, current sampler.Result, hidde
return
}
committed = true
- commitSpeculation(s.spec.targets, keep, draftCount, before)
+ commitSpeculation(s.spec.targets, keep, draftCount, before+1)
}
defer commit(0)
hiddenSeq := r.Model.Forward(&batch.Batch{
- InputIDs: candidates.tokens,
+ InputIDs: current.Token.ExpandDims(-1).Concatenate(1, candidates.tokens),
SeqOffsets: []int32{int32(before)},
- SeqQueryLens: []int32{int32(draftCount)},
+ SeqQueryLens: []int32{int32(draftCount + 1)},
}, s.spec.caches)
- targetDist := r.Sampler.Distribution(pipelineSlot, validationLogits(r, baseLogits, hiddenSeq), candidates.tokens)
+ // Row i of the fused hidden is the state after the token at before+i, so
+ // the rows already line up with the drafts: row 0 (current's state)
+ // predicts draft 0, and the row after the last accepted draft is the
+ // bonus row. No separate base-logits forward exists on this path.
+ targetDist := r.Sampler.Distribution(pipelineSlot, r.Model.Unembed(hiddenSeq), candidates.tokens)
draftDist := candidates.dist
acceptedMask := r.sampleAcceptedMask(targetDist.SliceRows(0, draftCount), draftDist, candidates.tokens)
mlx.Eval(candidates.tokens, acceptedMask)
@@ -482,35 +480,35 @@ func (s *speculationSession) accept(position *int, current sampler.Result, hidde
// Find where an accepted EOS ends the run, before committing, so the cut
// is known while the per-token rollback snapshots still exist.
commitIDs := make([]int32, 0, accepted+1)
+ keep := accepted
done := false
for i, id := range draftIDs[:accepted] {
commitIDs = append(commitIDs, int32(id))
if r.Tokenizer.IsEOS(int32(id)) {
done = true
accepted = i + 1
+ // Leave the EOS's own state uncommitted: the next sequence won't
+ // contain this EOS, and recurrent state can't drop a folded-in
+ // token, so committing it would carry the caches past the
+ // reusable prefix and force the next sequence to recompute.
+ keep = i
break
}
}
- // The final token of a generation is recorded and streamed but its KV
- // is never committed: the caches rest at the trie frontier.
- keep := accepted
- if done {
- keep--
- }
+
commit(keep)
- *position = before + keep
+ *position = before + 1 + keep
// Report the validated run — current plus the kept drafts, with the
- // hidden state at each token's own slot — to the drafter before
+ // fused hidden state at each token's own slot — to the drafter before
// returning, so even a cancelled emission leaves the drafter's state
// describing exactly what the target caches hold. A done generation's
// final token is never committed; it reaches the drafter through finish.
runIDs := append([]int32{int32(current.Token.Int())}, commitIDs[:keep]...)
- runHiddens := lastHiddenRow(hidden)
- if keep > 0 {
- runHiddens = runHiddens.Concatenate(1, hiddenSeq.Slice(mlx.Slice(), mlx.Slice(0, keep), mlx.Slice()))
- }
- s.drafter.committed(mlx.FromValues(runIDs, 1, len(runIDs)), runHiddens, before-1)
+ s.drafter.committed(
+ mlx.FromValues(runIDs, 1, len(runIDs)),
+ hiddenSeq.Slice(mlx.Slice(), mlx.Slice(0, len(runIDs)), mlx.Slice()),
+ before)
results = draftResults(draftIDs[:accepted])
if done {
@@ -533,13 +531,6 @@ func (s *speculationSession) accept(position *int, current sampler.Result, hidde
return results, accepted, nil
}
-// validationLogits stacks the current token's logits ahead of the draft
-// positions' logits so row i scores draft i.
-func validationLogits(r *Runner, baseLogits, hiddenSeq *mlx.Array) *mlx.Array {
- seqLogits := r.Model.Unembed(hiddenSeq)
- return baseLogits.ExpandDims(1).Concatenate(1, seqLogits)
-}
-
func (r *Runner) sampleAcceptedMask(targetDist, draftDist sampler.Distribution, draftTokens *mlx.Array) *mlx.Array {
p := targetDist.Prob(draftTokens)
q := draftDist.Prob(draftTokens)