Last updated: 2026-11-17

Tokenization

Tokenizer

All API Sections

Native BPE tokenizer that reads vocabulary and merge rules from GGUF metadata.

Implements byte-pair encoding directly in Zig using the tokenizer tables embedded in GGUF model files, eliminating external tokenizer dependencies.

17 exports 0 methods src/model/tokenizer.zig

17 exports shown

struct

Tokenizer

#
pub const Tokenizer = struct

Memory Layout

Size: 224 bytes (alignment: 8)

Offset Size Align Field Type
0 16 8 vocab []const []const u8
16 40 8 token_to_id hash_map.HashMap([]const u8,u32,hash_map.StringContext,80)
56 16 8 merges []const model.tokenizer.Tokenizer.Merge
192 8 4 bos_id ?u32
200 4 4 eos_id u32
204 8 4 eot_id ?u32
212 1 1 prepend_bos bool
213 1 1 add_eos_token bool
72 16 8 scores ?[]const f32
88 16 8 chat_template ?[]const u8
214 1 1 pretokenizer model.tokenizer.Tokenizer.Pretokenizer
104 16 8 special_token_mask ?[]bool
120 16 8 eog_ids []const u32
215 1 1 eog_ids_owned bool
136 40 8 merge_ranks hash_map.HashMap([]const u8,u32,hash_map.StringContext,80)
216 1 1 merge_ranks_ready bool
176 16 8 allocator mem.Allocator

No public doc comment yet.

src/model/tokenizer.zig:86

function

initFromGGUF

#
pub fn initFromGGUF(gf: *const gguf.GGUFFile, allocator: std.mem.Allocator) !Tokenizer

Initialize a Tokenizer from an open GGUF file.

Reads `tokenizer.ggml.tokens`, `tokenizer.ggml.merges`, token scores, and special token IDs (BOS, EOS, add-BOS flag) from GGUF metadata. Also builds the `merge_ranks` lookup table so that subsequent `encode` calls are fast.

Parameters

gf
Parsed GGUF file whose metadata contains the tokenizer tables.
allocator
Used for all owned heap allocations; pass to `deinit` to free.

Returns

An initialized Tokenizer, or an error if required metadata is absent.

src/model/tokenizer.zig:160

function

encode

#
pub fn encode(self: *const Tokenizer, text: []const u8) ![]u32

Encode UTF-8 text into a sequence of token IDs.

Applies the appropriate pretokenizer (Gemma-4 chunk splitter, GPT-2 word splitter, or legacy no-split) and then BPE or SentencePiece merges. The returned slice is owned by the caller; free it with `freeEncoded`.

Parameters

text
UTF-8 input to tokenize; an empty string returns an empty slice.

Returns

Heap-allocated token ID sequence, or an error on allocation failure.

src/model/tokenizer.zig:847

function

freeEncoded

#
pub fn freeEncoded(self: *const Tokenizer, tokens: []u32) void

Release a token slice returned by `encode`.

src/model/tokenizer.zig:900

function

encodePrompt

#
pub fn encodePrompt(self: *const Tokenizer, text: []const u8, allocator: std.mem.Allocator) ![]u32

Encode a prompt and prepend BOS when the model expects it.

The returned slice is allocated with `allocator`, so server routes can use a per-request allocator while the tokenizer keeps owning its internal scratch buffers. Special tokens (e.g. `<|start_header_id|>`) are resolved via `token_to_id` rather than being BPE-encoded character by character.

src/model/tokenizer.zig:909

function

encodeAppended

#
pub fn encodeAppended(self: *const Tokenizer, text: []const u8, allocator: std.mem.Allocator) ![]u32

Encode text that may contain special-token markers, without prepending BOS: for appending a rendered tail to a token sequence the engine holds.

src/model/tokenizer.zig:935

function

eosId

#
pub fn eosId(self: *const Tokenizer) u32

Return the model's end-of-sequence token ID as loaded from GGUF metadata.

src/model/tokenizer.zig:1294

function

isEndOfGeneration

#
pub fn isEndOfGeneration(self: *const Tokenizer, token: u32) bool

Whether a sampled token ends the current generation turn.

