"""Tokenizer used for the Qwen4 chat encoding protocol.""" from __future__ import annotations import logging import os from pathlib import Path from shutil import copyfile from typing import Any, Literal, cast import tiktoken from tiktoken.load import load_tiktoken_bpe from tokenizers import AddedToken from transformers.convert_slow_tokenizer import bytes_to_unicode from transformers.tokenization_utils import PreTrainedTokenizer from .encoding_qwen4 import Qwen4ChatEncoder logger = logging.getLogger(__name__) VOCAB_FILES_NAMES = {"vocab_file": "tiktoken.model"} class Qwen4Tokenizer(PreTrainedTokenizer): """Qwen3.8 BPE plus Qwen4's Python-rendered message encoding protocol.""" vocab_files_names = VOCAB_FILES_NAMES model_input_names = ("input_ids", "attention_mask") # 248044 base tokens + 276 special/reserved slots = config vocab_size. num_reserved_special_tokens = 276 pat_str = ( r"(?i:'s|'t|'re|'ve|'m|'ll|'d)" r"|[^\r\n\p{L}\p{N}]?[\p{L}\p{M}]+" r"|\p{N}" r"| ?[^\s\p{L}\p{M}\p{N}]+[\r\n]*" r"|\s*[\r\n]+" r"|\s+(?!\S)" r"|\s+" ) def __init__( self, vocab_file: str, bos_token: str | AddedToken | None = None, eos_token: str | AddedToken | None = "<|im_end|>", unk_token: str | AddedToken | None = None, pad_token: str | AddedToken | None = "<|endoftext|>", additional_special_tokens: list[str] | None = None, added_tokens_decoder: dict | None = None, **kwargs, ): if not os.path.isfile(vocab_file): raise ValueError(f"missing vocabulary file: {vocab_file}") known_specials: dict[int, str] = {} for token_id, token in (added_tokens_decoder or {}).items(): content = token.content if hasattr(token, "content") else str(token) known_specials[int(token_id)] = content self.vocab_file = vocab_file mergeable_ranks = load_tiktoken_bpe(vocab_file) self.num_base_tokens = len(mergeable_ranks) first_special = self.num_base_tokens final_vocab_size = first_special + self.num_reserved_special_tokens self.special_tokens: dict[str, int] = { known_specials.get(token_id, f"<|reserved_token_{token_id}|>"): token_id for token_id in range(first_special, final_vocab_size) } self.model = tiktoken.Encoding( name=Path(vocab_file).name, pat_str=self.pat_str, mergeable_ranks=mergeable_ranks, special_tokens=self.special_tokens, ) self.n_words = self.model.n_vocab if self.n_words != 248320: # hardcoded raise ValueError(f"unexpected Qwen4 vocabulary size: {self.n_words}") self.bos_id = self.special_tokens.get(str(bos_token)) if bos_token is not None else None self.eos_id = self.special_tokens.get(str(eos_token)) if eos_token is not None else None self.pad_id = self.special_tokens.get(str(pad_token)) if pad_token is not None else None self.unk_id = self.special_tokens.get(str(unk_token)) if unk_token is not None else None self.byte_encoder = bytes_to_unicode() self.byte_decoder = {value: key for key, value in self.byte_encoder.items()} self.decoder: dict[int, str] = {} for token_id in range(self.n_words): raw = self.model.decode_single_token_bytes(token_id) self.decoder[token_id] = "".join(self.byte_encoder[byte] for byte in raw) self.encoder = {token: token_id for token_id, token in self.decoder.items()} super().__init__( bos_token=bos_token, eos_token=eos_token, unk_token=unk_token, pad_token=pad_token, additional_special_tokens=additional_special_tokens, added_tokens_decoder=added_tokens_decoder, **kwargs, ) self.all_special_ids_set = set(self.all_special_ids) def init_xgrammar(self) -> tuple[Any, list[int]]: """Build XGrammar's TokenizerInfo straight from the tiktoken ranks. SGLang's ``XGrammarGrammarBackend`` calls this hook when the tokenizer defines it, and falls back to ``TokenizerInfo.from_huggingface`` otherwise. That fallback is wrong for us: ``get_vocab`` deliberately returns the GPT-2 byte-escaped surface forms (``byte_encoder``, needed for ``PreTrainedTokenizer`` compatibility), so XGrammar reads ``0xA1`` as the two-character string ``"\u00c2\u00a1"`` and re-encodes it to ``b"\xc2\xa1"``. It silently mis-builds every grammar mask; the model then samples a token the grammar rejects and ``accept_token`` raises mid-generation. Handing XGrammar the raw tiktoken byte strings avoids the round trip. Mirrors ``sglang/srt/tokenizer/tiktoken_tokenizer.py``. """ from xgrammar import TokenizerInfo token_items = sorted( {**self.model._mergeable_ranks, **self.model._special_tokens}.items(), key=lambda item: item[1], ) token_ids = [token_id for _, token_id in token_items] if token_ids != list(range(self.n_words)): raise ValueError("Qwen4 vocabulary token IDs must be contiguous") encoded_vocab = [token for token, _ in token_items] # XGrammar's raw-vocab convention reads a leading b"\x00" as "this is one of # my own special tokens", so the byte token b"\x00" (id 188) # lands in ``special_token_ids`` and gets masked out. Leave it that way. An # earlier revision renamed the slot to a placeholder string to keep # ``special_token_ids`` empty, but a placeholder is ordinary *text*: measured # against {"type": "string"} after the opening quote, the mask then allowed # id 188 and ``accept_token(188)`` succeeded, so the grammar believed it had # emitted text while the output carried a bare NUL and JSON parsing failed. # Masking the token only costs us NUL bytes inside grammar-constrained output. nul_prefixed = { token_id for token, token_id in token_items if isinstance(token, bytes) and token.startswith(b"\x00") } override_stop_tokens = list( dict.fromkeys( token_id for token_id in (self.pad_token_id, self.eos_token_id) if token_id is not None ) ) tokenizer_info = TokenizerInfo( encoded_vocab, stop_token_ids=override_stop_tokens ) if tokenizer_info.vocab_size != self.n_words: raise ValueError( f"XGrammar vocabulary size mismatch: {tokenizer_info.vocab_size} " f"!= {self.n_words}" ) # Only the b"\x00"-prefixed byte tokens may be reclassified as XGrammar # specials; anything else means XGrammar reinterpreted a token of ours, which # is the silent mask corruption this hook exists to prevent. unexpected = sorted(set(tokenizer_info.special_token_ids) - nul_prefixed) if unexpected: raise ValueError(f"Unexpected XGrammar special token IDs: {unexpected}") return tokenizer_info, override_stop_tokens def _encode_text_piece(self, text: str, *, allow_special: bool) -> list[int]: if allow_special: return self.model.encode(text, allowed_special="all") else: return self.model.encode(text, disallowed_special=()) def tokenize_segment(self, text: str, *, allow_special: bool = False) -> list[int]: if not isinstance(text, str): raise TypeError(f"text must be str, got {type(text).__name__}") return self._encode_text_piece(text, allow_special=allow_special) def encode(self, text: str, allow_special_tokens: bool = True, **kwargs) -> list[int]: if not kwargs: return self._encode_text_piece(text, allow_special=allow_special_tokens) if allow_special_tokens: return super().encode(text, **kwargs) # Encode literal text first; HF then handles padding, truncation and tensors. ids = self._encode_text_piece(text, allow_special=False) text_pair = kwargs.pop("text_pair", None) pair_ids = None if text_pair is not None: pair_ids = self._encode_text_piece(text_pair, allow_special=False) kwargs.setdefault("truncation", None) # Match HF encode's default. return self.prepare_for_model( ids, pair_ids=pair_ids, prepend_batch_axis=True, **kwargs )["input_ids"] def decode(self, token_ids: int | list[int], **kwargs) -> str: if kwargs: return super().decode(token_ids, **kwargs) values = [token_ids] if isinstance(token_ids, int) else token_ids return self.model.decode(cast(list[int], values)) @property def vocab_size(self) -> int: return self.n_words def get_vocab(self) -> dict[str, int]: return dict(self.encoder) def _tokenize(self, text: str, **kwargs) -> list[str]: return [self.decoder[token_id] for token_id in self._encode_text_piece(text, allow_special=True)] def _convert_token_to_id(self, token: str) -> int | None: return self.encoder.get(token, self.unk_id) def _convert_id_to_token(self, index: int) -> str | None: return self.decoder.get(index) def convert_tokens_to_string(self, tokens: list[str]) -> str: text = "".join(tokens) return bytearray(self.byte_decoder[character] for character in text).decode("utf-8", "replace") @staticmethod def clean_up_tokenization(out_string: str) -> str: return out_string def save_vocabulary( self, save_directory: str, filename_prefix: str | None = None, ) -> tuple[str]: if not os.path.isdir(save_directory): raise ValueError(f"vocabulary path must be a directory: {save_directory}") filename = (f"{filename_prefix}-" if filename_prefix else "") + "tiktoken.model" destination = os.path.join(save_directory, filename) if os.path.abspath(self.vocab_file) != os.path.abspath(destination): copyfile(self.vocab_file, destination) return (destination,) def _encode_chat_segments(self, segments): token_ids: list[int] = [] for segment in segments: if segment.text: token_ids.extend( self.tokenize_segment(segment.text, allow_special=segment.allow_special) ) return token_ids @staticmethod def _is_batched_conversation(conversation: Any) -> bool: return bool( isinstance(conversation, (list, tuple)) and conversation and isinstance(conversation[0], (list, tuple)) ) @staticmethod def _truncate(ids: list[int], truncation: bool, max_length: int | None) -> list[int]: return ids[:max_length] if truncation and max_length is not None else ids def _format_chat_token_output( self, encoded_inputs: list[list[int]], *, is_batched: bool, padding=False, truncation: bool = False, max_length: int | None = None, return_tensors=None, return_dict: bool = False, ): encoded_inputs = [ self._truncate(ids, truncation=truncation, max_length=max_length) for ids in encoded_inputs ] needs_batch = is_batched or bool(padding) or return_tensors is not None or return_dict if needs_batch: features = [ {"input_ids": ids, "attention_mask": [1] * len(ids)} for ids in encoded_inputs ] batch = self.pad( features, padding=padding, max_length=max_length if padding else None, return_attention_mask=True, return_tensors=return_tensors, ) if return_dict: result = batch elif is_batched or return_tensors is not None: result = batch["input_ids"] else: result = batch["input_ids"][0] else: result = encoded_inputs[0] return result def apply_chat_template( self, conversation, tools: list[dict] | None = None, add_generation_prompt: bool = True, tokenize: bool = False, padding=False, truncation: bool = False, max_length: int | None = None, return_tensors=None, return_dict: bool = False, enable_thinking: bool | None = None, reasoning_effort: Literal["xhigh", "high", "low", "off"] | None = None, preserve_thinking: bool | None = True, **kwargs, ): """Render and tokenize a conversation.""" if kwargs: unknown = ", ".join(sorted(kwargs)) logger.warning("Ignoring unsupported apply_chat_template arguments: %s", unknown) is_batched = self._is_batched_conversation(conversation) conversations = list(conversation) if is_batched else [conversation] encoder = Qwen4ChatEncoder(self) segment_batches = [ encoder.encode( list(messages), tools=tools, add_generation_prompt=add_generation_prompt, enable_thinking=enable_thinking, reasoning_effort=reasoning_effort, preserve_thinking=preserve_thinking, ) for messages in conversations ] if not tokenize: # this is the not the expected way to use this tokenizer rendered = ["".join(segment.text for segment in segments) for segments in segment_batches] return rendered if is_batched else rendered[0] encoded_inputs = [self._encode_chat_segments(segments) for segments in segment_batches] return self._format_chat_token_output( encoded_inputs, is_batched=is_batched, padding=padding, truncation=truncation, max_length=max_length, return_tensors=return_tensors, return_dict=return_dict, )