grammar

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 14 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package cudagrammar constrains language model generation to JSON that conforms to a schema.

Compile turns a schema into a Grammar; Grammar.Match starts a Matcher, a pushdown automaton over the generated bytes. Given a view of a tokenizer's vocabulary, a matcher reports which token ids can continue the document (Matcher.TokenMask) or masks the logits of those that cannot (Matcher.ApplyMask).

The supported schema subset is objects with fixed required properties, arrays, strings, numbers, integers, booleans, nulls, and enumerations of strings, nested to any depth. Any other schema keyword is an error from Compile rather than a constraint silently dropped.

Masks are computed on the CPU. The name records where they are applied, in a sampler running on the device, not where they are built.

g, err := cudagrammar.CompileString(`{"type":"object","properties":{"n":{"type":"integer"}}}`)
if err != nil {
	return err
}
m := g.Match()
for !m.Done() {
	m.ApplyMask(vocab, logits)
	m.Accept(vocab(sample(logits)))
}

For multi-token speculative decoding, Matcher.Save, Matcher.Restore, and Matcher.Rollback rewind accepted transitions in O(1), while Matcher.SpeculativeMasks and Matcher.CommitPrefix build per-step Bitmask slices over a Vocabulary and roll back draft transitions before verification commits the accepted prefix.

For general context-free grammars and full Pydantic v2 JSON Schemas (with recursive $defs/$ref, anyOf/oneOf unions, optional object properties, additionalProperties, const, and mixed-type enum), CompileCFG and CompilePydanticSchema compile into an immutable CFG. CFG.Match returns a CFGMatcher, an incremental byte-level Earley parser supporting arbitrary recursion and atomic rollback. BuildTokenTrie indexes a vocabulary into a compact byte-prefix TokenTrie (including split multi-byte UTF-8 BPE tokens) for fast pruned CFGMatcher.FillBitmask computation with EOS admission and optional MaskCache state caching, and DecodeLoop drives end-to-end grammar-constrained sampling over a LogitSource.

This package is outside the compatibility promise of github.com/tmc/lib/nvidia. Its API may change or be removed in patch releases.

Index

Examples

Constants

View Source
const MaskedLogit = float32(-1e9)

MaskedLogit is the value assigned to a token the grammar forbids. It is a large finite penalty rather than negative infinity, so that a state which happens to forbid every token yields a uniform distribution instead of NaN.

Variables

This section is empty.

Functions

This section is empty.

Types

type Bitmask

type Bitmask struct {
	VocabSize int
	Words     []uint32
}

Bitmask holds a packed 32-bit word token bitmask ([ceil(VocabSize/32)]uint32) representing the set of vocabulary tokens admitted at a grammar step.

func NewBitmask

func NewBitmask(vocabSize int) *Bitmask

NewBitmask allocates an all-zero Bitmask for vocabSize tokens.

func (*Bitmask) ApplyInPlace

func (b *Bitmask) ApplyInPlace(logits []float32)

ApplyInPlace sets logits[i] to MaskedLogit for every token i not allowed by b.

func (*Bitmask) CountAllowed

func (b *Bitmask) CountAllowed() int

CountAllowed returns the number of allowed tokens in b.

func (*Bitmask) IsAllowed

func (b *Bitmask) IsAllowed(tokenID int) bool

IsAllowed reports whether tokenID is marked as valid in b.

func (*Bitmask) Set

func (b *Bitmask) Set(tokenID int, allowed bool)

Set marks tokenID as allowed (or disallowed when allowed is false).

type BitmaskTable

type BitmaskTable struct {
	NumStates int
	VocabSize int
	Words     int // (VocabSize + 63) / 64
	Table     [][]uint64
}

BitmaskTable stores pre-computed 64-bit boolean bitmasks for vocab token validity per FSM state.

func NewBitmaskTable

func NewBitmaskTable(numStates, vocabSize int) *BitmaskTable

NewBitmaskTable initializes a bitmask lookup table for a given vocabulary size and state count.

func (*BitmaskTable) ApplyMask

func (b *BitmaskTable) ApplyMask(state int, logits []float32)

ApplyMask sets the logit of every token the grammar forbids in state to MaskedLogit. Tokens at or beyond VocabSize are forbidden: the table has no bit for them, so they were never permitted.

func (*BitmaskTable) IsValid

func (b *BitmaskTable) IsValid(state, tokenID int) bool

