Overview
The Qwen tokenizer converts text to token IDs for model input and decodes token IDs back to text. It includes special tokens for the ChatML format and provides various encoding/decoding options.Loading Tokenizer
Encoding Text
encode() Method
Convert text to token IDs:Parameters
str
required
Input text to encode
bool
default:"True"
Whether to add special tokens (BOS/EOS)
int
default:"None"
Maximum sequence length (truncate if exceeded)
bool
default:"False"
Whether to truncate sequences exceeding max_length
str | bool
default:"False"
Padding strategy:
"max_length", "longest", or FalseReturns
list[int]
List of token IDs
Decoding Token IDs
decode() Method
Convert token IDs back to text:Parameters
list[int]
required
List of token IDs to decode
bool
default:"False"
Whether to remove special tokens from output
bool
default:"True"
Whether to clean up extra spaces
str
default:"replace"
How to handle decoding errors:
"ignore", "replace", or "strict"Returns
str
Decoded text string
Batch Encoding
Encode multiple texts at once:Parameters
str | list[str]
required
Single text or list of texts to encode
bool | str
default:"False"
Padding strategy:
Trueor"longest": Pad to longest sequence in batch"max_length": Pad to max_length parameterFalse: No padding
bool
default:"False"
Whether to truncate sequences exceeding max_length
int
default:"None"
Maximum sequence length
str
default:"None"
Return format:
"pt": PyTorch tensors"tf": TensorFlow tensors"np": NumPy arraysNone: Python lists
bool
default:"True"
Whether to return attention mask
Returns
torch.Tensor | list
Encoded token IDs
torch.Tensor | list
Attention mask (1 for real tokens, 0 for padding)