Skip to content

mistral_common.tokens.tokenizers.tekken

ModelData

Bases: TypedDict

Complete tekken tokenizer model data from the JSON file.

Attributes:

Name Type Description
vocab list[TokenInfo]

List of TokenInfo entries for regular vocabulary tokens.

special_tokens list[SpecialTokenInfo] | None

List of SpecialTokenInfo entries, or None to use defaults.

config TekkenConfig

TekkenConfig with tokenizer settings.

version int

Integer version of the tokenizer file format.

type str

String type identifier for the tokenizer.

image ImageConfig

ImageConfig for image processing, or missing if not supported.

audio AudioConfig

AudioConfig for audio processing, or missing if not supported.

SpecialTokenInfo

Bases: TypedDict

Special token information in the JSON file.

Attributes:

Name Type Description
rank int

The integer rank/index of this special token.

token_str str

The string representation of the special token.

is_control bool

True if this is a control token (non-printable), False otherwise.

TekkenConfig

Bases: TypedDict

Tekken tokenizer configuration in the JSON file.

Attributes:

Name Type Description
pattern str

Regex pattern string used for tokenization (tiktoken pat_str).

num_vocab_tokens int

Number of regular (non-special) tokens in the vocabulary.

default_vocab_size int

Default total vocabulary size (vocab + special tokens).

default_num_special_tokens int

Default number of special tokens.

version str

Version string of the tokenizer (e.g., "v1", "v2").

Tekkenizer(vocab, special_tokens, pattern, vocab_size, num_special_tokens, version, *, name='tekkenizer', _path=None, image_config=None, audio_config=None, model_settings_builder=None)

Bases: Tokenizer

Tekken tokenizer based on the tiktoken library.

High-performance tokenizer for multiple languages, supporting text, image, and audio modalities. Uses byte-level BPE with customizable patterns and special tokens.

The tokenizer works by: 1. Using tiktoken's fast BPE encoder for regular tokens 2. Managing special tokens separately (prefixed to the vocabulary) 3. Supporting multimodal configurations via image_config and audio_config

Parameters:

Name Type Description Default
vocab list[TokenInfo]

List of token information defining the vocabulary. Each entry contains the token's rank, base64-encoded bytes, and string representation.

required
special_tokens list[SpecialTokenInfo]

List of special token definitions. If fewer than num_special_tokens are provided, filler tokens are generated automatically.

required
pattern str

Regex pattern used for tokenization (tiktoken pat_str).

required
vocab_size int

Total vocabulary size (vocab tokens + special tokens). Must be <= len(vocab) + num_special_tokens.

required
num_special_tokens int

Total number of special tokens. If special_tokens list is shorter, filler tokens are added to reach this count.

required
version TokenizerVersion

Tokenizer version. Determines supported features and validation rules.

required
name str

Identifier for this tokenizer instance. Defaults to "tekkenizer".

'tekkenizer'
_path str | Path | None

Source file path. Internal use only; not for direct instantiation.

None
image_config ImageConfig | None

Configuration for image processing, or None if not supported.

None
audio_config AudioConfig | None

Configuration for audio processing, or None if not supported.

None
model_settings_builder ModelSettingsBuilder | None

Builder for model-specific settings. Must be None if version does not support model settings (pre-v15).

None

Raises:

Type Description
ValueError

If model_settings_builder is provided but version does not support it.

AssertionError

If vocab_size constraint is violated or special tokens are invalid.