IsValid checks if tokenID is permissible in state.

func (*BitmaskTable) SetValid

func (b *BitmaskTable) SetValid(state, tokenID int)

SetValid marks tokenID as permissible in state.

type CFG

type CFG struct {
	// contains filtered or unexported fields
}

CFG is a compiled, immutable byte-level context-free grammar.

A CFG is safe for concurrent use and can start any number of independent CFGMatcher instances via CFG.Match.

func CompileCFG

func CompileCFG(gbnf string) (*CFG, error)

CompileCFG parses a GBNF/EBNF context-free grammar into an immutable CFG.

Supported syntax:

  • Rules: `name ::= alt1 | alt2` (rules may span multiple lines)
  • Quoted string literals `"..."` with escapes (`\"`, `\\`, `\n`, `\r`, `\t`, `\b`, `\f`, `\/`, `\xNN`, `\uNNNN`, `\UNNNNNNNN`); `""` denotes epsilon
  • Positive and negated character classes `[a-z0-9_]`, `[^"\\]`
  • Grouping `(...)` and quantifiers `?`, `*`, `+`
  • Line comments `# ...`

If a rule named "root" is defined it is used as the start rule; otherwise the first defined rule is the start rule. Undefined non-terminals, empty rules, malformed syntax, unproductive rules, and unguarded empty cycles are rejected with an error.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/host/grammar"
)

func main() {
	cfg, err := grammar.CompileCFG(`
expr ::= term (("+" | "-") term)*
term ::= [0-9]+ | "(" expr ")"
`)
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	m := cfg.Match()
	if err := m.AcceptString("(1+2)-3"); err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Printf("start=%s pos=%d canFinish=%v\n", cfg.StartRule(), m.Pos(), m.CanFinish())
}
Output:
start=expr pos=7 canFinish=true

func CompilePydanticSchema

func CompilePydanticSchema(schemaJSON []byte) (*CFG, error)

CompilePydanticSchema compiles a Pydantic v2 (JSON Schema Draft 2020-12) schema into an immutable byte-level CFG.

Supported schema features:

  • $defs and definitions with local $ref (including self-recursive and mutually recursive definitions, and root self-reference "#")
  • anyOf and oneOf unions (including Pydantic Optional[T] and discriminated unions with discriminator)
  • single type string or multi-type array (e.g. ["string", "null"])
  • const (any JSON value) and mixed-type enum
  • object with required and optional properties, empty objects, escaped property names, and additionalProperties (false, true, or sub-schema)
  • array with items and optional bounded minItems/maxItems (up to 32)
  • string (RFC 8259 escapes and valid multi-byte UTF-8), integer, number, boolean, null, and unconstrained empty schema {}
  • Pydantic metadata annotations ($schema, $id, title, description, default, examples, $comment, readOnly, writeOnly, deprecated)

Unsupported constraint keywords (such as not, allOf, patternProperties, pattern, format, minLength, minimum) and unresolved $ref targets fail closed with a descriptive error.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/host/grammar"
)

func main() {
	const schema = `{
		"$defs": {
			"Node": {
				"type": "object",
				"properties": {
					"val": {"type": "integer"},
					"next": {"anyOf": [{"$ref": "#/$defs/Node"}, {"type": "null"}], "default": null}
				},
				"required": ["val"]
			}
		},
		"$ref": "#/$defs/Node"
	}`
	cfg, err := grammar.CompilePydanticSchemaString(schema)
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	m := cfg.Match()
	if err := m.AcceptString(`{"val":1,"next":{"val":2,"next":null}}`); err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Printf("canFinish=%v pos=%d\n", m.CanFinish(), m.Pos())
}
Output:
canFinish=true pos=38

func CompilePydanticSchemaString

func CompilePydanticSchemaString(s string) (*CFG, error)

CompilePydanticSchemaString is CompilePydanticSchema for a string schema.

func (*CFG) Match

func (g *CFG) Match() *CFGMatcher

Match starts a new incremental CFGMatcher at offset 0.

func (*CFG) NumProductions

func (g *CFG) NumProductions() int

NumProductions returns the total number of productions in g, excluding the internal augmented start production.

func (*CFG) NumRules

func (g *CFG) NumRules() int

NumRules returns the number of user-defined and synthesized rules in g, excluding the internal augmented start rule.

func (*CFG) RuleNames

