Get up and running with Kimi, GLM, MiniMax, DeepSeek, gpt-oss, Qwen, Gemma and other models.
mlxrunner: add a block-diffusion drafting session
Jesse Grossc1bf60d7b133
diff --git a/x/mlxrunner/dflash.go b/x/mlxrunner/dflash.gonew file mode 100644index 000000000..768a3be43--- /dev/null+++ b/x/mlxrunner/dflash.go@@ -0,0 +1,180 @@+package mlxrunner++import (+ "fmt"++ "github.com/ollama/ollama/x/mlxrunner/batch"+ "github.com/ollama/ollama/x/mlxrunner/mlx"+ "github.com/ollama/ollama/x/mlxrunner/model/base"+)++// dflashPendingFlushTokens bounds the pinned feature rows between flushes.+const dflashPendingFlushTokens = 256++// dflashDrafter drafts with a block-diffusion draft model (DFlash): one+// forward proposes a whole block. A context-cache entry depends only on its+// own position, so the trie keys need no look-ahead.+type dflashDrafter struct {+ spec *speculation+ blockSize int+ maskToken int32+}++func newDFlashDrafter(s *speculation, draft base.BlockDraft) *dflashDrafter {+ blockSize, maskToken := draft.BlockParams()+ return &dflashDrafter{spec: s, blockSize: blockSize, maskToken: maskToken}+}++func (d *dflashDrafter) draftLimit() int { return d.blockSize - 1 }++// open returns a session synced to the draft caches' restored offset.+func (d *dflashDrafter) open() draftSession {+ s := &dflashDraftSession{drafter: d}+ if kv := d.spec.draftKV; len(kv) > 0 {+ s.ctxOffset = kv[0].Offset()+ }+ return s+}++// dflashDraftSession runs one request's drafting. A context entry at slot S+// derives only from the features at S; ctxOffset+pendingCount is the slot+// after the last reported token.+type dflashDraftSession struct {+ drafter *dflashDrafter++ // ctxOffset is the slot after the last feature row written; pendingCount+ // rows are buffered past it.+ ctxOffset int+ pendingFeatures []*mlx.Array+ pendingCount int++ // blockOutstanding tracks the proposal's scheduled rollback point, which+ // commitBlock has to drain even when it needs no rewind.+ blockOutstanding bool+}++func (d *dflashDraftSession) committed(tokens, features *mlx.Array, position int) {+ n := tokens.Dim(1)+ // Skip leading rows the session already has (a restored prefix). A run+ // that starts past the frontier would leave a gap, which is a bug.+ start := d.ctxOffset + d.pendingCount - position+ if start < 0 {+ panic(fmt.Sprintf("dflash: committed run at %d leaves a context gap at %d", position, d.ctxOffset+d.pendingCount))+ }+ if start < n {+ f := features.Slice(mlx.Slice(), mlx.Slice(start, n), mlx.Slice())+ mlx.Pin(f)+ d.pendingFeatures = append(d.pendingFeatures, f)+ d.pendingCount += n - start+ if d.pendingCount >= dflashPendingFlushTokens {+ d.flush()+ }+ }+}++// settle writes buffered rows through, leveling the draft caches with the+// target's; next is unused.+func (d *dflashDraftSession) settle(_ *mlx.Array) {+ d.flush()+}++func (d *dflashDraftSession) close() {+ d.flush()+}++// takePending returns the buffered rows, advancing ctxOffset past them.+func (d *dflashDraftSession) takePending() *mlx.Array {+ if len(d.pendingFeatures) == 0 {+ return nil+ }+ features := mlx.Concatenate(d.pendingFeatures, 1)+ mlx.Unpin(d.pendingFeatures...)+ d.pendingFeatures = nil+ d.ctxOffset += d.pendingCount+ d.pendingCount = 0+ return features+}++// commitBlock rewinds the round's block out of the draft caches; the caches+// keep only context rows, and accepted tokens arrive as context later. Every+// write path must run this first, otherwise the new rows land after the block+// and the cache contents no longer match their positions.+func (d *dflashDraftSession) commitBlock() {+ if !d.blockOutstanding {+ return+ }+ commitSpeculation(d.drafter.spec.draftKV, 0, 1, d.ctxOffset)+ d.blockOutstanding = false+}++// flush rewinds the round's block, then writes the pending rows in one+// context-only forward. The block is rewound even when nothing is pending.+func (d *dflashDraftSession) flush() {+ spec := d.drafter.spec+ d.commitBlock()++ offset := d.ctxOffset+ features := d.takePending()+ if features == nil {+ return+ }+ spec.draft.Forward(&batch.Batch{+ SeqOffsets: []int32{int32(offset)},+ Hidden: features,+ }, spec.targets, spec.draftKV)++ // Force the cache writes: a session that never drafts would otherwise+ // leave the flush chain unevaluated, pinning every feature until close.+ state := make([]*mlx.Array, 0, 2*len(spec.draftKV))+ for _, c := range spec.draftKV {+ state = append(state, c.State()...)+ }+ mlx.AsyncEval(state...)+}++// propose drafts a block after the not-yet-validated current token, one+// forward filling every mask position.+func (d *dflashDraftSession) propose(current *mlx.Array, maxTokens int) *draftCandidates {+ spec := d.drafter.spec+ r := spec.r+ blockSize := d.drafter.blockSize++ n := min(maxTokens, blockSize-1)+ if n <= 0 || d.ctxOffset+d.pendingCount == 0 {+ return nil+ }+ d.commitBlock()++ // Send only the anchor and the rows being sampled, not the full trained+ // block. Exact for causal layers, and measured as free for bidirectional+ // ones.+ masks := make([]int32, n)+ for i := range masks {+ masks[i] = d.drafter.maskToken+ }+ block := current.ExpandDims(-1).Concatenate(1, mlx.FromValues(masks, 1, len(masks)))++ offset := d.ctxOffset+ features := d.takePending()++ scheduleSpeculation(spec.draftKV, d.ctxOffset, 1)+ d.blockOutstanding = true++ hidden, _ := spec.draft.Forward(&batch.Batch{+ InputIDs: block,+ SeqOffsets: []int32{int32(offset)},+ SeqQueryLens: []int32{int32(n + 1)},+ Hidden: features,+ }, spec.targets, spec.draftKV)++ // Row i predicts the token at its own position, so the anchor row is+ // unused. Rows 1..n are sampled from one batched distribution; penalties+ // see only the committed history, not the other rows of the block.+ logits := spec.draft.Unembed(hidden.Slice(mlx.Slice(), mlx.Slice(1, n+1), mlx.Slice()))+ dist := r.Sampler.Distribution(pipelineSlot, logits, nil)+ tokens := r.Sampler.SampleDistribution(pipelineSlot, dist)+ return &draftCandidates{+ tokens: tokens.ExpandDims(0),+ dist: dist,+ }+}diff --git a/x/mlxrunner/dflash_test.go b/x/mlxrunner/dflash_test.gonew file mode 100644index 000000000..ed323889b--- /dev/null+++ b/x/mlxrunner/dflash_test.go@@ -0,0 +1,347 @@+package mlxrunner++import (+ "context"+ "slices"+ "testing"++ "github.com/ollama/ollama/api"+ "github.com/ollama/ollama/x/mlxrunner/batch"+ "github.com/ollama/ollama/x/mlxrunner/cache"+ "github.com/ollama/ollama/x/mlxrunner/mlx"+ "github.com/ollama/ollama/x/mlxrunner/model/base"+ sampler "github.com/ollama/ollama/x/mlxrunner/sample"+)++// fakeBlockDraft is a block-diffusion draft: one Draft call ingests context+// feature rows and fills a block's mask positions in parallel. It feeds the+// context rows' hot indices and then the block's token ids to its cache+// (advancing the offset like the real model's single write), records each+// call, and scripts block row i as the i-th successor of the anchor under+// predict.+type fakeBlockDraft struct {+ predict map[int32]int32+ blockSize int+ maskToken int32+ draftCaches []cache.Cache+ calls []blockCall+}++// blockCall is one recorded Draft call: the absolute slot of the first+// context row, the hot index of each context feature row (nil for a+// block-only call), and the block's token ids (nil for a context-only call).+type blockCall struct {+ offset int32+ ctx []int32+ block []int32+}++func (d *fakeBlockDraft) LoadWeights(map[string]*mlx.Array) error { return nil }++func (d *fakeBlockDraft) NewCaches() []cache.Cache { return d.draftCaches }++func (d *fakeBlockDraft) BlockParams() (int, int32) { return d.blockSize, d.maskToken }++func (d *fakeBlockDraft) Forward(b *batch.Batch, _, draftCaches []cache.Cache) (hidden, auxHidden *mlx.Array) {+ call := blockCall{offset: b.SeqOffsets[0]}++ if b.Hidden != nil {+ mlx.Eval(b.Hidden)+ call.ctx = make([]int32, b.Hidden.Dim(1))+ flat := b.Hidden.Floats()+ for r := range call.ctx {+ call.ctx[r] = -1+ for v := range mtpTestVocab {+ if flat[r*mtpTestVocab+v] != 0 {+ call.ctx[r] = int32(v)+ break+ }+ }+ }+ }+ if b.InputIDs != nil {+ mlx.Eval(b.InputIDs)+ ids := b.InputIDs.Ints()+ call.block = make([]int32, len(ids))+ for i, id := range ids {+ call.block[i] = int32(id)+ }+ }+ d.calls = append(d.calls, call)++ if rc, ok := draftCaches[0].(*fakeRewindableCache); ok {+ rc.feed(call.ctx)+ rc.feed(call.block)+ }++ if call.block == nil {+ return nil, nil+ }+ // Row i predicts the token at its own position: the anchor row restates+ // the anchor, mask row i the i-th successor of the anchor.+ preds := make([]int32, len(call.block))+ preds[0] = call.block[0]+ for i := 1; i < len(preds); i++ {+ preds[i] = d.predict[preds[i-1]]+ }+ h := oneHotLogits(preds)+ return h, h+}++// Unembed is the identity: the fake's hidden already is its one-hot logits.+func (d *fakeBlockDraft) Unembed(x *mlx.Array) *mlx.Array { return x }++var _ base.BlockDraft = (*fakeBlockDraft)(nil)++// newBlockTestSession wires a runner around a fakeBlockDraft and opens one+// request's drafting session, returning the concrete session for+// internal-state assertions.+func newBlockTestSession(t *testing.T, predict map[int32]int32, blockSize int) (*Runner, *fakeBlockDraft, *dflashDraftSession, []cache.Cache) {+ t.Helper()+ r := mtpTestRunner(t, predict, []int32{7}, sampler.Options{})+ caches, _ := newMTPTestCaches(2) // caches[0] target, caches[1] draft context+ draft := &fakeBlockDraft{predict: predict, blockSize: blockSize, maskToken: 6, draftCaches: caches[1:]}+ r.cache.caches = caches+ r.spec = newSpeculation(r, draft, caches[:1], caches[1:])+ return r, draft, r.spec.drafter.open().(*dflashDraftSession), caches+}++// draftTokensOf reads the draft cache's fed token stream.+func draftTokensOf(caches []cache.Cache) []int32 {+ return caches[1].(*fakeRewindableCache).tokens+}++func TestDFlashCommittedBuffersPastFlushCap(t *testing.T) {+ skipIfNoMLX(t)+ _, draft, session, caches := newBlockTestSession(t, nil, 4)++ // One prefill-sized run at the flush cap writes through immediately in a+ // single context-only Draft call.+ n := dflashPendingFlushTokens+ ids := make([]int32, n)+ for i := range ids {+ ids[i] = int32(i % mtpTestVocab)+ }+ session.committed(mlx.FromValues(ids, 1, n), oneHotLogits(ids), 0)+ if got := len(draft.calls); got != 1 {+ t.Fatalf("draft calls after cap-sized run = %d, want 1", got)+ }+ if got := caches[1].Offset(); got != n {+ t.Fatalf("draft cache offset = %d, want %d", got, n)+ }++ // A run below the cap only buffers; settle writes it through, skipping+ // the leading rows the flush already covered.+ tail := []int32{1, 2, 3}+ session.committed(mlx.FromValues(tail, 1, 3), oneHotLogits(tail), n-1)+ if got := len(draft.calls); got != 1 {+ t.Fatalf("draft calls after buffered run = %d, want 1 (buffered)", got)+ }+ session.settle(nil)+ want := blockCall{offset: int32(n), ctx: []int32{2, 3}}+ if got := draft.calls[1]; got.offset != want.offset || !slices.Equal(got.ctx, want.ctx) || got.block != nil {+ t.Fatalf("settle flush = %+v, want %+v", got, want)+ }+ if got := caches[1].Offset(); got != n+2 {+ t.Fatalf("draft cache offset = %d, want %d (level with reports)", got, n+2)+ }+}++func TestDFlashCommittedGapPanics(t *testing.T) {+ skipIfNoMLX(t)+ _, _, session, _ := newBlockTestSession(t, nil, 4)++ session.committed(mlx.FromValues([]int32{1}, 1, 1), oneHotLogits([]int32{1}), 0)+ defer func() {+ if recover() == nil {+ t.Fatalf("committed run past the frontier did not panic")+ }+ }()+ // The frontier is at slot 1; a run starting at 3 leaves slot 1..2 unfed.+ session.committed(mlx.FromValues([]int32{4}, 1, 1), oneHotLogits([]int32{4}), 3)+}++func TestDFlashRestoredPrefixResumes(t *testing.T) {+ skipIfNoMLX(t)+ r := mtpTestRunner(t, nil, []int32{7}, sampler.Options{})+ caches, _ := newMTPTestCaches(2)+ draft := &fakeBlockDraft{blockSize: 4, maskToken: 6, draftCaches: caches[1:]}+ r.cache.caches = caches+ r.spec = newSpeculation(r, draft, caches[:1], caches[1:])++ // A restored prefix arrives with the draft caches already written.+ restored := []int32{1, 2, 3, 4, 5}+ caches[1].(*fakeRewindableCache).feed(restored)+ session := r.spec.drafter.open().(*dflashDraftSession)+ if session.ctxOffset != len(restored) {+ t.Fatalf("ctxOffset = %d, want %d (synced to restored offset)", session.ctxOffset, len(restored))+ }++ // The resumed prefill's run overlaps the restore point; only the rows+ // past the frontier are buffered and written.+ run := []int32{2, 3, 0, 1}+ session.committed(mlx.FromValues(run, 1, 4), oneHotLogits(run), 3)+ session.settle(nil)+ want := blockCall{offset: 5, ctx: []int32{0, 1}}+ if got := draft.calls[0]; got.offset != want.offset || !slices.Equal(got.ctx, want.ctx) || got.block != nil {+ t.Fatalf("resume flush = %+v, want %+v", got, want)+ }+ if got, wantTok := draftTokensOf(caches), append(restored, 0, 1); !slices.Equal(got, wantTok) {+ t.Fatalf("draft cache = %v, want %v", got, wantTok)+ }+}++func TestDFlashProposeBounds(t *testing.T) {+ skipIfNoMLX(t)+ predict := map[int32]int32{1: 2, 2: 3, 3: 4, 4: 5}+ _, draft, session, _ := newBlockTestSession(t, predict, 4)+ current := mlx.FromValues([]int32{1}, 1)++ // Nothing committed yet: no context to draft from.+ if session.propose(current, 4) != nil {+ t.Fatalf("propose with no context did not decline")+ }+ session.committed(mlx.FromValues([]int32{1}, 1, 1), oneHotLogits([]int32{1}), 0)+ if session.propose(current, 0) != nil {+ t.Fatalf("propose with no budget did not decline")+ }++ // The block caps the draft at blockSize-1 mask rows regardless of budget.+ cand := session.propose(current, 10)+ if cand == nil {+ t.Fatalf("propose declined with context and budget")+ }+ mlx.Eval(cand.tokens)+ if got := cand.tokens.Ints(); !slices.Equal(got, []int{2, 3, 4}) {+ t.Fatalf("draft tokens = %v, want [2 3 4]", got)+ }+ if got, want := draft.calls[0].block, []int32{1, 6, 6, 6}; !slices.Equal(got, want) {+ t.Fatalf("block = %v, want %v (anchor plus blockSize-1 masks)", got, want)+ }+}++func TestDFlashBlockRewoundBeforeContextWrites(t *testing.T) {+ skipIfNoMLX(t)+ predict := map[int32]int32{2: 3, 3: 4, 4: 5}+ _, draft, session, caches := newBlockTestSession(t, predict, 4)++ session.committed(mlx.FromValues([]int32{1}, 1, 1), oneHotLogits([]int32{1}), 0)+ if session.propose(mlx.FromValues([]int32{2}, 1), 3) == nil {+ t.Fatalf("propose declined")+ }+ // The proposal's block sits in the caches until the next write.+ if got, want := draftTokensOf(caches), []int32{1, 2, 6, 6, 6}; !slices.Equal(got, want) {+ t.Fatalf("draft cache after propose = %v, want %v", got, want)+ }++ // The next round's report rewinds the block before appending context, so+ // the accepted tokens' rows land at their true slots.+ run := []int32{2, 3, 4}+ session.committed(mlx.FromValues(run, 1, 3), oneHotLogits(run), 1)+ session.settle(nil)+ if got, want := draftTokensOf(caches), []int32{1, 2, 3, 4}; !slices.Equal(got, want) {+ t.Fatalf("draft cache after settle = %v, want %v (block rewound)", got, want)+ }+ if got := caches[1].Offset(); got != 4 {+ t.Fatalf("draft cache offset = %d, want 4 (level with reports)", got)+ }+ want := blockCall{offset: 1, ctx: []int32{2, 3, 4}}+ if got := draft.calls[1]; got.offset != want.offset || !slices.Equal(got.ctx, want.ctx) || got.block != nil {+ t.Fatalf("context flush = %+v, want %+v", got, want)+ }+}++func TestDFlashCloseDrainsOutstandingBlock(t *testing.T) {+ skipIfNoMLX(t)+ predict := map[int32]int32{2: 3, 3: 4, 4: 5}+ _, _, session, caches := newBlockTestSession(t, predict, 4)++ session.committed(mlx.FromValues([]int32{1}, 1, 1), oneHotLogits([]int32{1}), 0)+ if session.propose(mlx.FromValues([]int32{2}, 1), 3) == nil {+ t.Fatalf("propose declined")+ }+ // A session that ends with a proposal in flight still leaves the caches+ // level: close rewinds the block even with nothing pending to flush.+ session.close()+ if got, want := draftTokensOf(caches), []int32{1}; !slices.Equal(got, want) {+ t.Fatalf("draft cache after close = %v, want %v", got, want)+ }+}++func TestDecodeBlockDraft(t *testing.T) {+ skipIfNoMLX(t)+ // The block draft mirrors the target chain, so one proposal round accepts+ // every draft and the bonus token is the EOS.+ const eos int32 = 7+ predict := map[int32]int32{1: 2, 2: 3, 3: 4, 4: 5, 5: eos, eos: 0}+ r := mtpTestRunner(t, predict, []int32{eos}, sampler.Options{})+ caches, _ := newMTPTestCaches(2)+ draft := &fakeBlockDraft{predict: predict, blockSize: 3, maskToken: 6, draftCaches: caches[1:]}+ r.cache.caches = caches+ r.spec = newSpeculation(r, draft, caches[:1], caches[1:])+ session, ch := newMTPTestSession(caches)++ req := Request{+ Responses: ch,+ Tokens: []int32{1},+ CompletionRequest: CompletionRequest{Options: api.Options{NumPredict: 20}},+ SamplerOpts: sampler.Options{},+ }+ spec := r.spec.open(req)+ if spec == nil || !spec.enabled {+ t.Fatalf("open rejected a block-draft request")+ }+ pinDraftLimit(spec, 4)+ d := spec.decoder(mlx.FromValues([]int32{1}, 1), 0)+ if err := r.decode(context.Background(), req, session, d, 0); err != nil {+ t.Fatalf("decode: %v", err)+ }+ d.close()+ spec.close()++ content, final := collectResponses(ch)+ if content != "2345" {+ t.Fatalf("content = %q, want %q", content, "2345")+ }+ if !final.Done || final.DoneReason != 0 {+ t.Fatalf("final = %+v, want Done with EOS reason", final)+ }+ if want := []int32{2, 3, 4, 5, eos}; !slices.Equal(session.outputs, want) {+ t.Fatalf("session outputs = %v, want %v", session.outputs, want)+ }++ // The unprimed drafter parks the first call, so two tokens decode as+ // pipelined plain forwards; the resumed round then validates the current+ // token and blockSize-1 drafts in one fused forward.+ wantForwards := []forwardCall{{offset: 0, n: 1}, {offset: 1, n: 1}, {offset: 2, n: 3}}+ model := r.Model.(*fakeMTPModel)+ if !slices.Equal(model.forwards, wantForwards) {+ t.Fatalf("target forwards = %v, want %v", model.forwards, wantForwards)+ }++ // Ending the parked stretch settles the buffered context through, so the+ // proposal runs block-only; close's flush then writes the accepted rows+ // after rewinding the block.+ wantCalls := []blockCall{+ {offset: 0, ctx: []int32{2, 3}},+ {offset: 2, block: []int32{3, 6, 6}},+ {offset: 2, ctx: []int32{4, 5, 7}},+ }+ if len(draft.calls) != len(wantCalls) {+ t.Fatalf("draft calls = %+v, want %+v", draft.calls, wantCalls)+ }+ for i, want := range wantCalls {+ got := draft.calls[i]+ if got.offset != want.offset || !slices.Equal(got.ctx, want.ctx) || !slices.Equal(got.block, want.block) {+ t.Fatalf("draft call %d = %+v, want %+v", i, got, want)+ }+ }++ // The draft caches end level with the target, holding only context rows.+ if got, want := caches[1].Offset(), caches[0].Offset(); got != want {+ t.Fatalf("draft cache offset = %d, want %d (level with target)", got, want)+ }+ if toks := draftTokensOf(caches); slices.Contains(toks, 6) {+ t.Fatalf("draft cache retains block rows: %v", toks)+ }+}diff --git a/x/mlxrunner/model/base/base.go b/x/mlxrunner/model/base/base.goindex 97c185ce7..243ac688e 100644--- a/x/mlxrunner/model/base/base.go+++ b/x/mlxrunner/model/base/base.go@@ -52,6 +52,17 @@ type DraftModel interface {Unembed(x *mlx.Array) *mlx.Array}+// BlockDraft is a DraftModel that drafts a whole block per forward (block+// diffusion), conditioned on features tapped from target layers rather than+// the final hidden state.+type BlockDraft interface {+ DraftModel++ // BlockParams returns the trained block length and the mask token+ // standing in for undrafted positions.+ BlockParams() (blockSize int, maskToken int32)+}+// SelfDraft is implemented by models whose draft head ships inline with the// target weights; it returns the head, or nil when the checkpoint shipped none.type SelfDraft interface {diff --git a/x/mlxrunner/mtp.go b/x/mlxrunner/mtp.goindex bc97fd106..2fe1063b0 100644--- a/x/mlxrunner/mtp.go+++ b/x/mlxrunner/mtp.go@@ -29,9 +29,13 @@ func newMTPDrafter(s *speculation) *mtpDrafter {return &mtpDrafter{spec: s}}+// draftLimit reports no bound; the head makes one call per draft token, so+// any depth is reachable.+func (d *mtpDrafter) draftLimit() int { return 0 }+// open returns the drafting session for one request, its pairing frontier// synced to the draft caches' restored offset.-func (d *mtpDrafter) open() *mtpDraftSession {+func (d *mtpDrafter) open() draftSession {s := &mtpDraftSession{drafter: d}if kv := d.spec.draftKV; len(kv) > 0 {// A restored prefix arrives with the draft caches already written;diff --git a/x/mlxrunner/speculate.go b/x/mlxrunner/speculate.goindex 97316bdd5..7afafe84c 100644--- a/x/mlxrunner/speculate.go+++ b/x/mlxrunner/speculate.go@@ -11,9 +11,9 @@ import (sampler "github.com/ollama/ollama/x/mlxrunner/sample")-// drafter proposes speculative tokens for the engine to validate, learning-// the conversation through the committed-stream reports.-type drafter interface {+// draftSession proposes speculative tokens for one request, learning the+// conversation through the committed-stream reports.+type draftSession interface {// propose returns up to maxTokens draft tokens with their proposal// distributions, or nil to decode this round plainly.propose(current *mlx.Array, maxTokens int) *draftCandidates@@ -43,20 +43,32 @@ type speculation struct {r *Runnerdraft base.DraftModel- // targets are the model's slots — what speculation snapshots and rolls- // back; draftKV the drafter's. Built at load, stable for the model's life.+ // targets are the model's cache slots, which speculation snapshots and+ // rolls back; draftKV are the drafter's. Both are built at load and+ // never change.targets []cache.CachedraftKV []cache.Cache- // drafter is the persistent half of the MTP drafting machinery; each+ // drafter is the persistent half of the drafting machinery; each// request's session comes from drafter.open.- drafter *mtpDrafter+ drafter drafter// depth selects each request's draft length and owns the cost/acceptance// models and probe cadence it learns across requests.depth *depthController}+// drafter is the per-model half of a drafting implementation, opening each+// request's drafting session.+type drafter interface {+ open() draftSession++ // draftLimit is the deepest draft this drafter can produce, 0 when nothing+ // bounds it. A depth past it is never measured, so the depth search must+ // not schedule one.+ draftLimit() int+}+// newSpeculation builds the speculative-decoding subsystem for a loaded model,// or nil when the checkpoint ships no draft head.func newSpeculation(r *Runner, draft base.DraftModel, targets, draftKV []cache.Cache) *speculation {@@ -64,7 +76,12 @@ func newSpeculation(r *Runner, draft base.DraftModel, targets, draftKV []cache.Creturn nil}s := &speculation{r: r, draft: draft, targets: targets, draftKV: draftKV, depth: newDepthController()}- s.drafter = newMTPDrafter(s)+ if bd, ok := draft.(base.BlockDraft); ok {+ s.drafter = newDFlashDrafter(s, bd)+ } else {+ s.drafter = newMTPDrafter(s)+ }+ s.depth.drafterLimit = s.drafter.draftLimit()return s}@@ -73,7 +90,7 @@ func newSpeculation(r *Runner, draft base.DraftModel, targets, draftKV []cache.C// decode.type speculationSession struct {spec *speculation- drafter drafter+ drafter draftSessionenabled bool // whether this request drafts; false parks (maintain-only)limit int // current draft lengthstats specStats@@ -102,7 +119,6 @@ func (s *speculation) open(request Request) *speculationSession {spec := &speculationSession{spec: s, drafter: d, enabled: enabled, prevDrafts: -1, roundDrafts: -1}if enabled {spec.limit = s.depth.scheduled- spec.stats.maxDraft = spec.limit}return spec}@@ -126,6 +142,7 @@ func (s *speculationSession) beginRound() {// positions past it (a terminator, not a target rejection).func (s *speculationSession) endRound(drafted, accepted, observed int) {s.roundDrafts = drafted+ s.stats.maxDraft = max(s.stats.maxDraft, drafted)s.stats.recordRound(drafted)s.stats.iterations++s.stats.drafted += drafted@@ -135,7 +152,6 @@ func (s *speculationSession) endRound(drafted, accepted, observed int) {s.spec.depth.acc.observe(observed, accepted)}s.limit = s.spec.depth.next()- s.stats.maxDraft = max(s.stats.maxDraft, s.limit)}}diff --git a/x/mlxrunner/speculate_depth.go b/x/mlxrunner/speculate_depth.goindex 83a328c42..b4a5558e1 100644--- a/x/mlxrunner/speculate_depth.go+++ b/x/mlxrunner/speculate_depth.go@@ -18,10 +18,11 @@ const depthProbeInterval = 4const depthProbeIntervalMax = 512// depthController drafts argmax_N EV(N) where EV(N) = committed(N) / cost(N), over-// depths from 0 (plain decode) up to one past the frontier. The depth-0 floor lets-// it stop speculating when no draft pays; the frontier ceiling keeps it from scoring-// a depth on the optimistic inherited rate, so it climbs outward one position at a-// time as acceptance is measured rather than leaping deep.+// depths from 0 (plain decode) up to one past the frontier, or the drafter's limit+// where that is shallower. The depth-0 floor lets it stop speculating when no draft+// pays; the frontier ceiling keeps it from scoring a depth on the optimistic+// inherited rate, so it climbs outward one position at a time as acceptance is+// measured rather than leaping deep.//// It holds the depth-selection state learned across requests — the target forward's// per-depth cost curve, the drafts' per-position acceptance rates, the probe cadence,@@ -32,6 +33,11 @@ type depthController struct {acc *acceptanceModelprobed bool // the previous round drafted a probe+ // drafterLimit is the deepest draft this model's drafter can produce, 0 when+ // nothing bounds it. A depth the drafter never produces is never measured,+ // and an unmeasured depth would always look best, pinning the search there.+ drafterLimit int+// scheduled is the draft depth next() chose for the upcoming round, carried// across requests so a new request's first round consumes it instead of// recomputing at the boundary. Its zero value is the depth-0 warmup start.@@ -49,9 +55,19 @@ func newDepthController() *depthController {func (c *depthController) frontier() int { return c.acc.frontier() }-// next returns the draft depth for the upcoming step: the EV-optimal depth (capped-// at frontier+1), except periodically it probes one past the selection to refresh-// the next position up. The probe stays within the frontier window. The cadence+// limit is the deepest depth the search considers: one past the frontier, held+// to what the drafter can produce.+func (c *depthController) limit() int {+ limit := c.frontier() + 1+ if c.drafterLimit > 0 {+ limit = min(limit, c.drafterLimit)+ }+ return limit+}++// next returns the draft depth for the upcoming step: the EV-optimal depth (held+// to the search limit), except periodically it probes one past the selection to+// refresh the next position up. The probe stays within that limit. The cadence// doubles toward its cap while probes change nothing and resets on any selection// change, giving the new selection a full interval to settle. The chosen depth is// recorded in c.scheduled for the next request's open to consume.@@ -70,7 +86,7 @@ func (c *depthController) next() (depth int) {c.probeSince++if c.probeSince >= c.probeInterval {c.probeSince = 0- if probe := min(sel+1, c.frontier()+1); probe != sel {+ if probe := min(sel+1, c.limit()); probe != sel {c.probed = truereturn probe}@@ -87,11 +103,11 @@ func (c *depthController) next() (depth int) {return sel}-// costSeedDepth is the shallowest depth in [0, frontier+1] with no clean-// cost sample, or -1 if all are sampled; bounding to frontier+1 keeps cost-seeding-// from outrunning the acceptance frontier.+// costSeedDepth is the shallowest depth within the search limit with no clean+// cost sample, or -1 if all are sampled; the bound keeps cost-seeding from+// outrunning the acceptance frontier or the drafter.func (c *depthController) costSeedDepth() int {- limit := c.frontier() + 1+ limit := c.limit()for n := 0; n <= limit; n++ {if !c.cost.sampled(n) {return n@@ -101,14 +117,14 @@ func (c *depthController) costSeedDepth() int {}// selected returns the EV-optimal draft depth without mutating probe state, the-// argmax over [0, frontier+1]. The frontier bound keeps the inherited optimistic+// argmax within the search limit. The frontier bound keeps the inherited optimistic// rate from making ever-deeper depths look best; the depth-0 floor lets it stop// speculating. Returns 0 until the cost model can compare depths.func (c *depthController) selected() int {if !c.cost.ready() {return 0}- limit := c.frontier() + 1+ limit := c.limit()best, bestEV := 0, c.acc.expectedCommitted(0)/c.cost.cost(0)for n := 1; n <= limit; n++ {if ev := c.acc.expectedCommitted(n) / c.cost.cost(n); ev > bestEV {diff --git a/x/mlxrunner/speculate_stats.go b/x/mlxrunner/speculate_stats.goindex 68ad82342..f357b23d1 100644--- a/x/mlxrunner/speculate_stats.go+++ b/x/mlxrunner/speculate_stats.go@@ -66,7 +66,7 @@ func (s *speculationSession) logStats() {}// Log learned acceptance over the trusted positions [1, frontier] and- // expected throughput over the searched window [0, frontier+1]; deeper+ // expected throughput over the searched window [0, limit]; deeper// depths have no data of their own.d := s.spec.depthfrontier := d.frontier()@@ -74,7 +74,7 @@ func (s *speculationSession) logStats() {for n := 1; n <= frontier; n++ {rates = append(rates, fmt.Sprintf("%d:%.2f", n, d.acc.acceptance(n)))}- limit := frontier + 1+ limit := d.limit()tps := make([]string, 0, limit+1)if d.cost.ready() {for n := 0; n <= limit; n++ {