Source code in src/mistral_common/tokens/tokenizers/tekken.py
def __init__(
    self,
    vocab: list[TokenInfo],
    special_tokens: list[SpecialTokenInfo],
    pattern: str,
    vocab_size: int,
    num_special_tokens: int,
    version: TokenizerVersion,
    *,
    name: str = "tekkenizer",
    _path: str | Path | None = None,
    image_config: ImageConfig | None = None,
    audio_config: AudioConfig | None = None,
    model_settings_builder: ModelSettingsBuilder | None = None,
):
    r"""Initialize the tekken tokenizer.

    Args:
        vocab: List of token information defining the vocabulary. Each entry contains
            the token's rank, base64-encoded bytes, and string representation.
        special_tokens: List of special token definitions. If fewer than
            `num_special_tokens` are provided, filler tokens are generated automatically.
        pattern: Regex pattern used for tokenization (tiktoken `pat_str`).
        vocab_size: Total vocabulary size (vocab tokens + special tokens).
            Must be <= len(vocab) + `num_special_tokens`.
        num_special_tokens: Total number of special tokens. If `special_tokens` list
            is shorter, filler tokens are added to reach this count.
        version: Tokenizer version. Determines supported features and validation rules.
        name: Identifier for this tokenizer instance. Defaults to "tekkenizer".
        _path: Source file path. Internal use only; not for direct instantiation.
        image_config: Configuration for image processing, or `None` if not supported.
        audio_config: Configuration for audio processing, or `None` if not supported.
        model_settings_builder: Builder for model-specific settings. Must be `None` if
            version does not support model settings (pre-v15).

    Raises:
        ValueError: If `model_settings_builder` is provided but version does not support it.
        AssertionError: If `vocab_size` constraint is violated or special tokens are invalid.
    """
    if not version.supports_model_settings and model_settings_builder is not None:
        raise ValueError(
            f"model_settings_builder is not supported for {version=} but got {model_settings_builder=}"
        )

    assert vocab_size <= len(vocab) + num_special_tokens, (
        vocab_size,
        len(vocab),
        num_special_tokens,
    )
    self._vocab_size = vocab_size

    # The number of special tokens defined in the tokenizer json
    num_defined_special_tokens = len(set([t["token_str"] for t in special_tokens]))

    assert len(special_tokens) == num_defined_special_tokens, f"Special tokens must be unique: {special_tokens}"
    assert len(special_tokens) <= num_special_tokens

    special_filler = [
        SpecialTokenInfo(rank=i, token_str=self.SPECIAL_TOKEN_TEMPLATE.format(id=i), is_control=True)
        for i in range(len(special_tokens), num_special_tokens)
    ]
    if special_filler:
        logger.info(
            f"Adding special tokens {special_filler[0]['token_str']}, ..., {special_filler[-1]['token_str']}"
        )
    special_tokens = special_tokens + special_filler

    assert len(set([t["token_str"] for t in special_tokens])) == len(special_tokens) == num_special_tokens, (
        special_tokens
    )
    inner_vocab_size = vocab_size - num_special_tokens

    # reload vocab
    logger.info(f"Non special vocabulary size is {inner_vocab_size} with {num_special_tokens} special tokens.")
    self._tekken_token2id_nospecial = _reload_mergeable_ranks(vocab, max_vocab=inner_vocab_size)
    assert set(range(inner_vocab_size)) == set(self._tekken_token2id_nospecial.values()), (
        inner_vocab_size,
        self._tekken_token2id_nospecial,
    )
    self._model = tiktoken.Encoding(
        name=name,
        pat_str=pattern,
        mergeable_ranks=self._tekken_token2id_nospecial,
        special_tokens={},  # special tokens are handled manually
    )

    self._version = version

    self._image_config = image_config
    self._audio_config = audio_config

    self._all_special_tokens = special_tokens
    self._special_token_ids = {t["rank"] for t in special_tokens}
    self._special_tokens_reverse_vocab = {t["token_str"]: t["rank"] for t in special_tokens}
    self._vocab = [self.id_to_piece(i) for i in range(vocab_size)]
    self._special_token_policy = SpecialTokenPolicy.IGNORE
    self._file_path = Path(_path) if _path is not None else None
    self._model_settings_builder = model_settings_builder

audio property writable

The audio configuration for this tokenizer.

Returns:

Type Description
AudioConfig | None

AudioConfig instance if audio support is configured, otherwise None.

bos_id cached property

The beginning-of-sentence token ID.

eos_id cached property

The end-of-sentence token ID.

file_path property

The path to the tokenizer file.

Returns:

Type Description
Path

Path to the source JSON file.

Raises:

Type Description
ValueError