func (g *CFG) RuleNames() []string

RuleNames returns the names of user-defined rules in g (excluding internal synthetic rules starting with "$").

func (*CFG) StartRule

func (g *CFG) StartRule() string

StartRule returns the name of the grammar's start rule.

type CFGMatcher

type CFGMatcher struct {
	// contains filtered or unexported fields
}

CFGMatcher is an incremental byte-level Earley parser enforcing a CFG.

It supports arbitrary context-free recursion, atomic multi-byte acceptance, O(1) rollback via CFGMatcher.Rollback, snapshotting via CFGMatcher.Save and CFGMatcher.Restore, and fast trie-pruned token bitmask generation via CFGMatcher.FillBitmask.

A CFGMatcher is not safe for concurrent mutation; use CFGMatcher.Clone to explore independent branches.

func (*CFGMatcher) Accept

func (m *CFGMatcher) Accept(p []byte) error

Accept atomically advances m over all bytes in p as a single history step. If any byte fails to match, m is rolled back completely and left unchanged.

func (*CFGMatcher) AcceptByte

func (m *CFGMatcher) AcceptByte(b byte) error

AcceptByte advances m by one byte. On error m is left unchanged.

func (*CFGMatcher) AcceptString

func (m *CFGMatcher) AcceptString(s string) error

AcceptString is CFGMatcher.Accept for a string.

func (*CFGMatcher) AcceptToken

func (m *CFGMatcher) AcceptToken(v Vocab, id int) error

AcceptToken validates and atomically advances m by the decoded bytes of token id from v as a single history step. If v is nil, token id decodes to empty bytes, or any byte is rejected by the grammar, m is left unchanged.

func (*CFGMatcher) Admits

func (m *CFGMatcher) Admits(v Vocab, id int) bool

Admits reports whether every byte of token id in v can be accepted from m's current state without advancing m. Empty/control tokens return false.

func (*CFGMatcher) Bitmask

func (m *CFGMatcher) Bitmask(trie *TokenTrie) (*Bitmask, error)

Bitmask computes and returns a packed Bitmask of tokens admitted from m's current state over trie.

func (*CFGMatcher) BitmaskCached

func (m *CFGMatcher) BitmaskCached(trie *TokenTrie, cache *MaskCache) (*Bitmask, bool, error)

BitmaskCached computes a Bitmask using cache when non-nil.

func (*CFGMatcher) CFG

func (m *CFGMatcher) CFG() *CFG

CFG returns the compiled grammar enforced by m.

func (*CFGMatcher) CanFinish

func (m *CFGMatcher) CanFinish() bool

CanFinish reports whether the start rule has a complete parse at the current position, even if additional bytes (such as trailing whitespace or more array items) could still be accepted.

func (*CFGMatcher) Clone

func (m *CFGMatcher) Clone() *CFGMatcher

Clone returns an independent copy of m. Because committed Earley chart columns are immutable, Clone only copies the column pointer slice.

func (*CFGMatcher) Done

func (m *CFGMatcher) Done() bool

Done reports whether matching is complete: either CFGMatcher.Finish has been called, or CFGMatcher.CanFinish is true and no further byte can be accepted.

func (*CFGMatcher) FillBitmask

func (m *CFGMatcher) FillBitmask(trie *TokenTrie, dst []uint32) (int, error)

FillBitmask fills dst[:trie.Words()] with a packed 32-bit bitmask of every vocabulary token admitted by m at its current state, returning the number of allowed tokens.

FillBitmask walks trie with incremental Earley column push/pop so rejected byte prefixes prune entire subtrees in O(1) without mutating m. When trie.EOSTokenID() >= 0, the EOS token bit is explicitly set when m.CanFinish() is true (and m has not already called Finish) and cleared whenever !m.CanFinish().

func (*CFGMatcher) FillBitmaskCached

func (m *CFGMatcher) FillBitmaskCached(trie *TokenTrie, cache *MaskCache, dst []uint32) (allowed int, hit bool, err error)

FillBitmaskCached fills dst[:trie.Words()] using cache when non-nil, falling back to CFGMatcher.FillBitmask on a miss and storing the result.

func (*CFGMatcher) Finish

func (m *CFGMatcher) Finish() error

Finish marks matching as cleanly finished if CFGMatcher.CanFinish is true, or returns an error if the current input is incomplete.

