tokenizers

package
v2.0.4 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2026 License: MIT Imports: 28 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 tokenizers counts and makes the tokens of a text exactly as a model's own tokenizer does, in Go: the Hugging Face tokenizer.json pipeline of either version, the files a model snapshot ships instead (vocab.json with merges.txt, vocab.txt, SentencePiece models, tiktoken rank files, Mistral's tekken.json), and the tokenizer a GGUF model file carries

Index

Constants

View Source
const Formats = "tokenizer.json, tekken.json, tiktoken.model, a SentencePiece model (tokenizer.model, spiece.model, sentencepiece.bpe.model, " +
	"spm.model or sentencepiece.model), vocab.json with merges.txt, or vocab.txt"

The tokenizer files Load reads, in the order it looks for them

View Source
const GPT2Split = `'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+`

GPT-2's split, which a ByteLevel pre-tokenizer runs when it uses its regex

Variables

View Source
var Files = []string{"tokenizer.json", "tekken.json", "tiktoken.model", "tokenizer.model", "spiece.model", "sentencepiece.bpe.model",
	"spm.model", "sentencepiece.model", "vocab.json", "merges.txt", "vocab.txt", "tokenizer_config.json", "special_tokens_map.json",
	"added_tokens.json", "config.json", "chat_template.jinja", "chat_template.json"}

Files a snapshot's tokenizer is read from, any of which may be absent: what Load reads, and what a download of a snapshot fetches

Functions

func Pad

func Pad(encodings []*Encoding, p Padding)

Pads every encoding, and what overflowed from it, to the batch's longest or to the fixed length, rounded up to the multiple

Types

type AddedToken

type AddedToken struct {
	ID         int    `json:"id"`
	Content    string `json:"content"`
	SingleWord bool   `json:"single_word"`
	LStrip     bool   `json:"lstrip"`
	RStrip     bool   `json:"rstrip"`
	Normalized bool   `json:"normalized"`
	Special    bool   `json:"special"`
	// A control token of tokenizer.json 2.0
	Control bool `json:"control"`
}

A token cut out of the text before the model runs, as tokenizer.json's added_tokens and a config's added_tokens_decoder write them

func (*AddedToken) UnmarshalJSON

func (a *AddedToken) UnmarshalJSON(data []byte) error

Reads an added token, one that does not say whether it is normalized being so unless it is special

type Dir

type Dir string

A snapshot folder on disk

func (Dir) Has

func (d Dir) Has(name string) bool

func (Dir) Read

func (d Dir) Read(name string) ([]byte, error)

type Encoding

type Encoding struct {
	IDs []int
	// Byte range of the text each id stands for; empty at where a token the tokenizer added stands
	Offsets [][2]int
	// Whether each id is a special token: one the tokenizer added around the text, or a special token read in it
	Special []bool
	// Sequence each id belongs to under a pair template, 0 for the first
	TypeIDs []int
	// Whether each id is one the model attends to, 0 for padding; nil when nothing was padded
	Attention []int
	// What truncation cut off, each part its own encoding
	Overflowing []*Encoding
}

The ids of a text and what is known of each

func (*Encoding) Len

func (e *Encoding) Len() int

Number of ids

func (*Encoding) Prefix

func (e *Encoding) Prefix(n int) int

Byte length of the longest start of the text the first n ids stand for whole

func (*Encoding) Suffix

func (e *Encoding) Suffix(n int, length int) int

Byte offset where the last n ids of the text start

type GGUF

type GGUF struct {
	Version int
	Meta    map[string]any
}