Always terminates on the configured EOS. Gemma 4 additionally uses `<eos>=1` and `</s>=212` alongside the primary `<turn|>=106` EOS — we treat those as EOG too when the chat template is Gemma, but not for other tokenizers (Qwen token 1 is a plain `"` character).

src/model/tokenizer.zig:1304

function

templateStartsWithBos

#
pub fn templateStartsWithBos(self: *const Tokenizer) bool

Recognize an unconditional leading `{{ bos_token }}` output, including Jinja whitespace control and multiline spacing (as in MiniCPM5).

This is deliberately not an expression evaluator: a conditional, filter, or similarly named variable does not establish that BOS will be emitted.

src/model/tokenizer.zig:1325

function

bosId

#
pub fn bosId(self: *const Tokenizer) u32

Return the model's beginning-of-sequence token ID.

Falls back to `eos_id` when no BOS token was found in GGUF metadata.

src/model/tokenizer.zig:1342

function

shouldPrependBos

#
pub fn shouldPrependBos(self: *const Tokenizer) bool

Return true when prompt construction should prepend a BOS token.

Requires both `prepend_bos` (from GGUF metadata) to be set and a valid `bos_id` to exist; returns false if either condition is absent.

src/model/tokenizer.zig:1349

function

preparePromptTokens

#
pub fn preparePromptTokens(self: *const Tokenizer, raw_tokens: []const u32) ![]u32

Wrap a raw token sequence with BOS/EOS according to the GGUF metadata flags.

Prepends BOS when `shouldPrependBos()` is true and appends EOS when `add_eos_token` is set. Allocates the result with the tokenizer's own allocator; caller is responsible for freeing the returned slice.

Parameters

raw_tokens
The BPE-encoded token IDs to wrap.

Returns

A newly allocated slice with optional BOS prefix and EOS suffix.

src/model/tokenizer.zig:1359

function

decodeToken

#
pub fn decodeToken(self: *const Tokenizer, token_id: u32, buf: []u8) []const u8

Decode a single token ID to UTF-8 text, reversing the GPT-2 byte-to-unicode mapping.

Handles SentencePiece word-boundary markers (▁ → space) and passes through non-ASCII codepoints (CJK, emoji) verbatim. Returns an empty string for out-of-range token IDs.

Parameters

token_id
Vocabulary index to decode.
buf
Caller-supplied output buffer; result is a slice into this buffer.

Returns

UTF-8 bytes for the token, or an empty slice if the ID is out of range.

src/model/tokenizer.zig:1385

struct

ChatTemplateOptions

#
pub const ChatTemplateOptions = struct

Options controlling chat template rendering behavior.

src/model/tokenizer.zig:1469

function

supportsThinkingToggle

#
pub fn supportsThinkingToggle(self: *const Tokenizer) bool

Return whether the model's chat template supports an explicit thinking toggle.

src/model/tokenizer.zig:1542

function

applyChatTemplate

#
pub fn applyChatTemplate(self: *const Tokenizer, roles: []const []const u8, contents: []const []const u8, buf: []u8) ![]const u8

Format a conversation into a model prompt using the embedded chat template.

Convenience wrapper around `applyChatTemplateWithOptions` with default options.

Parameters

roles
Parallel slice of role strings (e.g. "user", "assistant", "system").
contents
Parallel slice of message body strings.
buf
Caller-supplied output buffer that receives the formatted prompt.

Returns

A slice of `buf` containing the rendered prompt.

src/model/tokenizer.zig:1557

function

applyChatTemplateWithOptions

#
pub fn applyChatTemplateWithOptions(self: *const Tokenizer, roles: []const []const u8, contents: []const []const u8, options: ChatTemplateOptions, buf: []u8) ![]const u8

Format a conversation into a model prompt with fine-grained rendering control.

Dispatches to the appropriate template renderer (ChatML, Llama-3, Gemma, OpenAI-MoE, or generic) based on `detectTemplateKind()`. Supports optional thinking tags, tool definitions, forced tool-call prefills, and generation-prompt suffixes.

Parameters

roles
Parallel slice of role strings (e.g. "user", "assistant", "system").
contents
Parallel slice of message body strings.
options
Rendering options; see `ChatTemplateOptions` for details.
buf
Caller-supplied output buffer that receives the formatted prompt.

Returns

A slice of `buf` containing the rendered prompt.

src/model/tokenizer.zig:1570