If the tokenizer was not loaded from a file (e.g., constructed directly via init without _path).

image property writable

The image configuration for this tokenizer.

Returns:

Type Description
ImageConfig | None

ImageConfig instance if image support is configured, otherwise None.

model_settings_builder property

The model settings builder for this tokenizer.

Returns:

Type Description
ModelSettingsBuilder | None

ModelSettingsBuilder instance if the tokenizer version supports model

ModelSettingsBuilder | None

settings, otherwise None.

n_words property

Total vocabulary size of the tokenizer.

Returns:

Type Description
int

Sum of regular vocabulary tokens and special tokens.

num_special_tokens property

The total number of special tokens in this tokenizer.

Returns:

Type Description
int

Count of all special tokens (original + filler tokens).

pad_id cached property

The padding token ID.

special_ids cached property

Set of all special token IDs.

Returns:

Type Description
set[int]

Set of integer IDs for all special tokens in this tokenizer.

unk_id cached property

The unknown token ID.

version property

The version of this tokenizer.

Returns:

Type Description
TokenizerVersion

TokenizerVersion enum value indicating the tokenizer's version.

decode(tokens, special_token_policy=SpecialTokenPolicy.IGNORE)

Decode a list of token IDs into a string.

Parameters:

Name Type Description Default
tokens list[int]

List of token IDs to decode.

required
special_token_policy SpecialTokenPolicy

Policy for handling special tokens: - IGNORE: Skip special tokens (default) - KEEP: Include special token strings in output - RAISE: Raise ValueError if special tokens are present

IGNORE

Returns:

Type Description
str

The decoded UTF-8 string.

Raises:

Type Description
ValueError

If special_token_policy is invalid or RAISE is set and special tokens are encountered.

Source code in src/mistral_common/tokens/tokenizers/tekken.py
def decode(self, tokens: list[int], special_token_policy: SpecialTokenPolicy = SpecialTokenPolicy.IGNORE) -> str:
    r"""Decode a list of token IDs into a string.

    Args:
        tokens: List of token IDs to decode.
        special_token_policy: Policy for handling special tokens:
            - IGNORE: Skip special tokens (default)
            - KEEP: Include special token strings in output
            - RAISE: Raise ValueError if special tokens are present

    Returns:
        The decoded UTF-8 string.

    Raises:
        ValueError: If `special_token_policy` is invalid or RAISE is set and
            special tokens are encountered.
    """
    try:
        special_token_policy = SpecialTokenPolicy(special_token_policy)
    except ValueError as e:
        valid = ", ".join(repr(p.value) for p in SpecialTokenPolicy)
        raise ValueError(
            f"Invalid `special_token_policy` {special_token_policy!r}. Expected one of: {valid}."
        ) from e

    return "".join(self._decode_all(tokens, special_token_policy=special_token_policy))

encode(s, bos, eos)

Encode a string into a list of token ids.

Parameters:

Name Type Description Default
s str

The string to encode.

required
bos bool

If True, prepends the beginning-of-sentence token ID to the result.

required
eos bool

If True, appends the end-of-sentence token ID to the result.

required

Returns:

Type Description
list[int]

List of token IDs. Regular tokens are offset by num_special_tokens.

Source code in src/mistral_common/tokens/tokenizers/tekken.py
def encode(self, s: str, bos: bool, eos: bool) -> list[int]:
    r"""Encode a string into a list of token ids.

    Args:
        s: The string to encode.
        bos: If `True`, prepends the beginning-of-sentence token ID to the result.
        eos: If `True`, appends the end-of-sentence token ID to the result.

    Returns:
        List of token IDs. Regular tokens are offset by `num_special_tokens`.
    """
    tokens: list[int] = self._model.encode(s)
    tokens = [t + self.num_special_tokens for t in tokens]
    if bos:
        tokens = [self.bos_id, *tokens]
    if eos:
        tokens = [*tokens, self.eos_id]
    return tokens

from_file(path) classmethod

Load the tekken tokenizer from a JSON file.

The file must contain vocab, config, and optionally special_tokens, image, audio, and model_settings_builder sections.