The metadata of a GGUF model file: every key of its header with its value, read without its tensors (ggml's docs/gguf.md)

func ReadGGUF

func ReadGGUF(r io.Reader) (*GGUF, error)

Reads the header of a GGUF stream, its metadata whole

func ReadGGUFFile

func ReadGGUFFile(path string) (*GGUF, error)

Reads the header of a GGUF file

func (*GGUF) Architecture

func (g *GGUF) Architecture() string

The model's architecture, such as llama or qwen3

func (*GGUF) Bool

func (g *GGUF) Bool(key string) (bool, bool)

A boolean value

func (*GGUF) ChatTemplate

func (g *GGUF) ChatTemplate() string

The chat template the file carries, empty for none

func (*GGUF) ContextLength

func (g *GGUF) ContextLength() int

The context length the model was trained for, 0 when the file says none

func (*GGUF) Int

func (g *GGUF) Int(key string) (int, bool)

A whole number value

func (*GGUF) Repos

func (g *GGUF) Repos() []string

The Hugging Face repositories the model was made from, the source first and its base models after, as org/name

func (*GGUF) String

func (g *GGUF) String(key string) string

A string value

func (*GGUF) Tokenizer

func (g *GGUF) Tokenizer() (*Snapshot, error)

The tokenizer the file carries, built as llama.cpp reads it: an embedded tokenizer.json whole, a gpt2 vocabulary as the Hugging Face pipeline its pre-tokenizer names, a llama vocabulary as SentencePiece BPE, a t5 one as SentencePiece unigram, a bert one as WordPiece

type Memo

type Memo interface {
	Get(key string) (int, bool)
	Put(key string, n int)
}

Where counts of stretches of text are kept between calls, so a text that grows, such as a session's messages, is counted only where it changed

type Options

type Options struct {
	// Special tokens written in the text are read as themselves, as a chat template's rendering is; otherwise they are read as text
	Specials bool
	// What the tokenizer puts around a sequence is added, such as a start token
	Frame bool
}

How a text is encoded

type Padding

type Padding struct {
	// Every encoding padded to the longest of the batch, or to Fixed when it is above zero
	Fixed      int
	Right      bool
	MultipleOf int
	PadID      int
	PadTypeID  int
	PadToken   string
}

How encodings are padded to one length, as tokenizer.json's padding writes it

type Pipeline

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

The pipeline a tokenizer.json describes, of version 1.0 or 2.0: added tokens, normalizer, pre-tokenizer, model, post-processor and decoder

func FromJSON

func FromJSON(data []byte) (*Pipeline, error)

The tokenizer a tokenizer.json describes

func (*Pipeline) Added

func (t *Pipeline) Added() []AddedToken

The added tokens, in the order they were added

func (*Pipeline) Count

func (t *Pipeline) Count(s string, opts Options) (int, error)

Number of ids of a text

func (*Pipeline) Decode

func (t *Pipeline) Decode(ids []int, skip bool) (string, error)

Text of ids, special tokens left out when skip is set

func (*Pipeline) Encode

func (t *Pipeline) Encode(s string, opts Options) (*Encoding, error)

Ids of a text with where each stands in it

func (*Pipeline) EncodeBatch

func (t *Pipeline) EncodeBatch(texts []string, opts Options, pad *Padding) ([]*Encoding, error)

Ids of every text, padded as the padding says, which the file's padding stands for when nil

func (*Pipeline) EncodePair

func (t *Pipeline) EncodePair(a, b string, opts Options) (*Encoding, error)

Ids of a pair of texts as the pair template puts them together, the second of type 1 unless the template says otherwise

func (*Pipeline) ID

func (t *Pipeline) ID(token string) (int, bool)

Id of a token, an added token before one of the model

func (*Pipeline) Padding

func (t *Pipeline) Padding() *Padding

The padding the file sets, nil for none

func (*Pipeline) Roles

func (t *Pipeline) Roles() map[string]string

Special tokens by role, as the snapshot's settings name them

func (*Pipeline) Size

func (t *Pipeline) Size() int

Ids the tokenizer knows, one past the highest

func (*Pipeline) Tally

func (t *Pipeline) Tally(s string, opts Options, memo Memo) (int, error)

Number of ids of a text a stretch at a time: the raw added tokens cut it before the normalizer runs, and every later step reads a stretch alone, knowing only whether it opens the input, so each stretch is counted on its own and one the memo knows is not counted again

func (*Pipeline) Token

func (t *Pipeline) Token(id int) (string, bool)

Token of an id, an added token before one of the model

func (*Pipeline) Truncated

func (t *Pipeline) Truncated(a string, b *string, opts Options, trunc Truncation) (*Encoding, error)

Ids of a text, or of a pair when b is given, cut to fit as the truncation says; what is cut off is in Overflowing, each part as long as the rest allow with stride ids of the part before repeated

func (*Pipeline) Truncation

func (t *Pipeline) Truncation() *Truncation

The truncation the file sets, nil for none

type Snapshot

type Snapshot struct {
	Tokenizer Tokenizer
	// Chat templates by name, "default" the one a conversation is rendered with when none is named
	Templates map[string]string
	// The tokenizer class the settings name, without its Fast
	Class string
	// The settings ask for a start token before a sequence, and an end token after it
	AddBOS, AddEOS bool
}

A snapshot's tokenizer with what its settings say beside it

func Load

func Load(src Source) (*Snapshot, error)

Reads the tokenizer of a snapshot from whichever tokenizer file it ships

type Source

type Source interface {
	Has(name string) bool
	Read(name string) ([]byte, error)
}

Reads the files of one tokenizer snapshot

type Stretcher

type Stretcher interface {
	// Number of ids of a text, as Count gives it
	Tally(text string, opts Options, memo Memo) (int, error)
}

A tokenizer that counts a text a stretch at a time: the tokens it cuts out of a text before anything else reads it make stretches counted on their own, so a stretch counted before is taken from the memo

type Tokenizer

type Tokenizer interface {
	// Ids of a text with where each stands in it
	Encode(text string, opts Options) (*Encoding, error)
	// Number of ids of a text, as Encode gives them
	Count(text string, opts Options) (int, error)
	// Text of ids, special tokens left out when skip is set
	Decode(ids []int, skip bool) (string, error)
	// Id of a token as the vocabulary writes it, added and special tokens among them
	ID(token string) (int, bool)
	// Token of an id as the vocabulary writes it
	Token(id int) (string, bool)
	// Ids the tokenizer knows, one past the highest
	Size() int
	// Special tokens by role, such as bos, eos, unk and pad, as the tokenizer's files name them
	Roles() map[string]string
}

What every tokenizer does, whichever family it is of

func FromEncoding

func FromEncoding(enc *tiktoken.Encoding) Tokenizer

A tokenizer of a tiktoken encoding as OpenAI's models read text: nothing put around a sequence

func Tekken

func Tekken(data []byte) (Tokenizer, error)

The tokenizer of a tekken.json, a start token put before a sequence when framed, as Mistral's models take one

type Truncation

type Truncation struct {
	MaxLength int `json:"max_length"`
	// Ids of the part before each overflowing part repeats
	Stride int `json:"stride"`
	// LongestFirst, OnlyFirst or OnlySecond
	Strategy string `json:"strategy"`
	// Right cuts the end, Left the start
	Direction string `json:"direction"`
}

How an encoding is cut to a length, as tokenizer.json's truncation writes it

Directories

Path Synopsis
Package chat renders the chat templates models ship, the Jinja Hugging Face tokenizer configs and GGUF files carry, into the text a conversation is sent to the model as: the template language with the filters, tests, methods and globals these templates use
Package chat renders the chat templates models ship, the Jinja Hugging Face tokenizer configs and GGUF files carry, into the text a conversation is sent to the model as: the template language with the filters, tests, methods and globals these templates use
Package pattern compiles the regular expressions tokenizers cut text with, written for Oniguruma (Hugging Face tokenizers) or for Rust's fancy-regex (tiktoken, Mistral's tekken, llama.cpp), into what regexp2 runs with the same matches
Package pattern compiles the regular expressions tokenizers cut text with, written for Oniguruma (Hugging Face tokenizers) or for Rust's fancy-regex (tiktoken, Mistral's tekken, llama.cpp), into what regexp2 runs with the same matches
Package sentencepiece reads SentencePiece models and encodes and decodes text with them as the C++ library does, without it: the unigram, BPE, word and character models, the precompiled normalization map and byte fallback
Package sentencepiece reads SentencePiece models and encodes and decodes text with them as the C++ library does, without it: the unigram, BPE, word and character models, the precompiled normalization map and byte fallback
Package tiktoken is the byte-pair encoding OpenAI's models count tokens with: a vocabulary of byte strings ranked by merge priority, a pattern that cuts text into pieces before the merges, and special tokens, read from the rank files OpenAI publishes
Package tiktoken is the byte-pair encoding OpenAI's models count tokens with: a vocabulary of byte strings ranked by merge priority, a pattern that cuts text into pieces before the merges, and special tokens, read from the rank files OpenAI publishes

Jump to

Keyboard shortcuts

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