func (*CFGMatcher) Pos

func (m *CFGMatcher) Pos() int

Pos returns the number of bytes accepted so far.

func (*CFGMatcher) Restore

func (m *CFGMatcher) Restore(cp Checkpoint) error

Restore resets m to the state and transition history captured in cp.

func (*CFGMatcher) Rollback

func (m *CFGMatcher) Rollback(steps int) error

Rollback rewinds steps accepted transitions along m's transition history in O(1).

func (*CFGMatcher) Save

func (m *CFGMatcher) Save() Checkpoint

Save captures the current parser state and transition history of m into a Checkpoint that can later be passed to CFGMatcher.Restore.

type Checkpoint

type Checkpoint struct {
	// contains filtered or unexported fields
}

Checkpoint captures the complete state and transition history of a Matcher or CFGMatcher so it can be restored in O(1) without re-running from the root of the document.

type DecodeConfig

type DecodeConfig struct {
	Grammar *CFG
	Trie    *TokenTrie
	Options DecodeOptions
}

DecodeConfig bundles a compiled CFG, TokenTrie, and DecodeOptions for repeated calls to DecodeConfig.Decode.

func (DecodeConfig) Decode

func (c DecodeConfig) Decode(ctx context.Context, src LogitSource) (DecodeResult, error)

Decode runs DecodeLoop with c's grammar, trie, and options.

type DecodeOptions

type DecodeOptions struct {
	// MaxTokens bounds the number of sampling steps (including EOS).
	// If <= 0, defaults to 1024.
	MaxTokens int

	// Temperature scales logits before sampling. Values <= 0 select
	// deterministic greedy (argmax) decoding.
	Temperature float32

	// TopK restricts stochastic sampling to the highest-logit K admissible
	// tokens. Ignored when <= 0 or during greedy decoding.
	TopK int

	// TopP restricts stochastic sampling to the smallest prefix of admissible
	// tokens whose cumulative probability is at least TopP. Ignored when <= 0,
	// >= 1, or during greedy decoding.
	TopP float32

	// Seed initializes the PRNG used when Temperature > 0.
	Seed int64

	// Cache optionally caches bitmasks across equivalent parser states.
	Cache *MaskCache
}

DecodeOptions configures constrained decoding in DecodeLoop.

type DecodeResult

type DecodeResult struct {
	Tokens     []int
	Bytes      []byte
	Text       string
	Steps      int
	StoppedEOS bool
	MaskStats  MaskStats
}

DecodeResult holds the generated tokens, decoded bytes/UTF-8 text, and bitmask statistics from DecodeLoop.

func DecodeLoop

func DecodeLoop(ctx context.Context, cfg *CFG, trie *TokenTrie, src LogitSource, opts DecodeOptions) (DecodeResult, error)

DecodeLoop runs grammar-constrained token generation over src until trie.EOSTokenID() is sampled in a completable grammar state (CanFinish()) or an error/limit occurs.

At every step DecodeLoop:

  1. Queries src.NextLogits(ctx, generatedTokens).
  2. Computes the token bitmask via CFGMatcher.FillBitmask (or CFGMatcher.FillBitmaskCached when opts.Cache != nil), which admits EOSTokenID if and only if CanFinish() is true.
  3. Masks disallowed logits to -Inf on a private copy of the logits slice.
  4. Samples the next token via greedy argmax (Temperature <= 0) or seeded temperature / top-k / top-p sampling (Temperature > 0).
  5. Stops cleanly when EOSTokenID is sampled (verifying CanFinish()), or atomically advances the matcher via CFGMatcher.AcceptToken.
Example
package main

import (
	"context"
	"fmt"

	"github.com/tmc/lib/nvidia/x/host/grammar"
)

func main() {
	cfg, err := grammar.CompilePydanticSchemaString(`{
		"type": "object",
		"properties": {"ok": {"type": "boolean"}},
		"required": ["ok"]
	}`)
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	vocab := grammar.NewVocabulary([]string{
		0: "", // EOS
		1: `{`,
		2: `"ok"`,
		3: `:`,
		4: `true`,
		5: `}`,
		6: `INVALID`,
	})
	trie, err := grammar.BuildVocabularyTrie(vocab, 0)
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	// Adversarial logits always prefer "INVALID" (token 6), but grammar masking
	// forces a valid JSON object and admits EOS only when the object completes.
	src := grammar.LogitSourceFunc(func(ctx context.Context, tokens []int) ([]float32, error) {
		return []float32{5, 1, 1, 1, 2, 1, 100}, nil
	})
	res, err := grammar.DecodeLoop(context.Background(), cfg, trie, src, grammar.DecodeOptions{
		MaxTokens:   16,
		Temperature: 0,
	})
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Printf("text=%s stoppedEOS=%v steps=%d\n", res.Text, res.StoppedEOS, res.Steps)
}
Output:
text={"ok":true} stoppedEOS=true steps=6