Parameters:

Name Type Description Default
path str | Path

Path to the tokenizer JSON file. Must exist and be readable.

required

Returns:

Type Description
Tekkenizer

A Tekkenizer instance configured from the file.

Raises:

Type Description
ValueError

If the file has an unknown version, is missing required fields, or contains incompatible configuration (e.g., model_settings_builder with a version that does not support it).

AssertionError

If the file does not exist.

Source code in src/mistral_common/tokens/tokenizers/tekken.py
@classmethod
def from_file(cls: type["Tekkenizer"], path: str | Path) -> "Tekkenizer":
    r"""Load the tekken tokenizer from a JSON file.

    The file must contain vocab, config, and optionally `special_tokens`, image,
    audio, and `model_settings_builder` sections.

    Args:
        path: Path to the tokenizer JSON file. Must exist and be readable.

    Returns:
        A Tekkenizer instance configured from the file.

    Raises:
        ValueError: If the file has an unknown version, is missing required fields,
            or contains incompatible configuration (e.g., `model_settings_builder`
            with a version that does not support it).
        AssertionError: If the file does not exist.
    """
    if isinstance(path, str):
        path = Path(path)
    assert path.exists(), path
    with open(path, "r", encoding="utf-8") as f:
        untyped = json.load(f)

    _version_str = untyped["config"].get("version")
    if _version_str not in TokenizerVersion.__members__:
        raise ValueError(
            f"Unknown version: {_version_str} in {path}. "
            f"Make sure to use a valid version string: {list(TokenizerVersion.__members__)}"
        )

    assert _version_str is not None
    version = TokenizerVersion(_version_str)

    special_tokens_dicts: list[SpecialTokenInfo] | None = untyped.get("special_tokens", None)
    if special_tokens_dicts is None:
        # Tokenizer > v7 should find special tokens in the tokenizer file
        if version > TokenizerVersion.v7:
            raise ValueError(
                f"Special tokens not found in {path}. "
                "Please update your tokenizer file and include all special tokens you need."
            )
        else:
            special_tokens = list(Tekkenizer.DEPRECATED_SPECIAL_TOKENS)
    else:
        special_tokens = [token for token in special_tokens_dicts]

    untyped["special_tokens"] = special_tokens

    if mm := untyped.get("multimodal"):
        # deprecated - only allowed for tokenizers <= v11
        if version > TokenizerVersion.v11:
            raise ValueError(
                f"The image config has to be called 'image' in {path} for tokenizers of version {version.value}."
            )

        untyped["image"] = ImageConfig(**mm)
    elif image := untyped.get("image"):
        untyped["image"] = ImageConfig(**image)

    if audio := untyped.get("audio"):
        encoding_config = audio.pop("audio_encoding_config")
        encoding_config = AudioSpectrogramConfig(**encoding_config)
        untyped["audio"] = AudioConfig(encoding_config=encoding_config, **audio)

    if (
        model_settings_builder := untyped.get("model_settings_builder")
    ) is not None and not version.supports_model_settings:
        raise ValueError(
            f"model_settings_builder is not supported for {version=} but got {model_settings_builder=}"
        )
    elif model_settings_builder is not None:
        model_settings_builder = ModelSettingsBuilder.model_validate(model_settings_builder)

    model_data: ModelData = untyped

    return cls(
        vocab=model_data["vocab"],
        special_tokens=special_tokens,
        pattern=model_data["config"]["pattern"],
        vocab_size=model_data["config"]["default_vocab_size"],
        num_special_tokens=model_data["config"]["default_num_special_tokens"],
        version=version,
        name=path.name.replace(".json", ""),
        image_config=model_data.get("image"),
        audio_config=model_data.get("audio"),
        model_settings_builder=model_settings_builder,
        _path=path,
    )

get_control_token(s)

Get the token ID of a control token. Deprecated: use get_special_token() instead.

Deprecated: Use get_special_token() instead.

Parameters:

Name Type Description Default
s str

The string representation of the control token.

required

Returns:

Type Description
int

The integer token ID for the control token.

