Skip to content

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

mlxrunner: enable speculative decoding under structured output

Jesse Gross4986e92379f1
diff --git a/x/mlxrunner/grammar.go b/x/mlxrunner/grammar.go
index f5b66314e..56a24a66f 100644
--- a/x/mlxrunner/grammar.go
+++ b/x/mlxrunner/grammar.go
@@ -340,16 +340,14 @@ func (e *grammarEngine) hasGrammar(grammars []*grammar) bool {
return false
}
-// accept advances a batch's grammars over its newly committed tokens —
-// every row's grammar accepts the row's token, constraining or not, with
-// grammars[i] and committed[i] aligned. Each token was sampled under its
-// own matcher's mask, so a rejection is an engine fault; errs[i] carries
-// row i's fault, which ends that request rather than the runner, and errs
-// is nil when every row succeeded.
+// accept advances each constraining row grammar over the row's newly
+// committed token, grammars[i] and committed[i] aligned. errs[i] carries a
+// row's rejection or fault, which ends that request rather than the runner;
+// errs is nil when every row succeeded.
func (e *grammarEngine) accept(grammars []*grammar, committed []int32) []error {
var errs []error
for i, g := range grammars {
- if g == nil {
+ if !g.constraining() {
continue
}
if err := g.m.Accept(committed[i]); err != nil {
@@ -362,44 +360,95 @@ func (e *grammarEngine) accept(grammars []*grammar, committed []int32) []error {
return errs
}
-// mask fills each constraining row's packed token mask and applies them to
-// the batch's logits in one device op, logits row i masked under
-// grammars[i]. Unconstrained, terminated, and failed rows keep their logits
-// (all-ones mask rows add zero). errs as in accept.
-func (e *grammarEngine) mask(grammars []*grammar, logits *mlx.Array) (*mlx.Array, []error) {
- var errs []error
- packed := make([]int32, len(grammars)*e.words)
+// mask fills and applies each constraining row grammar's token masks over
+// the batch's [B, L, V] logits: row b's position i constrains the token
+// after drafts[b][:i], with nil drafts masking one position per row from
+// the current state. Each matcher advances through its drafts as the
+// positions fill and is rolled back before returning, so its state is
+// unchanged; positions past a rejected draft stay unmasked.
+func (e *grammarEngine) mask(grammars []*grammar, logits *mlx.Array, drafts [][]int32) (*mlx.Array, []error) {
+ positions := 1
+ for _, ids := range drafts {
+ positions = max(positions, len(ids)+1)
+ }
+ packed := make([]int32, len(grammars)*positions*e.words)
for i := range packed {
packed[i] = -1
}
+ var errs []error
apply := false
- for i, g := range grammars {
+ for b, g := range grammars {
if !g.constraining() {
continue
}
- row := packed[i*e.words : (i+1)*e.words]
- constrained, err := g.m.Fill(row)
+ var ids []int32
+ if drafts != nil {
+ ids = drafts[b]
+ }
+ block := packed[b*positions*e.words : (b+1)*positions*e.words]
+ constrains, err := e.fill(g, block, ids)
if err != nil {
if errs == nil {
errs = make([]error, len(grammars))
}
- errs[i] = fmt.Errorf("grammar: fill token mask: %w", err)
- continue
- }
- // An all-zero mask would send every logit to -inf and sampling to NaN.
- if constrained && !slices.ContainsFunc(row, func(w int32) bool { return w != 0 }) {
- if errs == nil {
- errs = make([]error, len(grammars))
+ errs[b] = err
+ // Nothing from a faulted row may constrain.
+ for j := range block {
+ block[j] = -1
}
- errs[i] = errors.New("grammar: token mask rejects every vocabulary token")
continue
}
- apply = apply || constrained
+ apply = apply || constrains
}
if !apply {
return logits, errs
}
- return e.apply(logits, mlx.FromValues(packed, len(grammars), e.words)), errs
+ rows := len(grammars) * positions
+ masked := e.apply(logits.Reshape(rows, logits.Dim(2)), mlx.FromValues(packed, rows, e.words))
+ return masked.Reshape(len(grammars), positions, logits.Dim(2)), errs
+}
+
+// fill fills one row's per-position masks, advancing the matcher through
+// the drafts and rolling the whole advance back before returning.
+func (e *grammarEngine) fill(g *grammar, packed []int32, ids []int32) (bool, error) {
+ constrains := false
+ advanced := 0
+ var walkErr error
+ for i := range len(ids) + 1 {
+ row := packed[i*e.words : (i+1)*e.words]
+ constrained, err := g.m.Fill(row)
+ if err != nil {
+ walkErr = fmt.Errorf("grammar: fill token mask: %w", err)
+ break
+ }
+ if constrained && !slices.ContainsFunc(row, func(w int32) bool { return w != 0 }) {
+ // No token continues this state: fatal at position 0, whose state
+ // is committed; a later position is left unmasked, and a run kept
+ // into it fails at its accept.
+ if i == 0 {
+ walkErr = errors.New("grammar: token mask rejects every vocabulary token")
+ } else {
+ for j := range row {
+ row[j] = -1
+ }
+ }
+ break
+ }
+ constrains = constrains || constrained
+ if i == len(ids) {
+ break
+ }
+ if g.m.Accept(ids[i]) != nil {
+ // A rejected draft ends the walk; a fault resurfaces at the
+ // committed run's accept.
+ break
+ }
+ advanced++
+ }
+ if err := g.m.Rollback(advanced); err != nil && walkErr == nil {
+ walkErr = fmt.Errorf("grammar: rollback draft tokens: %w", err)
+ }
+ return constrains, walkErr
}
// apply masks logits under packed token masks, one row per sequence: logits
diff --git a/x/mlxrunner/grammar_mask_test.go b/x/mlxrunner/grammar_mask_test.go
index 638d38cba..36bcc9988 100644
--- a/x/mlxrunner/grammar_mask_test.go
+++ b/x/mlxrunner/grammar_mask_test.go
@@ -1,11 +1,16 @@
package mlxrunner
import (
+ "errors"
+ "io/fs"
"math"
+ "path/filepath"
+ "slices"
"testing"
"github.com/ollama/ollama/x/internal/mlxtest"
"github.com/ollama/ollama/x/mlxrunner/mlx"
+ "github.com/ollama/ollama/x/mlxrunner/xgrammar"
)
func TestApplyTokenMask(t *testing.T) {
@@ -28,6 +33,7 @@ func TestApplyTokenMask(t *testing.T) {
}
e := &grammarEngine{}
e.initMask(vocabSize)
+ t.Cleanup(e.close)
logits := mlx.Zeros(mlx.DTypeFloat32, 1, vocabSize)
masked := e.apply(logits, mlx.FromValues(packed, 1, len(packed)))
mlx.Eval(masked)
@@ -48,3 +54,309 @@ func TestApplyTokenMask(t *testing.T) {
}
})
}
+
+const (
+ draftTestEOS int32 = 32
+ draftTestVocab int = 40
+)
+
+func draftTestVocabulary() []string {
+ pieces := []string{
+ "{", "}", `"`, ":", ",", "a", "n", "s", "w", "e", "r", "o", "k", " ",
+ "1", "2", "[", "]", "true", "false", "ok", "answer",
+ }
+ for len(pieces) < draftTestVocab {
+ pieces = append(pieces, "")
+ }
+ pieces[draftTestEOS] = "<eos>"
+ return pieces
+}
+
+func draftPieceIDs(t *mlxtest.T, pieces ...string) []int32 {
+ t.Helper()
+ vocab := draftTestVocabulary()
+ ids := make([]int32, len(pieces))
+ for i, piece := range pieces {
+ id := slices.Index(vocab, piece)
+ if id < 0 {
+ t.Fatalf("test vocabulary does not contain %q", piece)
+ }
+ ids[i] = int32(id)
+ }
+ return ids
+}
+
+// testDraftGrammar builds a grammar over the small draft-test vocabulary and
+// an engine sized to match, skipping when the native payloads are not built.
+func testDraftGrammar(t *mlxtest.T, schema string) (*grammarEngine, *grammar) {
+ t.Helper()
+ path, err := mlx.LoadedLibraryPath()
+ if err != nil {
+ t.Skipf("native MLX payload is not built: %v", err)
+ }
+ compiler, err := xgrammar.New(filepath.Dir(path), draftTestVocabulary(), draftTestVocab, []int32{draftTestEOS}, 8, 128<<20)
+ if err != nil {
+ if errors.Is(err, fs.ErrNotExist) {
+ t.Skipf("native xgrammar payload is not built: %v", err)
+ }
+ t.Fatal(err)
+ }
+ t.Cleanup(compiler.Close)
+ m, err := compiler.Compile(xgrammar.JSONSchema, schema)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(m.Close)
+ e := &grammarEngine{}
+ e.initMask(draftTestVocab)
+ t.Cleanup(e.close)
+ return e, &grammar{m: m}
+}
+
+// requireSameMask asserts two matchers fill identical masks, proving their
+// parser states are equivalent.
+func requireSameMask(t *mlxtest.T, got, want *grammar, vocab int) {
+ t.Helper()
+ words := (vocab + 31) / 32
+ gotRow, wantRow := make([]int32, words), make([]int32, words)
+ gotConstrained, err := got.m.Fill(gotRow)
+ if err != nil {
+ t.Fatal(err)
+ }
+ wantConstrained, err := want.m.Fill(wantRow)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if gotConstrained != wantConstrained || !slices.Equal(gotRow, wantRow) {
+ t.Fatalf("mask %v %032b, want %v %032b", gotConstrained, gotRow, wantConstrained, wantRow)
+ }
+}
+
+// acceptRun advances a grammar over committed tokens through the engine's
+// accept, failing the test on any rejection.
+func acceptRun(t *mlxtest.T, e *grammarEngine, g *grammar, ids []int32) {
+ t.Helper()
+ for _, id := range ids {
+ if err := errors.Join(e.accept([]*grammar{g}, []int32{id})...); err != nil {
+ t.Fatal(err)
+ }
+ }
+}
+
+// maskedRows evaluates mask's logits, returning per-row allowed flags.
+func maskedRows(t *mlxtest.T, masked *mlx.Array, rows int) [][]bool {
+ t.Helper()
+ mlx.Eval(masked)
+ vals := masked.Floats()
+ out := make([][]bool, rows)
+ for i := range rows {
+ out[i] = make([]bool, draftTestVocab)
+ for id := range draftTestVocab {
+ out[i][id] = !math.IsInf(float64(vals[i*draftTestVocab+id]), -1)
+ }
+ }
+ return out
+}
+
+const draftTestSchema = `{"type":"object","properties":{"answer":{"type":"string","enum":["ok"]}},"required":["answer"],"additionalProperties":false}`
+
+func TestMaskDraftPositions(t *testing.T) {
+ mlxtest.Run(t, func(t *mlxtest.T) {
+ e, g := testDraftGrammar(t, draftTestSchema)
+ _, shadow := testDraftGrammar(t, draftTestSchema)
+
+ drafts := draftPieceIDs(t, "{", `"`, "answer")
+ logits := mlx.Zeros(mlx.DTypeFloat32, 1, len(drafts)+1, draftTestVocab)
+ masked, errs := e.mask([]*grammar{g}, logits, [][]int32{drafts})
+ if errs != nil {
+ t.Fatal(errs)
+ }
+ // The walk left no matcher state behind: the mask matches a fresh shadow's.
+ requireSameMask(t, g, shadow, draftTestVocab)
+
+ rows := maskedRows(t, masked, len(drafts)+1)
+ open := draftPieceIDs(t, "{", "}")
+ if !rows[0][open[0]] || rows[0][open[1]] {
+ t.Fatal("row 0 does not constrain to the object opener")
+ }
+ for i, id := range drafts {
+ if !rows[i][id] {
+ t.Fatalf("row %d masks its own draft token %d", i, id)
+ }
+ }
+ quote := draftPieceIDs(t, `"`)[0]
+ if !rows[3][quote] {
+ t.Fatal("bonus row masks the value-opening quote")
+ }
+
+ // Verification rejects the third draft; the committed run reaches the
+ // grammar through accept, like every emitted token.
+ final := draftPieceIDs(t, "answer")[0]
+ run := append(drafts[:2:2], final)
+ acceptRun(t, e, g, run)
+ for _, id := range run {
+ if err := shadow.m.Accept(id); err != nil {
+ t.Fatalf("shadow accept %d: %v", id, err)
+ }
+ }
+ requireSameMask(t, g, shadow, draftTestVocab)
+ })
+}
+
+func TestMaskStopsAtRejectedDraft(t *testing.T) {
+ mlxtest.Run(t, func(t *mlxtest.T) {
+ e, g := testDraftGrammar(t, draftTestSchema)
+ _, shadow := testDraftGrammar(t, draftTestSchema)
+
+ // "}" is invalid after "{": the answer property is required.
+ drafts := draftPieceIDs(t, "{", "}", `"`)
+ logits := mlx.Zeros(mlx.DTypeFloat32, 1, len(drafts)+1, draftTestVocab)
+ masked, errs := e.mask([]*grammar{g}, logits, [][]int32{drafts})
+ if errs != nil {
+ t.Fatal(errs)
+ }
+ requireSameMask(t, g, shadow, draftTestVocab)
+
+ rows := maskedRows(t, masked, len(drafts)+1)
+ if rows[1][drafts[1]] {
+ t.Fatal("row 1 allows the invalid draft")
+ }
+ for i := 2; i < len(rows); i++ {
+ for id, ok := range rows[i] {
+ if !ok {
+ t.Fatalf("unreached row %d masks token %d", i, id)
+ }
+ }
+ }
+ })
+}
+
+func TestMaskCrossesAnAcceptedStop(t *testing.T) {
+ mlxtest.Run(t, func(t *mlxtest.T) {
+ e, g := testDraftGrammar(t, `{"type":"object"}`)
+
+ drafts := draftPieceIDs(t, "{", "}", "<eos>")
+ logits := mlx.Zeros(mlx.DTypeFloat32, 1, len(drafts)+1, draftTestVocab)
+ masked, errs := e.mask([]*grammar{g}, logits, [][]int32{drafts})
+ if errs != nil {
+ t.Fatal(errs)
+ }
+ rows := maskedRows(t, masked, len(drafts)+1)
+ if !rows[2][draftTestEOS] {
+ t.Fatal("row 2 masks EOS after the object completes")
+ }
+ // The walk accepts the stop and the restore un-terminates: the position
+ // past it is unconstrained, and the matcher replays from the start.
+ for id, ok := range rows[3] {
+ if !ok {
+ t.Fatalf("row past the stop masks token %d", id)
+ }
+ }
+ if g.m.Terminated() {
+ t.Fatal("matcher terminated after the restore")
+ }
+ acceptRun(t, e, g, drafts)
+ if !g.m.Terminated() {
+ t.Fatal("matcher not terminated after the committed EOS")
+ }
+ // A terminated grammar accepts nothing further and needs nothing
+ // accepted: the row is skipped, not faulted.
+ if err := errors.Join(e.accept([]*grammar{g}, []int32{drafts[0]})...); err != nil {
+ t.Fatalf("accept after termination: %v", err)
+ }
+ })
+}
+
+func TestMaskLeavesDeadPositionsUnmasked(t *testing.T) {
+ mlxtest.Run(t, func(t *mlxtest.T) {
+ // After `{"` this schema requires a property name no vocabulary piece can
+ // start, so that position's fill rejects every token.
+ schema := `{"type":"object","properties":{"z":{"type":"string"}},"required":["z"],"additionalProperties":false}`
+ e, g := testDraftGrammar(t, schema)
+ _, shadow := testDraftGrammar(t, schema)
+
+ drafts := draftPieceIDs(t, "{", `"`)
+ logits := mlx.Zeros(mlx.DTypeFloat32, 1, len(drafts)+1, draftTestVocab)
+ masked, errs := e.mask([]*grammar{g}, logits, [][]int32{drafts})
+ if errs != nil {
+ t.Fatal(errs)
+ }
+ requireSameMask(t, g, shadow, draftTestVocab)
+ rows := maskedRows(t, masked, len(drafts)+1)
+ if !rows[0][drafts[0]] || !rows[1][drafts[1]] {
+ t.Fatal("leading rows mask their own drafts")
+ }
+ for id, ok := range rows[2] {
+ if !ok {
+ t.Fatalf("dead position masks token %d", id)
+ }
+ }
+ // A run committed into the dead state fails at its accept.
+ acceptRun(t, e, g, drafts)
+ if err := errors.Join(e.accept([]*grammar{g}, draftPieceIDs(t, "a"))...); err == nil {
+ t.Fatal("accept into a dead grammar state unexpectedly succeeded")
+ }
+
+ // At position 0 the dead state is already committed: the row fails.
+ e0, g0 := testDraftGrammar(t, `{"enum":[3]}`)
+ logits0 := mlx.Zeros(mlx.DTypeFloat32, 1, 2, draftTestVocab)
+ if _, errs := e0.mask([]*grammar{g0}, logits0, [][]int32{draftPieceIDs(t, "1")}); errs == nil || errs[0] == nil {
+ t.Fatal("dead position 0 did not fail the row")
+ }
+ })
+}
+
+func TestMaskBatchesRows(t *testing.T) {
+ mlxtest.Run(t, func(t *mlxtest.T) {
+ e, g0 := testDraftGrammar(t, draftTestSchema)
+ _, shadow0 := testDraftGrammar(t, draftTestSchema)
+ _, g1 := testDraftGrammar(t, `{"type":"object"}`)
+ _, shadow1 := testDraftGrammar(t, `{"type":"object"}`)
+
+ // Ragged rows: row 0 advances three drafts, row 1 one; row 1's tail
+ // positions pad with all-ones.
+ drafts := [][]int32{draftPieceIDs(t, "{", `"`, "answer"), draftPieceIDs(t, "{")}
+ logits := mlx.Zeros(mlx.DTypeFloat32, 2, 4, draftTestVocab)
+ masked, errs := e.mask([]*grammar{g0, g1}, logits, drafts)
+ if errs != nil {
+ t.Fatal(errs)
+ }
+ requireSameMask(t, g0, shadow0, draftTestVocab)
+ requireSameMask(t, g1, shadow1, draftTestVocab)
+
+ rows := maskedRows(t, masked, 8)
+ if !rows[4][drafts[1][0]] {
+ t.Fatal("row 1 position 0 masks its own draft")
+ }
+ // The bands differ where the schemas do: only the permissive object may
+ // close immediately after the opener.
+ closeID := draftPieceIDs(t, "}")[0]
+ if rows[1][closeID] {
+ t.Fatal("strict schema allows closing an empty object")
+ }
+ if !rows[5][closeID] {
+ t.Fatal("permissive schema masks closing an empty object")
+ }
+ for id, ok := range rows[6] {
+ if !ok {
+ t.Fatalf("padding position masks token %d", id)
+ }
+ }
+
+ // Each row's committed run reconciles against its own matcher.
+ acceptRun(t, e, g0, append(drafts[0][:2:2], draftPieceIDs(t, "answer")[0]))
+ acceptRun(t, e, g1, []int32{drafts[1][0], closeID})
+ for _, id := range draftPieceIDs(t, "{", `"`, "answer") {
+ if err := shadow0.m.Accept(id); err != nil {
+ t.Fatalf("shadow accept %d: %v", id, err)
+ }
+ }
+ for _, id := range []int32{draftPieceIDs(t, "{")[0], closeID} {
+ if err := shadow1.m.Accept(id); err != nil {
+ t.Fatalf("shadow accept %d: %v", id, err)
+ }
+ }
+ requireSameMask(t, g0, shadow0, draftTestVocab)
+ requireSameMask(t, g1, shadow1, draftTestVocab)
+ })
+}
diff --git a/x/mlxrunner/grammar_test.go b/x/mlxrunner/grammar_test.go
index c1e83aefc..ebaf62c7a 100644
--- a/x/mlxrunner/grammar_test.go
+++ b/x/mlxrunner/grammar_test.go
@@ -1,15 +1,22 @@
package mlxrunner
import (
+ "context"
"encoding/json"
"errors"
+ "fmt"
+ "io/fs"
"net/http"
+ "path/filepath"
+ "slices"
"strings"
"testing"
"github.com/ollama/ollama/api"
+ "github.com/ollama/ollama/x/internal/mlxtest"
"github.com/ollama/ollama/x/mlxrunner/batch"
"github.com/ollama/ollama/x/mlxrunner/mlx"
+ sampler "github.com/ollama/ollama/x/mlxrunner/sample"
"github.com/ollama/ollama/x/mlxrunner/xgrammar"
)
@@ -212,12 +219,18 @@ func (grammarTestDraftSession) committed(*mlx.Array, *mlx.Array, int, []batch.Me
func (grammarTestDraftSession) settle(*mlx.Array) {}
func (grammarTestDraftSession) close() {}
-func TestGrammarParksSpeculation(t *testing.T) {
+func TestSpeculationGating(t *testing.T) {
s := &speculation{drafter: grammarTestDrafter{}, depth: newDepthController()}
constrained := s.open(Request{Grammar: resolvedGrammarCompilation(&xgrammar.Matcher{})}, nil)
defer constrained.close()
- if constrained.enabled {
- t.Fatal("structured output request enabled speculative decoding")
+ if !constrained.enabled {
+ t.Fatal("structured output request disabled speculative decoding")
+ }
+
+ logprobs := s.open(Request{SamplerOpts: sampler.Options{Logprobs: true}}, nil)
+ defer logprobs.close()
+ if logprobs.enabled {
+ t.Fatal("logprobs request enabled speculative decoding")
}
unconstrained := s.open(Request{}, nil)
@@ -226,3 +239,178 @@ func TestGrammarParksSpeculation(t *testing.T) {
t.Fatal("ordinary request unexpectedly disabled speculative decoding")
}
}
+
+// testDigitGrammar builds a grammar over the decode fakes' digit
+// vocabulary, with token 7 as the stop id.
+func testDigitGrammar(t *mlxtest.T, schema string) (*grammarEngine, *grammar) {
+ t.Helper()
+ path, err := mlx.LoadedLibraryPath()
+ if err != nil {
+ t.Skipf("native MLX payload is not built: %v", err)
+ }
+ pieces := make([]string, mtpTestVocab)
+ for i := range pieces {
+ pieces[i] = fmt.Sprintf("%d", i)
+ }
+ compiler, err := xgrammar.New(filepath.Dir(path), pieces, mtpTestVocab, []int32{7}, 8, 128<<20)
+ if err != nil {
+ if errors.Is(err, fs.ErrNotExist) {
+ t.Skipf("native xgrammar payload is not built: %v", err)
+ }
+ t.Fatal(err)
+ }
+ t.Cleanup(compiler.Close)
+ m, err := compiler.Compile(xgrammar.JSONSchema, schema)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(m.Close)
+ e := &grammarEngine{}
+ e.initMask(mtpTestVocab)
+ t.Cleanup(e.close)
+ return e, &grammar{m: m}
+}
+
+func TestDecodeGrammarTransitions(t *testing.T) {
+ mlxtest.Run(t, func(t *mlxtest.T) {
+ // Drive every mode change (park, resume, a round with a rejection, park
+ // again, EOS) while a shadow matcher replays the emitted tokens:
+ // identical masks prove the matcher tracks exactly the emitted stream.
+ const eos int32 = 7
+ target := map[int32]int32{1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: eos, eos: 0}
+ draftPredict := map[int32]int32{2: 3, 3: 4, 4: 5, 5: 0, 6: eos, eos: 0}
+ r := mtpTestRunner(t, target, []int32{eos}, sampler.Options{})
+ engine, g := testDigitGrammar(t, `{"type":"integer"}`)
+ _, shadow := testDigitGrammar(t, `{"type":"integer"}`)
+ r.grammarEngine = engine
+
+ draft := &fakeKVDraft{predict: draftPredict}
+ caches, _ := newMTPTestCaches(2)
+ draft.draftCaches = caches[1:]
+ r.cache.caches = caches
+ r.spec = newSpeculation(r, draft, caches[:1], caches[1:])
+ req := Request{
+ Tokens: []int32{1},
+ CompletionRequest: CompletionRequest{Options: api.Options{NumPredict: 20}},
+ SamplerOpts: sampler.Options{},
+ }
+ spec := r.spec.open(req, nil)
+ if spec == nil || !spec.enabled {
+ t.Fatalf("want a drafting speculationSession, got %+v", spec)
+ }
+ pinDraftLimit(spec, 0)
+ d := spec.decoder(mlx.FromValues([]int32{1}, 1), 0, g).(*speculativeDecoder)
+
+ check := func(want []int32) {
+ t.Helper()
+ results, err := d.next(20)
+ if err != nil {
+ t.Fatalf("next: %v", err)
+ }
+ if got := resultIDs(results); !slices.Equal(got, want) {
+ t.Fatalf("results = %v, want %v", got, want)
+ }
+ for _, id := range want {
+ if err := shadow.m.Accept(id); err != nil {
+ t.Fatalf("shadow accept %d: %v", id, err)
+ }
+ }
+ requireSameMask(t, g, shadow, mtpTestVocab)
+ }
+
+ check([]int32{2}) // parked
+ check([]int32{3}) // parked
+ spec.limit = 2
+ check([]int32{4}) // resume: the drained sample catches the matcher up
+ check([]int32{5, 6}) // round: draft [5 0], rejection at 1, residual 6
+ spec.limit = 0
+ check([]int32{eos}) // parked again off the round's final token
+ if !g.m.Terminated() {
+ t.Fatal("matcher not terminated after the emitted EOS")
+ }
+
+ d.close()
+ spec.close()
+ })
+}
+
+func TestRunMTPDecodeGrammar(t *testing.T) {
+ mlxtest.Run(t, func(t *mlxtest.T) {
+ // The greedy decode chain under an integer grammar: the round's drafted
+ // EOS ends the run through the done path, with every emitted token masked.
+ 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{})
+ engine, g := testDigitGrammar(t, `{"type":"integer"}`)
+ r.grammarEngine = engine
+ draft := &fakeMTPDraft{predict: predict}
+ caches, _ := newMTPTestCaches(1)
+ r.cache.caches = caches
+ r.spec = newSpeculation(r, draft, caches[:1], caches[1:])
+ session, ch := newMTPTestSession(caches)
+
+ req := Request{
+ Responses: ch,
+ Tokens: []int32{0},
+ CompletionRequest: CompletionRequest{Options: api.Options{NumPredict: 20}},
+ SamplerOpts: sampler.Options{},
+ }
+ spec := r.spec.open(req, nil)
+ pinDraftLimit(spec, 4)
+ d := spec.decoder(mlx.FromValues([]int32{1}, 1), 1, g)
+ 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 != "234" {
+ t.Fatalf("content = %q, want %q", content, "234")
+ }
+ if final.DoneReason != 0 {
+ t.Fatalf("DoneReason = %d, want 0 (EOS)", final.DoneReason)
+ }
+ })
+}
+
+func TestRunMTPDecodeGrammarRejectsInvalidDraft(t *testing.T) {
+ mlxtest.Run(t, func(t *mlxtest.T) {
+ // Target and draft predict 3 at every step, but the enum admits only
+ // "12": the masks zero each draft's probability, verification rejects
+ // them, and every emitted token is a residual from a masked distribution.
+ const eos int32 = 7
+ predict := map[int32]int32{1: 3, 3: 4, 2: eos, eos: 0}
+ r := mtpTestRunner(t, predict, []int32{eos}, sampler.Options{})
+ engine, g := testDigitGrammar(t, `{"enum":[12]}`)
+ r.grammarEngine = engine
+ draft := &fakeMTPDraft{predict: predict}
+ caches, _ := newMTPTestCaches(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, nil)
+ pinDraftLimit(spec, 2)
+ d := spec.decoder(mlx.FromValues([]int32{1}, 1), 1, g)
+ 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 != "12" {
+ t.Fatalf("content = %q, want %q", content, "12")
+ }
+ if final.DoneReason != 0 {
+ t.Fatalf("DoneReason = %d, want 0 (EOS)", final.DoneReason)
+ }
+ })
+}
diff --git a/x/mlxrunner/mtp_test.go b/x/mlxrunner/mtp_test.go
index d3b70cd41..881362d8e 100644
--- a/x/mlxrunner/mtp_test.go
+++ b/x/mlxrunner/mtp_test.go
@@ -276,7 +276,7 @@ func TestAcceptMTPDraftsGreedyAcceptAll(t *testing.T) {
current := sampler.Result{Token: mlx.FromValues([]int32{1}, 1)}
unpin := pinAcceptInputs(current, candidates)
defer unpin()
- results, accepted, observed, err := spec.accept(&position, current, candidates)
+ results, accepted, observed, err := spec.accept(&position, current, candidates, nil)
if err != nil {
t.Fatalf("accept: %v", err)
}
@@ -313,7 +313,7 @@ func TestAcceptMTPDraftsGreedyMismatch(t *testing.T) {
current := sampler.Result{Token: mlx.FromValues([]int32{1}, 1)}
unpin := pinAcceptInputs(current, candidates)
defer unpin()
- results, accepted, observed, err := spec.accept(&position, current, candidates)
+ results, accepted, observed, err := spec.accept(&position, current, candidates, nil)
if err != nil {
t.Fatalf("accept: %v", err)
}
@@ -352,7 +352,7 @@ func TestAcceptMTPDraftsGreedyEOS(t *testing.T) {
current := sampler.Result{Token: mlx.FromValues([]int32{1}, 1)}
unpin := pinAcceptInputs(current, candidates)
defer unpin()
- results, accepted, observed, err := spec.accept(&position, current, candidates)
+ results, accepted, observed, err := spec.accept(&position, current, candidates, nil)
if err != nil {
t.Fatalf("accept: %v", err)
}
diff --git a/x/mlxrunner/pipeline.go b/x/mlxrunner/pipeline.go
index bd260cb44..c7be35ee1 100644
--- a/x/mlxrunner/pipeline.go
+++ b/x/mlxrunner/pipeline.go
@@ -244,8 +244,9 @@ type decoder interface {
// drain ends production, returning any results sampled but never
// delivered through next and the position the next forward would have
- // taken; the decoder remains closeable.
- drain() ([]sampler.Result, int)
+ // taken, and surfaces the decoder's deferred fault; the decoder remains
+ // closeable.
+ drain() ([]sampler.Result, int, error)
close()
}
@@ -257,7 +258,7 @@ type decoder interface {
func (r *Runner) decode(ctx context.Context, request Request, session *cacheSession, d decoder, promptEval time.Duration) error {
// A sampled-but-undelivered result is still a produced token; record it.
defer func() {
- results, _ := d.drain()
+ results, _, _ := d.drain()
for _, res := range results {
session.outputs = append(session.outputs, res.Token.Int())
}
@@ -396,7 +397,7 @@ func (r *Runner) pipelinedDecoder(spec *speculationSession, caches []cache.Cache
mlx.Sweep()
mlx.AsyncEval(logits)
var errs []error
- logits, errs = r.grammarEngine.mask(t.grammars, logits)
+ logits, errs = r.grammarEngine.mask(t.grammars, logits, nil)
t.err = t.failRows(errs)
}
t.pending = t.sample(logits)
@@ -431,7 +432,7 @@ func (t *pipelinedDecoder) next(int) ([]sampler.Result, error) {
err := t.failRows(t.r.grammarEngine.accept(t.grammars, out.Token.Ints()))
var errs []error
- logits, errs = t.r.grammarEngine.mask(t.grammars, logits)
+ logits, errs = t.r.grammarEngine.mask(t.grammars, logits, nil)
t.err = errors.Join(err, t.failRows(errs))
}
@@ -442,7 +443,7 @@ func (t *pipelinedDecoder) next(int) ([]sampler.Result, error) {
}
// forward runs the model one step over token, shaped [B, L], and returns the
-// final position's logits, still lazy.
+// final position's [B, 1, V] logits, still lazy.
func (t *pipelinedDecoder) forward(token *mlx.Array) *mlx.Array {
hidden, auxHidden := t.r.Model.Forward(&batch.Batch{
InputIDs: token,
@@ -453,14 +454,14 @@ func (t *pipelinedDecoder) forward(token *mlx.Array) *mlx.Array {
t.spec.committed(token, auxHidden, t.position, nil)
t.position += token.Dim(1)
logits := t.r.Model.Unembed(hidden)
- return logits.Slice(mlx.Slice(), mlx.Slice(logits.Dim(1)-1), mlx.Slice()).Squeeze(1)
+ return logits.Slice(mlx.Slice(), mlx.Slice(logits.Dim(1)-1), mlx.Slice())
}
// sample dispatches the batched sample over the decoder's rows. On an
// unconstrained step it fuses onto the forward's chain, so the whole step
// is in flight before the previous tokens are synchronized.
func (t *pipelinedDecoder) sample(logits *mlx.Array) sampler.Result {
- next := t.r.Sampler.Sample([]int{pipelineSlot}, logits)
+ next := t.r.Sampler.Sample([]int{pipelineSlot}, logits.Squeeze(1))
mlx.Pin(next.Arrays()...)
mlx.Sweep()
mlx.AsyncEval(next.Arrays()...)
@@ -468,10 +469,15 @@ func (t *pipelinedDecoder) sample(logits *mlx.Array) sampler.Result {
}
// drain ends production: it returns the in-flight sample (sampled but never
-// forwarded) and the position its forward would have taken. The decoder
-// keeps the sample for close.
-func (t *pipelinedDecoder) drain() ([]sampler.Result, int) {
- return []sampler.Result{t.pending}, t.position
+// forwarded) and the position its forward would have taken, surfacing the
+// decoder's deferred fault. The decoder keeps the sample for close.
+func (t *pipelinedDecoder) drain() ([]sampler.Result, int, error) {
+ err := t.err
+ if err == nil && t.r.grammarEngine.hasGrammar(t.grammars) {
+ // The sample leaves without its forward, so its accept runs here.
+ err = t.failRows(t.r.grammarEngine.accept(t.grammars, t.pending.Token.Ints()))
+ }
+ return []sampler.Result{t.pending}, t.position, err
}
func (t *pipelinedDecoder) close() {
diff --git a/x/mlxrunner/speculate.go b/x/mlxrunner/speculate.go
index ddaaac8dc..4b461686f 100644
--- a/x/mlxrunner/speculate.go
+++ b/x/mlxrunner/speculate.go
@@ -1,6 +1,7 @@
package mlxrunner
import (
+ "errors"
"fmt"
"time"
@@ -118,7 +119,7 @@ func (s *speculation) open(request Request, layout []any) *speculationSession {
// Logprobs are not yet supported, so a logprobs request keeps a speculationSession
// only to maintain a draft cache in lockstep (permanently parked).
opts := request.SamplerOpts
- enabled := request.Grammar == nil && !opts.Logprobs && opts.TopLogprobs == 0
+ enabled := !opts.Logprobs && opts.TopLogprobs == 0
spec := &speculationSession{spec: s, drafter: d, layout: layout, enabled: enabled, prevDrafts: -1, roundDrafts: -1}
if enabled {
@@ -129,8 +130,8 @@ func (s *speculation) open(request Request, layout []any) *speculationSession {
// beginRound records the previous round's cost sample (its wall time runs to
// this round's start) and starts timing the new one. A session that cannot
-// draft records nothing: its parked rounds carry grammar or logprobs work
-// that would skew the shared depth-0 cost.
+// draft records nothing: its parked rounds carry logprobs work that would
+// skew the shared depth-0 cost.
func (s *speculationSession) beginRound() {
if !s.enabled {
return
@@ -199,14 +200,12 @@ type speculativeDecoder struct {
position int
current sampler.Result // emitted (or the seed), not yet forwarded
inner *pipelinedDecoder // pipelines plain tokens while parked; nil while drafting
- // grammar reaches sampling through the parked inner decoder; a
- // constrained session never drafts.
- grammar *grammar
+ grammar *grammar
}
// decoder returns the decoder for this engine's session. A speculationSession that
-// cannot draft (a grammar, logprobs) has no depth controller and permanently
-// parks, running the inner pipelined decoder whose reports keep the draft KV level.
+// cannot draft (logprobs) has no depth controller and permanently parks,
+// running the inner pipelined decoder whose reports keep the draft KV level.
func (s *speculationSession) decoder(seed *mlx.Array, position int, grammar *grammar) decoder {
current := sampler.Result{Token: seed}
mlx.Pin(current.Arrays()...)
@@ -218,7 +217,11 @@ func (st *speculativeDecoder) next(remaining int) ([]sampler.Result, error) {
// positive length and a primed drafter, else decode parked.
var results []sampler.Result
if s := st.s; st.inner != nil && s.limit > 0 {
- results = st.resume()
+ var err error
+ results, err = st.resume()
+ if err != nil {
+ return nil, err
+ }
} else {
s.beginRound()
var candidates *draftCandidates
@@ -238,7 +241,7 @@ func (st *speculativeDecoder) next(remaining int) ([]sampler.Result, error) {
// draft-count read below; accept pins only its own intermediates.
mlx.Pin(candidates.tokens)
defer mlx.Unpin(candidates.tokens)
- results, accepted, observed, err = st.s.accept(&st.position, st.current, candidates)
+ results, accepted, observed, err = st.s.accept(&st.position, st.current, candidates, st.grammar)
}
if err != nil {
return nil, err
@@ -265,8 +268,11 @@ func (st *speculativeDecoder) advance(next sampler.Result) {
// resume ends a parked stretch: the inner decoder's in-flight sample (sampled
// but never forwarded) is exactly the current token a drafting round expects,
// so emit it and let the next call draft from it.
-func (st *speculativeDecoder) resume() []sampler.Result {
- next, position := st.inner.drain()
+func (st *speculativeDecoder) resume() ([]sampler.Result, error) {
+ next, position, err := st.inner.drain()
+ if err != nil {
+ return nil, err
+ }
st.position = position
st.inner.close()
st.inner = nil
@@ -275,7 +281,7 @@ func (st *speculativeDecoder) resume() []sampler.Result {
st.s.stats.recordRound(0)
st.s.stats.iterations++
st.s.roundDrafts = -1
- return next
+ return next, nil
}
// park decodes one pipelined plain token while the engine cannot draft. Each
@@ -291,11 +297,11 @@ func (st *speculativeDecoder) park(remaining int) ([]sampler.Result, error) {
// drain surrenders the inner decoder's undelivered sample while parked; a
// drafting decoder has already delivered everything it sampled.
-func (st *speculativeDecoder) drain() ([]sampler.Result, int) {
+func (st *speculativeDecoder) drain() ([]sampler.Result, int, error) {
if st.inner != nil {
return st.inner.drain()
}
- return nil, st.position
+ return nil, st.position, nil
}
func (st *speculativeDecoder) close() {
@@ -386,7 +392,7 @@ func commitSpeculation(caches []cache.Cache, accepted, draftCount, before int) {
// The caller keeps current and the candidate tokens pinned across the call,
// since accept sweeps before its eval and reads both afterward; accept pins
// only the intermediates it produces.
-func (s *speculationSession) accept(position *int, current sampler.Result, candidates *draftCandidates) (results []sampler.Result, accepted, observed int, err error) {
+func (s *speculationSession) accept(position *int, current sampler.Result, candidates *draftCandidates, g *grammar) (results []sampler.Result, accepted, observed int, err error) {
r := s.spec.r
before := *position
draftCount := candidates.tokens.Dim(1)
@@ -406,6 +412,12 @@ func (s *speculationSession) accept(position *int, current sampler.Result, candi
}
defer commit(0)
+ dist := candidates.dist.Arrays()
+ mlx.Pin(dist...)
+ mlx.Sweep()
+ mlx.AsyncEval(candidates.tokens)
+ mlx.Unpin(dist...)
+
hiddenSeq, auxHiddenSeq := r.Model.Forward(&batch.Batch{
InputIDs: current.Token.ExpandDims(-1).Concatenate(1, candidates.tokens),
SeqOffsets: []int32{int32(before)},
@@ -417,7 +429,19 @@ func (s *speculationSession) accept(position *int, current sampler.Result, candi
// 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)
+ logits := r.Model.Unembed(hiddenSeq)
+
+ draftIDs := candidates.tokens.Ints()
+ constrained := g.constraining()
+ if constrained {
+ var errs []error
+ logits, errs = r.grammarEngine.mask([]*grammar{g}, logits, [][]int32{draftIDs})
+ if err := errors.Join(errs...); err != nil {
+ return nil, 0, 0, err
+ }
+ }
+
+ targetDist := r.Sampler.Distribution(pipelineSlot, logits, candidates.tokens)
draftDist := candidates.dist
acceptedMask := r.sampleAcceptedMask(targetDist.SliceRows(0, draftCount), draftDist, candidates.tokens)
@@ -429,17 +453,14 @@ func (s *speculationSession) accept(position *int, current sampler.Result, candi
residualTokens := r.Sampler.SampleDistribution(pipelineSlot, targetDist.SliceRows(0, draftCount).ResidualAgainst(draftDist))
bonusToken := r.sampleTokenAt(targetDist, draftCount)
- // Pin the arrays read after the eval, then sweep so the draft proposal
- // chain and this validation forward's intermediates are freed as the eval
- // consumes them, the way the plain decode dispatch sweeps before its eval.
- // current and the candidate tokens stay pinned by the caller across the call.
+ // Pin the arrays read after the eval; current and the candidate tokens
+ // stay pinned by the caller across the call.
live := []*mlx.Array{hiddenSeq, auxHiddenSeq, acceptedMask, residualTokens, bonusToken}
mlx.Pin(live...)
defer mlx.Unpin(live...)
mlx.Sweep()
mlx.Eval(candidates.tokens, acceptedMask, residualTokens, bonusToken)
- draftIDs := candidates.tokens.Ints()
acceptedFlags := acceptedMask.Ints()
for _, ok := range acceptedFlags {
if ok == 0 {
@@ -473,6 +494,26 @@ func (s *speculationSession) accept(position *int, current sampler.Result, candi
}
}
+ var nextID int32
+ if !done {
+ if accepted < draftCount {
+ nextID = residualTokens.Ints()[accepted]
+ } else {
+ nextID = bonusToken.Int()
+ }
+ commitIDs = append(commitIDs, nextID)
+ }
+ if constrained {
+ // The grammar accepts the run the way it accepts every emitted token,
+ // before the caches commit it: on a rejection the deferred rollback
+ // keeps them level with the tokens decode has recorded.
+ for _, id := range commitIDs {
+ if err := errors.Join(r.grammarEngine.accept([]*grammar{g}, []int32{id})...); err != nil {
+ return nil, 0, 0, err
+ }
+ }
+ }
+
commit(keep)
*position = before + 1 + keep
@@ -486,21 +527,10 @@ func (s *speculationSession) accept(position *int, current sampler.Result, candi
before, nil)
results = draftResults(draftIDs[:accepted])
- if done {
- r.Sampler.Commit(pipelineSlot, commitIDs)
- return results, accepted, observed, nil
- }
-
- var nextID int32
- if accepted < draftCount {
- nextID = residualTokens.Ints()[accepted]
- } else {
- nextID = bonusToken.Int()
+ if !done {
+ results = append(results, sampler.Result{Token: mlx.FromValues([]int32{nextID}, 1)})
}
- commitIDs = append(commitIDs, nextID)
r.Sampler.Commit(pipelineSlot, commitIDs)
-
- results = append(results, sampler.Result{Token: mlx.FromValues([]int32{nextID}, 1)})
return results, accepted, observed, nil
}
diff --git a/x/mlxrunner/xgrammar/dynamic.c b/x/mlxrunner/xgrammar/dynamic.c
index bea1e766a..86d98bb1f 100644
--- a/x/mlxrunner/xgrammar/dynamic.c
+++ b/x/mlxrunner/xgrammar/dynamic.c
@@ -53,6 +53,8 @@ static int (*matcher_new_fn)(ollama_xgrammar_compiler*, ollama_xgrammar_kind, co
static void (*matcher_free_fn)(ollama_xgrammar_matcher*);
static int (*matcher_fill_fn)(ollama_xgrammar_matcher*, int32_t*, size_t, int*);
static int (*matcher_accept_fn)(ollama_xgrammar_matcher*, int32_t, int*);
+static int (*matcher_rollback_fn)(ollama_xgrammar_matcher*, int32_t);
+static int (*matcher_is_terminated_fn)(ollama_xgrammar_matcher*, int*);
static const char* load_error;
static void clear_symbols(void) {
@@ -64,6 +66,8 @@ static void clear_symbols(void) {
matcher_free_fn = NULL;
matcher_fill_fn = NULL;
matcher_accept_fn = NULL;
+ matcher_rollback_fn = NULL;
+ matcher_is_terminated_fn = NULL;
}
#define LOAD(handle, field, name) do { \
@@ -90,6 +94,8 @@ int ollama_xgrammar_dynamic_load(ollama_xgrammar_dynamic_handle* handle, const c
LOAD(handle, matcher_free_fn, "ollama_xgrammar_matcher_free");
LOAD(handle, matcher_fill_fn, "ollama_xgrammar_matcher_fill");
LOAD(handle, matcher_accept_fn, "ollama_xgrammar_matcher_accept");
+ LOAD(handle, matcher_rollback_fn, "ollama_xgrammar_matcher_rollback");
+ LOAD(handle, matcher_is_terminated_fn, "ollama_xgrammar_matcher_is_terminated");
load_error = NULL;
return 0;
@@ -144,3 +150,9 @@ int ollama_xgrammar_dynamic_matcher_fill(ollama_xgrammar_matcher* m, int32_t* b,
int ollama_xgrammar_dynamic_matcher_accept(ollama_xgrammar_matcher* m, int32_t t, int* a, char** error) {
return capture_error(matcher_accept_fn(m, t, a), error);
}
+int ollama_xgrammar_dynamic_matcher_rollback(ollama_xgrammar_matcher* m, int32_t n, char** error) {
+ return capture_error(matcher_rollback_fn(m, n), error);
+}
+int ollama_xgrammar_dynamic_matcher_is_terminated(ollama_xgrammar_matcher* m, int* t, char** error) {
+ return capture_error(matcher_is_terminated_fn(m, t), error);
+}
diff --git a/x/mlxrunner/xgrammar/dynamic.h b/x/mlxrunner/xgrammar/dynamic.h
index 43ca68084..c4783f0ce 100644
--- a/x/mlxrunner/xgrammar/dynamic.h
+++ b/x/mlxrunner/xgrammar/dynamic.h
@@ -21,5 +21,7 @@ int ollama_xgrammar_dynamic_matcher_new(
void ollama_xgrammar_dynamic_matcher_free(ollama_xgrammar_matcher*);
int ollama_xgrammar_dynamic_matcher_fill(ollama_xgrammar_matcher*, int32_t*, size_t, int*, char**);
int ollama_xgrammar_dynamic_matcher_accept(ollama_xgrammar_matcher*, int32_t, int*, char**);
+int ollama_xgrammar_dynamic_matcher_rollback(ollama_xgrammar_matcher*, int32_t, char**);
+int ollama_xgrammar_dynamic_matcher_is_terminated(ollama_xgrammar_matcher*, int*, char**);
#endif
diff --git a/x/mlxrunner/xgrammar/native/xgrammar.cpp b/x/mlxrunner/xgrammar/native/xgrammar.cpp
index 217fda683..3edecc414 100644
--- a/x/mlxrunner/xgrammar/native/xgrammar.cpp
+++ b/x/mlxrunner/xgrammar/native/xgrammar.cpp
@@ -217,6 +217,31 @@ int ollama_xgrammar_matcher_accept(
});
}
+int ollama_xgrammar_matcher_rollback(
+ ollama_xgrammar_matcher* matcher,
+ int32_t num_tokens) {
+ return protect([&] {
+ if (matcher == nullptr) {
+ throw std::invalid_argument("matcher is null");
+ }
+ if (num_tokens < 0) {
+ throw std::invalid_argument("negative rollback count");
+ }
+ matcher->matcher.Rollback(num_tokens);
+ });
+}
+
+int ollama_xgrammar_matcher_is_terminated(
+ ollama_xgrammar_matcher* matcher,
+ int* terminated) {
+ return protect([&] {
+ if (matcher == nullptr || terminated == nullptr) {
+ throw std::invalid_argument("matcher or result is null");
+ }
+ *terminated = matcher->matcher.IsTerminated() ? 1 : 0;
+ });
+}
+
void ollama_xgrammar_matcher_free(ollama_xgrammar_matcher* matcher) {
delete matcher;
}
diff --git a/x/mlxrunner/xgrammar/native/xgrammar.h b/x/mlxrunner/xgrammar/native/xgrammar.h
index e6c6f1631..6b1a5019c 100644
--- a/x/mlxrunner/xgrammar/native/xgrammar.h
+++ b/x/mlxrunner/xgrammar/native/xgrammar.h
@@ -60,6 +60,12 @@ OLLAMA_XGRAMMAR_API int ollama_xgrammar_matcher_accept(
ollama_xgrammar_matcher* matcher,
int32_t token_id,
int* accepted);
+OLLAMA_XGRAMMAR_API int ollama_xgrammar_matcher_rollback(
+ ollama_xgrammar_matcher* matcher,
+ int32_t num_tokens);
+OLLAMA_XGRAMMAR_API int ollama_xgrammar_matcher_is_terminated(
+ ollama_xgrammar_matcher* matcher,
+ int* terminated);
#ifdef __cplusplus
}
diff --git a/x/mlxrunner/xgrammar/xgrammar.go b/x/mlxrunner/xgrammar/xgrammar.go
index 921224e04..35e52902b 100644
--- a/x/mlxrunner/xgrammar/xgrammar.go
+++ b/x/mlxrunner/xgrammar/xgrammar.go
@@ -11,7 +11,6 @@ import (
"os"
"path/filepath"
"runtime"
- "slices"
"sync"
"unsafe"
)
@@ -77,7 +76,6 @@ type Compiler struct {
ctx *C.ollama_xgrammar_compiler
path string
vocabSize int
- stops []int32
}
// New loads the native library from dir — once per process, never unloaded —
@@ -127,7 +125,7 @@ func New(dir string, pieces []string, vocabSize int, stopIDs []int32, threads in
) != 0 {
return nil, nativeError("create grammar compiler", cError)
}
- return &Compiler{ctx: ctx, path: path, vocabSize: vocabSize, stops: slices.Clone(stopIDs)}, nil
+ return &Compiler{ctx: ctx, path: path, vocabSize: vocabSize}, nil
}
// Path returns the loaded native library's location.
@@ -159,7 +157,7 @@ func (c *Compiler) Compile(kind Kind, source string) (*Matcher, error) {
) != 0 {
return nil, nativeError("compile grammar", cError)
}
- return &Matcher{ctx: ctx, vocabSize: c.vocabSize, stops: c.stops}, nil
+ return &Matcher{ctx: ctx, vocabSize: c.vocabSize}, nil
}
func (c *Compiler) Close() {
@@ -175,19 +173,23 @@ func (c *Compiler) Close() {
type Matcher struct {
ctx *C.ollama_xgrammar_matcher
vocabSize int
- stops []int32
- // terminated: a stop token was accepted, ending the grammar; the matcher
- // no longer constrains sampling.
- terminated bool
}
// Terminated reports whether an accepted stop token ended the grammar; a
-// terminated matcher no longer constrains sampling.
+// terminated matcher no longer constrains sampling. Rollback across the
+// stop token resumes constraining.
func (m *Matcher) Terminated() bool {
- if m == nil {
+ if m == nil || m.ctx == nil {
return true
}
- return m.terminated
+ var terminated C.int
+ var cError *C.char
+ if C.ollama_xgrammar_dynamic_matcher_is_terminated(m.ctx, &terminated, &cError) != 0 {
+ // Still constraining: the fault surfaces at the next fill or accept.
+ C.free(unsafe.Pointer(cError))
+ return false
+ }
+ return terminated != 0
}
// Fill writes the packed allowed-token bitmask for the next position into
@@ -206,7 +208,8 @@ func (m *Matcher) Fill(row []int32) (bool, error) {
if want := (m.vocabSize + 31) / 32; len(row) != want {
return false, fmt.Errorf("mask row holds %d words; the vocabulary needs %d", len(row), want)
}
- if m.terminated {
+ // The native fill rejects a terminated matcher outright.
+ if m.Terminated() {
return false, nil
}
@@ -233,8 +236,20 @@ func (m *Matcher) Accept(tokenID int32) error {
if accepted == 0 {
return fmt.Errorf("grammar rejected sampled token %d", tokenID)
}
- if slices.Contains(m.stops, tokenID) {
- m.terminated = true
+ return nil
+}
+
+// Rollback rewinds the matcher's last n accepted tokens.
+func (m *Matcher) Rollback(n int) error {
+ if m == nil || m.ctx == nil {
+ return errors.New("grammar matcher is closed")
+ }
+ if n == 0 {
+ return nil
+ }
+ var cError *C.char
+ if C.ollama_xgrammar_dynamic_matcher_rollback(m.ctx, C.int32_t(n), &cError) != 0 {
+ return nativeError("rollback", cError)
}
return nil
}
diff --git a/x/mlxrunner/xgrammar/xgrammar_test.go b/x/mlxrunner/xgrammar/xgrammar_test.go
index e5d276c8d..8dce2967c 100644
--- a/x/mlxrunner/xgrammar/xgrammar_test.go
+++ b/x/mlxrunner/xgrammar/xgrammar_test.go
@@ -168,6 +168,55 @@ func TestFillAfterTermination(t *testing.T) {
}
}
+// Rollback restores earlier matcher state exactly: the refilled mask equals
+// the one filled before the rolled-back accepts, and the replay proceeds.
+func TestRollbackRestoresState(t *testing.T) {
+ compiler := testGrammarCompiler(t)
+ schema := `{"type":"object","properties":{"answer":{"type":"string","enum":["ok"]}},"required":["answer"],"additionalProperties":false}`
+ matcher, err := compiler.Compile(xgrammar.JSONSchema, schema)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer matcher.Close()
+
+ acceptPieces(t, matcher, "{", `"`)
+ before, _ := fillMask(t, matcher)
+ acceptPieces(t, matcher, "answer", `"`, ":")
+ if err := matcher.Rollback(3); err != nil {
+ t.Fatal(err)
+ }
+ after, constrained := fillMask(t, matcher)
+ if !constrained || !slices.Equal(before, after) {
+ t.Fatal("mask after rollback does not match the pre-accept mask")
+ }
+ acceptPieces(t, matcher, "answer", `"`, ":", `"`, "ok", `"`, "}")
+
+ // Rollback across the stop token resumes constraining.
+ acceptPieces(t, matcher, "<eos>")
+ if !matcher.Terminated() {
+ t.Fatal("matcher not terminated after the stop token")
+ }
+ if err := matcher.Rollback(1); err != nil {
+ t.Fatal(err)
+ }
+ if matcher.Terminated() {
+ t.Fatal("matcher still terminated after rolling back the stop token")
+ }
+ acceptPieces(t, matcher, "<eos>")
+
+ if err := matcher.Rollback(0); err != nil {
+ t.Fatal(err)
+ }
+ if err := matcher.Rollback(1000); err == nil {
+ t.Fatal("rollback past history unexpectedly succeeded")
+ }
+
+ matcher.Close()
+ if err := matcher.Rollback(1); err == nil {
+ t.Fatal("rollback on closed matcher unexpectedly succeeded")
+ }
+}
+
func TestInvalidGrammarReturnsError(t *testing.T) {
compiler := testGrammarCompiler(t)
for _, tt := range []struct {