type Grammar

type Grammar struct {
	// contains filtered or unexported fields
}

Grammar is a compiled JSON schema. It is immutable once compiled and can be used to start any number of independent Matcher values.

func Compile

func Compile(schema []byte) (*Grammar, error)

Compile builds a grammar from a JSON schema.

The supported subset is: objects with a fixed set of required properties, arrays, strings, numbers, integers, booleans, nulls, and enumerations of strings. Nesting is unrestricted. Every other schema keyword is rejected rather than ignored, so a schema that would not in fact be enforced never compiles.

Objects are matched with their properties in the order the schema declares them. JSON itself does not order object members, but a decoder that is being constrained emits them one at a time, and fixing the order is what lets the automaton name the next key exactly.

func CompileString

func CompileString(schema string) (*Grammar, error)

CompileString is Compile for a schema held in a string.

func (*Grammar) Match

func (g *Grammar) Match() *Matcher

Match starts a matcher at the beginning of a document.

type LogitSource

type LogitSource interface {
	NextLogits(ctx context.Context, tokens []int) ([]float32, error)
}

LogitSource produces raw next-token logits given the tokens generated so far.

type LogitSourceFunc

type LogitSourceFunc func(ctx context.Context, tokens []int) ([]float32, error)

LogitSourceFunc adapts a function to the LogitSource interface.

func (LogitSourceFunc) NextLogits

func (f LogitSourceFunc) NextLogits(ctx context.Context, tokens []int) ([]float32, error)

NextLogits calls f(ctx, tokens).

type MaskCache

type MaskCache struct {
	// contains filtered or unexported fields
}

MaskCache caches computed token bitmasks keyed by the canonical reachable parser state fingerprint so repeated identical parser states (such as inside JSON strings, numbers, whitespace, or repeated structures) reuse masks in O(VocabSize/32) memory copies.

MaskCache is safe for concurrent use.

func NewMaskCache

func NewMaskCache(maxEntries int) *MaskCache

NewMaskCache allocates a MaskCache holding up to maxEntries cached masks. If maxEntries <= 0, a default capacity of 4096 is used.

func (*MaskCache) Clear

func (c *MaskCache) Clear()

Clear empties all cached masks without resetting hit/miss counters.

func (*MaskCache) Hits

func (c *MaskCache) Hits() int64

Hits returns the cumulative number of cache hits.

func (*MaskCache) Len

func (c *MaskCache) Len() int

Len returns the current number of cached state masks.

func (*MaskCache) Misses

func (c *MaskCache) Misses() int64

Misses returns the cumulative number of cache misses.

type MaskStats

type MaskStats struct {
	Steps        int
	TotalAllowed int
	MinAllowed   int
	MaxAllowed   int
	CacheHits    int
	CacheMisses  int
}

MaskStats summarizes bitmask computation over a DecodeLoop run.

type Matcher

type Matcher struct {
	// contains filtered or unexported fields
}

Matcher enforces a Grammar over a byte stream.

It is a pushdown automaton: the stack holds the object and array nestings currently open, so nesting depth is bounded by the input rather than by the compiled grammar. A Matcher is not safe for concurrent use; use Matcher.Clone to explore alternatives, which is how Matcher.TokenMask works.

func (*Matcher) Accept

func (m *Matcher) Accept(b []byte) error

Accept advances the matcher over a run of bytes as a single atomic transition. On error the matcher is left unchanged, and the error names the offset of the first byte that could not be matched.

func (*Matcher) AcceptByte

func (m *Matcher) AcceptByte(c byte) error

AcceptByte advances the matcher over one byte. On error the matcher is left unchanged, and the error names the offset of the byte that could not be matched.

func (*Matcher) AcceptString

func (m *Matcher) AcceptString(s string) error

AcceptString is Accept for a string.

func (*Matcher) AcceptToken