Source code in src/mistral_common/tokens/tokenizers/tekken.py
def get_control_token(self, s: str) -> int:
    r"""Get the token ID of a control token. Deprecated: use `get_special_token()` instead.

    Deprecated: Use `get_special_token()` instead.

    Args:
        s: The string representation of the control token.

    Returns:
        The integer token ID for the control token.
    """
    warnings.warn("`get_control_token` is deprecated. Use `get_special_token` instead.", FutureWarning)
    return self.get_special_token(s)

get_special_token(s)

Get the token ID of a special token by its string representation.

Parameters:

Name Type Description Default
s str

The string representation of the special token (e.g., "", "").

required

Returns:

Type Description
int

The integer token ID for the special token.

Raises:

Type Description
ValueError

If the special token string is not recognized.

Source code in src/mistral_common/tokens/tokenizers/tekken.py
def get_special_token(self, s: str) -> int:
    r"""Get the token ID of a special token by its string representation.

    Args:
        s: The string representation of the special token (e.g., "<s>", "<eos>").

    Returns:
        The integer token ID for the special token.

    Raises:
        ValueError: If the special token string is not recognized.
    """
    if s in self._special_tokens_reverse_vocab:
        return self._special_tokens_reverse_vocab[s]
    else:
        raise ValueError(f"Unknown control token {s}")

id_to_byte_piece(token_id, special_token_policy=SpecialTokenPolicy.IGNORE)

Convert a token ID to its byte representation.

Parameters:

Name Type Description Default
token_id int

The token ID to convert.

required
special_token_policy SpecialTokenPolicy

Policy for handling special tokens: - IGNORE: Return empty bytes for special tokens - KEEP: Return UTF-8 encoded special token string - RAISE: Raise ValueError if token is special

IGNORE

Returns:

Type Description
bytes

The byte representation of the token. For regular tokens, returns the

bytes

original byte sequence from the vocabulary.

Raises:

Type Description
ValueError

If special_token_policy is RAISE and token_id is a special token, or if special_token_policy is invalid.

Source code in src/mistral_common/tokens/tokenizers/tekken.py
def id_to_byte_piece(
    self, token_id: int, special_token_policy: SpecialTokenPolicy = SpecialTokenPolicy.IGNORE
) -> bytes:
    r"""Convert a token ID to its byte representation.

    Args:
        token_id: The token ID to convert.
        special_token_policy: Policy for handling special tokens:
            - IGNORE: Return empty bytes for special tokens
            - KEEP: Return UTF-8 encoded special token string
            - RAISE: Raise ValueError if token is special

    Returns:
        The byte representation of the token. For regular tokens, returns the
        original byte sequence from the vocabulary.

    Raises:
        ValueError: If `special_token_policy` is RAISE and `token_id` is a special token,
            or if `special_token_policy` is invalid.
    """
    if token_id < self.num_special_tokens:
        if special_token_policy == SpecialTokenPolicy.KEEP:
            return self._all_special_tokens[token_id]["token_str"].encode("utf-8")
        elif special_token_policy == SpecialTokenPolicy.RAISE:
            raise ValueError(f"{token_id} is a special token")
        elif special_token_policy == SpecialTokenPolicy.IGNORE:
            return b""
        else:
            raise ValueError(f"Unknown special token policy {special_token_policy}")

    return self._model.decode_single_token_bytes(token_id - self.num_special_tokens)

id_to_piece(token_id)

Convert a token ID to its string representation.

Parameters:

Name Type Description Default
token_id int

The token ID to convert.

required

Returns:

Type Description
str

The string representation of the token. Special tokens are decoded as their

str

token string; regular tokens are decoded using the underlying tiktoken model.

Source code in src/mistral_common/tokens/tokenizers/tekken.py
def id_to_piece(self, token_id: int) -> str:
    r"""Convert a token ID to its string representation.

    Args:
        token_id: The token ID to convert.

    Returns:
        The string representation of the token. Special tokens are decoded as their
        token string; regular tokens are decoded using the underlying tiktoken model.
    """
    return self.decode([token_id], special_token_policy=SpecialTokenPolicy.KEEP)