func (m *Matcher) AcceptToken(v *Vocabulary, tokenID int32) error

AcceptToken validates and advances m by the bytes of tokenID in v as a single atomic transition step. If tokenID is out of range, empty, or rejected by the grammar, m is left completely unchanged and an error is returned.

func (*Matcher) Admits

func (m *Matcher) Admits(v Vocab, id int) bool

Admits reports whether the grammar can accept every byte of token id from the matcher's current state. The matcher is not advanced.

A token that decodes to no bytes is never admitted: it carries no evidence about the document, so a decoder that picked it would make no progress.

func (*Matcher) ApplyMask

func (m *Matcher) ApplyMask(v Vocab, logits []float32)

ApplyMask sets the logit of every token the grammar forbids to MaskedLogit, leaving the admitted ones as they are.

func (*Matcher) Bitmask

func (m *Matcher) Bitmask(v *Vocabulary) (*Bitmask, error)

Bitmask computes the packed Bitmask of tokens in v admitted from m's current state.

func (*Matcher) Clone

func (m *Matcher) Clone() *Matcher

Clone returns an independent copy of m.

func (*Matcher) CommitPrefix

func (m *Matcher) CommitPrefix(v *Vocabulary, acceptedTokens []int32) error

CommitPrefix advances m across each token in acceptedTokens after speculative verification. If any token in acceptedTokens is rejected by the grammar, CommitPrefix rolls back all tokens accepted during this call and returns an error.

func (*Matcher) Done

func (m *Matcher) Done() bool

Done reports whether a complete document has been matched. Once done, a matcher accepts only trailing whitespace.

func (*Matcher) FillBitmask

func (m *Matcher) FillBitmask(v Vocab, table *BitmaskTable, state int)

FillBitmask marks in table, for the given state row, every token the matcher admits. It lets a caller precompute a row once and apply it on the device with BitmaskTable.ApplyMask.

func (*Matcher) Finish

func (m *Matcher) Finish() error

Finish reports whether the document is complete, ending any number that runs to the end of the input.

A number has no closing delimiter, so a matcher fed "42" is still inside the number and not Done. Finish settles that case; it is the check to make when no more bytes are coming.

func (*Matcher) Pos

func (m *Matcher) Pos() int

Pos returns the number of bytes accepted so far.

func (*Matcher) Restore

func (m *Matcher) Restore(cp Checkpoint) error

Restore resets m to the state and transition history captured in cp.

func (*Matcher) Rollback

func (m *Matcher) Rollback(steps int) error

Rollback rewinds steps accepted transitions along m's transition history, matching XGrammar's matcher.rollback(n) in DeepInfer's speculative sampler.

func (*Matcher) Save

func (m *Matcher) Save() Checkpoint

Save captures the current state and transition history of m in O(1).

func (*Matcher) SpeculativeMasks

func (m *Matcher) SpeculativeMasks(v *Vocabulary, draftTokens []int32) ([]*Bitmask, error)

SpeculativeMasks implements DeepInfer's _get_so_mask loop for an N-token speculative draft chain:

  1. Emits mask 0 for the current matcher state (validating draftTokens[0]).
  2. For each draft token t_k (k in [0, len(draftTokens))): attempts to advance m with v.Token(int(t_k)). If accepted, emits mask k+1 from the new matcher state; if rejected (or m already terminated), fills remaining masks k+1..len(draftTokens) with an all-zero bitmask and stops advancing.
  3. Automatically calls Matcher.Rollback for the exact number of accepted draft transitions before returning so m's state is unchanged until verification commits the accepted prefix via Matcher.CommitPrefix.
Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/host/grammar"
)

func main() {
	g, err := grammar.CompileString(`{"type":"object","properties":{"n":{"type":"integer"}}}`)
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	vocab := grammar.NewVocabulary([]string{
		0: `{`,
		1: `"n"`,
		2: `:`,
		3: `42`,
		4: `}`,
		5: `"bad"`,
	})

	m := g.Match()
	if err := m.CommitPrefix(vocab, []int32{0, 1}); err != nil {
		fmt.Println("error:", err)
		return
	}

	// Speculative draft chain: [2 (":"), 3 ("42"), 5 ("\"bad\"")].
	// Tokens 2 and 3 are accepted by the grammar; token 5 is rejected.
	masks, err := m.SpeculativeMasks(vocab, []int32{2, 3, 5})
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Printf("pos after SpeculativeMasks=%d masks=%d mask0_allows_colon=%v mask2_allows_rbrace=%v mask3_allowed=%d\n",
		m.Pos(), len(masks), masks[0].IsAllowed(2), masks[2].IsAllowed(4), masks[3].CountAllowed())

	if err := m.CommitPrefix(vocab, []int32{2, 3, 4}); err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Printf("done=%v pos=%d\n", m.Done(), m.Pos())
}
Output:
pos after SpeculativeMasks=4 masks=4 mask0_allows_colon=true mask2_allows_rbrace=true mask3_allowed=0
done=true pos=8