is_byte(token_id)

Check if a token ID represents a single byte.

Parameters:

Name Type Description Default
token_id int

The token ID to check.

required

Returns:

Type Description
bool

True if the token (after subtracting special token offset) is in the

bool

range [0, 255], meaning it represents a single byte.

Source code in src/mistral_common/tokens/tokenizers/tekken.py
def is_byte(self, token_id: int) -> bool:
    r"""Check if a token ID represents a single byte.

    Args:
        token_id: The token ID to check.

    Returns:
        `True` if the token (after subtracting special token offset) is in the
        range [0, 255], meaning it represents a single byte.
    """
    return 0 <= token_id - self.num_special_tokens < 256

is_special(token)

Check if a token is a special token.

Parameters:

Name Type Description Default
token int | integer | str

Token ID (int or numpy integer) or token string to check.

required

Returns:

Type Description
bool

True if the token is a special token, False otherwise.

Raises:

Type Description
TypeError

If token is not an int, numpy integer, or str.

Source code in src/mistral_common/tokens/tokenizers/tekken.py
def is_special(self, token: int | np.integer | str) -> bool:
    r"""Check if a token is a special token.

    Args:
        token: Token ID (int or numpy integer) or token string to check.

    Returns:
        `True` if the token is a special token, `False` otherwise.

    Raises:
        TypeError: If token is not an int, numpy integer, or str.
    """
    if isinstance(token, (int, np.integer)):
        return token in self._special_token_ids
    elif isinstance(token, str):
        return token in self._special_tokens_reverse_vocab
    else:
        raise TypeError(f"Expected int or str, got {type(token).__name__}")

vocab()

Get all tokens in the vocabulary as strings.

Note

Tokens with decoding errors are collapsed into the "<?>" string. This may result in len(set(vocab)) != len(vocab). Use with caution.

Returns:

Type Description
list[str]

List of all tokens in the vocabulary as strings, in token ID order.

Source code in src/mistral_common/tokens/tokenizers/tekken.py
def vocab(self) -> list[str]:
    r"""Get all tokens in the vocabulary as strings.

    Note:
        Tokens with decoding errors are collapsed into the "<?>" string. This may
        result in len(set(vocab)) != len(vocab). Use with caution.

    Returns:
        List of all tokens in the vocabulary as strings, in token ID order.
    """
    # when returning self._vocab this will collapse
    # all tokens for which we have a decoding error into
    # the <?> string. This is bad and results in things
    # like len(set(vocab)) != len(vocab))
    # be careful when using self._vocab
    return self._vocab

TokenInfo

Bases: TypedDict

Token information in the JSON file.

Attributes:

Name Type Description
rank int

The integer rank/index of this token in the vocabulary.

token_bytes str

The token's byte representation, base64 encoded.

token_str str | None

The token's string representation, or None if not applicable.

is_tekken(path)

Check if the given path is a tekken tokenizer file.

Source code in src/mistral_common/tokens/tokenizers/tekken.py
def is_tekken(path: str | Path) -> bool:
    r"""Check if the given path is a tekken tokenizer file."""
    if isinstance(path, str):
        path = Path(path)
    return path.is_file() and "tekken" in path.name and path.suffix == ".json"

is_tekkenizer(tokenizer)

Check if a tokenizer is a Tekkenizer.

Parameters:

Name Type Description Default
tokenizer Tokenizer

The tokenizer to check.

required

Returns:

Type Description
TypeGuard[Tekkenizer]

True if the tokenizer is an instance of Tekkenizer, False otherwise.

Source code in src/mistral_common/tokens/tokenizers/tekken.py
def is_tekkenizer(tokenizer: Tokenizer) -> TypeGuard[Tekkenizer]:
    r"""Check if a tokenizer is a Tekkenizer.

    Args:
        tokenizer: The tokenizer to check.

    Returns:
        `True` if the tokenizer is an instance of Tekkenizer, `False` otherwise.
    """
    return isinstance(tokenizer, Tekkenizer)