func (*Matcher) TokenMask

func (m *Matcher) TokenMask(v Vocab, vocabSize int, dst []int) []int

TokenMask returns the ids below vocabSize that the grammar admits, in increasing order. dst is appended to and may be nil.

The result is the set a decoder may sample from. It is empty only if the vocabulary cannot continue the document at all, which is the caller's cue to stop rather than to sample.

type TokenTrie

type TokenTrie struct {
	// contains filtered or unexported fields
}

TokenTrie indexes a tokenizer vocabulary into a compact byte-prefix trie for pruned token bitmask generation over a CFGMatcher.

Tokens are indexed strictly by their raw UTF-8 byte sequences, so BPE tokens that split a single multi-byte UTF-8 codepoint across 2 to 4 tokens are handled seamlessly. The designated EOS token (if >= 0) is tracked separately and never matched as literal text; instead CFGMatcher.FillBitmask admits it if and only if CFGMatcher.CanFinish is true.

A TokenTrie is immutable once built and safe for concurrent use.

func BuildTokenTrie

func BuildTokenTrie(v Vocab, vocabSize, eosTokenID int) (*TokenTrie, error)

BuildTokenTrie constructs a compact TokenTrie over token IDs [0, vocabSize) using v. Pass eosTokenID < 0 if the vocabulary has no designated EOS token. Empty/control tokens (where v(id) returns nil or length 0) and eosTokenID are omitted from the byte trie.

func BuildVocabularyTrie

func BuildVocabularyTrie(v *Vocabulary, eosTokenID int) (*TokenTrie, error)

BuildVocabularyTrie constructs a TokenTrie from a Vocabulary.

func (*TokenTrie) EOSTokenID

func (t *TokenTrie) EOSTokenID() int

EOSTokenID returns the designated EOS token ID, or a negative value if unset.

func (*TokenTrie) NumNodes

func (t *TokenTrie) NumNodes() int

NumNodes returns the number of prefix nodes in the trie.

func (*TokenTrie) TokenBytes

func (t *TokenTrie) TokenBytes(id int) []byte

TokenBytes returns a copy of the raw UTF-8 bytes for token id, or nil if id is out of bounds, empty, or the EOS token.

func (*TokenTrie) Vocab

func (t *TokenTrie) Vocab() Vocab

Vocab returns a Vocab function backed by t's stored token bytes.

func (*TokenTrie) VocabSize

func (t *TokenTrie) VocabSize() int

VocabSize returns the number of token IDs covered by t.

func (*TokenTrie) Words

func (t *TokenTrie) Words() int

Words returns the number of uint32 bitmask words required for this vocabulary.

type Vocab

type Vocab func(id int) []byte

Vocab is a view of a tokenizer's vocabulary: it returns the bytes a token id stands for, or nil for an id the tokenizer does not decode to text, such as a control token. Taking a function rather than a table keeps the grammar independent of any one tokenizer.

type Vocabulary

type Vocabulary struct {
	// contains filtered or unexported fields
}

Vocabulary maps token IDs in [0, Size) to their decoded byte strings.

func NewVocabulary

func NewVocabulary(tokens []string) *Vocabulary

NewVocabulary constructs a Vocabulary from a slice of token strings indexed by token ID.

func (*Vocabulary) Size

func (v *Vocabulary) Size() int

Size returns the number of tokens in v.

func (*Vocabulary) Token

func (v *Vocabulary) Token(id int) string

Token returns the string representation of token ID id, or "" if id is out of bounds.

func (*Vocabulary) Vocab

func (v *Vocabulary) Vocab() Vocab

Vocab returns a Vocab function view of v for use with Matcher.Admits, Matcher.TokenMask, and Matcher.ApplyMask.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL