Buckets:
Tokenizer
Tokenizer[[tokenizers.Tokenizer]]
- model (Model) --
The core algorithm that this
Tokenizershould be using. ATokenizerworks as a pipeline. It processes some raw text as input and outputs an Encoding.
The pipeline is structured as follows:
- The Normalizer normalizes the raw input text.
- The PreTokenizer splits the normalized text into word-level tokens.
- The Model tokenizes each word into subword tokens and maps them to IDs.
- The
PostProcessorapplies any final transformations (e.g., adding special tokens like[CLS]and[SEP]).
Example:
>>> from tokenizers import Tokenizer
>>> from tokenizers.models import BPE
>>> from tokenizers.normalizers import Lowercase
>>> from tokenizers.pre_tokenizers import Whitespace
>>> tokenizer = Tokenizer(BPE(unk_token="<unk>"))
>>> tokenizer.normalizer = Lowercase()
>>> tokenizer.pre_tokenizer = Whitespace()
>>> # Load a pre-built tokenizer from HuggingFace Hub
>>> tokenizer = Tokenizer.from_pretrained("bert-base-uncased")
The optional Decoder in use by the Tokenizer
The Model in use by the Tokenizer
The optional Normalizer in use by the Tokenizer
(dict, optional)A dict with the current padding parameters if padding is enabled
Get the current padding parameters
Cannot be set, use enable_padding() instead
The optional PostProcessor in use by the Tokenizer
The optional PreTokenizer in use by the Tokenizer
(dict, optional)A dict with the current truncation parameters if truncation is enabled
Get the currently set truncation parameters
Cannot set, use enable_truncation() instead
- tokens (A
Listof AddedToken orstr) -- The list of special tokens we want to add to the vocabulary. Each token can either be a string or an instance of AddedToken for more customization.intThe number of tokens that were created in the vocabulary Add the given special tokens to the Tokenizer.
If these tokens are already part of the vocabulary, it just let the Tokenizer know about them. If they don't exist, the Tokenizer creates them, giving them a new id.
These special tokens will never be processed by the model (ie won't be split into multiple tokens), and they can be removed from the output when decoding.
- tokens (A
Listof AddedToken orstr) -- The list of tokens we want to add to the vocabulary. Each token can be either a string or an instance of AddedToken for more customization.intThe number of tokens that were created in the vocabulary Add the given tokens to the vocabulary
The given tokens are added only if they don't already exist in the vocabulary. Each token then gets a new attributed id.
sequences (
ListofList[int]) -- The batch of sequences we want to decodeskip_special_tokens (
bool, defaults toTrue) -- Whether the special tokens should be removed from the decoded stringsList[str]A list of decoded strings Decode a batch of ids back to their corresponding stringsequence (
~tokenizers.InputSequence) -- The main input sequence we want to encode. This sequence can be either raw text or pre-tokenized, according to theis_pretokenizedargument:- If
is_pretokenized=False:TextInputSequence - If
is_pretokenized=True:PreTokenizedInputSequence()
- If
pair (
~tokenizers.InputSequence, optional) -- An optional input sequence. The expected format is the same that forsequence.is_pretokenized (
bool, defaults toFalse) -- Whether the input is already pre-tokenizedadd_special_tokens (
bool, defaults toTrue) -- Whether to add the special tokensEncodingThe encoded result
Asynchronously encode the given input with character offsets.
This is an async version of encode that can be awaited in async Python code.
Example:
Here are some examples of the inputs that are accepted:
await async_encode("A single sequence")
input (A
List/``Tupleof~tokenizers.EncodeInput) -- A list of single sequences or pair sequences to encode. Each sequence can be either raw text or pre-tokenized, according to theis_pretokenized` argument:- If
is_pretokenized=False:TextEncodeInput() - If
is_pretokenized=True:PreTokenizedEncodeInput()
- If
is_pretokenized (
bool, defaults toFalse) -- Whether the input is already pre-tokenizedadd_special_tokens (
bool, defaults toTrue) -- Whether to add the special tokensAListof [`~tokenizers.Encoding``]The encoded batch
Asynchronously encode the given batch of inputs with character offsets.
This is an async version of encode_batch that can be awaited in async Python code.
Example:
Here are some examples of the inputs that are accepted:
await async_encode_batch([
"A single sequence",
("A tuple with a sequence", "And its pair"),
[ "A", "pre", "tokenized", "sequence" ],
([ "A", "pre", "tokenized", "sequence" ], "And its pair")
])
input (A
List/``Tupleof~tokenizers.EncodeInput) -- A list of single sequences or pair sequences to encode. Each sequence can be either raw text or pre-tokenized, according to theis_pretokenized` argument:- If
is_pretokenized=False:TextEncodeInput() - If
is_pretokenized=True:PreTokenizedEncodeInput()
- If
is_pretokenized (
bool, defaults toFalse) -- Whether the input is already pre-tokenizedadd_special_tokens (
bool, defaults toTrue) -- Whether to add the special tokensAListof [`~tokenizers.Encoding``]The encoded batch
Asynchronously encode the given batch of inputs without tracking character offsets.
This is an async version of encode_batch_fast that can be awaited in async Python code.
Example:
Here are some examples of the inputs that are accepted:
await async_encode_batch_fast([
"A single sequence",
("A tuple with a sequence", "And its pair"),
[ "A", "pre", "tokenized", "sequence" ],
([ "A", "pre", "tokenized", "sequence" ], "And its pair")
])
ids (A
List/Tupleofint) -- The list of ids that we want to decodeskip_special_tokens (
bool, defaults toTrue) -- Whether the special tokens should be removed from the decoded stringstrThe decoded string Decode the given list of ids back to a string
This is used to decode anything coming back from a Language Model
sequences (
ListofList[int]) -- The batch of sequences we want to decodeskip_special_tokens (
bool, defaults toTrue) -- Whether the special tokens should be removed from the decoded stringsList[str]A list of decoded strings Decode a batch of ids back to their corresponding stringdirection (
str, optional, defaults toright) -- The direction in which to pad. Can be eitherrightorleftpad_to_multiple_of (
int, optional) -- If specified, the padding length should always snap to the next multiple of the given value. For example if we were going to pad witha length of 250 butpad_to_multiple_of=8then we will pad to 256.pad_id (
int, defaults to 0) -- The id to be used when paddingpad_type_id (
int, defaults to 0) -- The type id to be used when paddingpad_token (
str, defaults to[PAD]) -- The pad token to be used when paddinglength (
int, optional) -- If specified, the length at which to pad. If not specified we pad using the size of the longest sequence in a batch. Enable the paddingmax_length (
int) -- The max length at which to truncatestride (
int, optional) -- The length of the previous first sequence to be included in the overflowing sequencestrategy (
str, optional, defaults tolongest_first) -- The strategy used to truncation. Can be one oflongest_first,only_firstoronly_second.direction (
str, defaults toright) -- Truncate direction Enable truncationsequence (
~tokenizers.InputSequence) -- The main input sequence we want to encode. This sequence can be either raw text or pre-tokenized, according to theis_pretokenizedargument:- If
is_pretokenized=False:TextInputSequence - If
is_pretokenized=True:PreTokenizedInputSequence()
- If
pair (
~tokenizers.InputSequence, optional) -- An optional input sequence. The expected format is the same that forsequence.is_pretokenized (
bool, defaults toFalse) -- Whether the input is already pre-tokenizedadd_special_tokens (
bool, defaults toTrue) -- Whether to add the special tokensEncodingThe encoded result
Encode the given sequence and pair. This method can process raw text sequences as well as already pre-tokenized sequences.
Example:
Here are some examples of the inputs that are accepted:
encode("A single sequence")*
encode("A sequence", "And its pair")*
encode([ "A", "pre", "tokenized", "sequence" ], is_pretokenized=True)`
encode(
[ "A", "pre", "tokenized", "sequence" ], [ "And", "its", "pair" ],
is_pretokenized=True
)
input (A
List/``Tupleof~tokenizers.EncodeInput) -- A list of single sequences or pair sequences to encode. Each sequence can be either raw text or pre-tokenized, according to theis_pretokenized` argument:- If
is_pretokenized=False:TextEncodeInput() - If
is_pretokenized=True:PreTokenizedEncodeInput()
- If
is_pretokenized (
bool, defaults toFalse) -- Whether the input is already pre-tokenizedadd_special_tokens (
bool, defaults toTrue) -- Whether to add the special tokensAListof [`~tokenizers.Encoding``]The encoded batch
Encode the given batch of inputs. This method accept both raw text sequences as well as already pre-tokenized sequences. The reason we use PySequence is because it allows type checking with zero-cost (according to PyO3) as we don't have to convert to check.
Example:
Here are some examples of the inputs that are accepted:
encode_batch([
"A single sequence",
("A tuple with a sequence", "And its pair"),
[ "A", "pre", "tokenized", "sequence" ],
([ "A", "pre", "tokenized", "sequence" ], "And its pair")
])
input (A
List/``Tupleof~tokenizers.EncodeInput) -- A list of single sequences or pair sequences to encode. Each sequence can be either raw text or pre-tokenized, according to theis_pretokenized` argument:- If
is_pretokenized=False:TextEncodeInput() - If
is_pretokenized=True:PreTokenizedEncodeInput()
- If
is_pretokenized (
bool, defaults toFalse) -- Whether the input is already pre-tokenizedadd_special_tokens (
bool, defaults toTrue) -- Whether to add the special tokensAListof [`~tokenizers.Encoding``]The encoded batch
Encode the given batch of inputs. This method is faster than encode_batch because it doesn't keep track of offsets, they will be all zeros.
Example:
Here are some examples of the inputs that are accepted:
encode_batch_fast([
"A single sequence",
("A tuple with a sequence", "And its pair"),
[ "A", "pre", "tokenized", "sequence" ],
([ "A", "pre", "tokenized", "sequence" ], "And its pair")
])
buffer (
bytes) -- A buffer containing a previously serialized TokenizerTokenizerThe new tokenizer Instantiate a new Tokenizer from the given buffer.path (
str) -- A path to a local JSON file representing a previously serialized TokenizerTokenizerThe new tokenizer Instantiate a new Tokenizer from the file at the given path.identifier (
str) -- The identifier of a Model on the Hugging Face Hub, that contains a tokenizer.json filerevision (
str, defaults to main) -- A branch or commit idtoken (
str, optional, defaults to None) -- An optional auth token used to access private repositories on the Hugging Face HubTokenizerThe new tokenizer Instantiate a new Tokenizer from an existing file on the Hugging Face Hub.json (
str) -- A valid JSON string representing a previously serialized TokenizerTokenizerThe new tokenizer Instantiate a new Tokenizer from the given JSON string.
Dict[int, AddedToken]The vocabulary
Get the underlying vocabulary
with_added_tokens (
bool, defaults toTrue) -- Whether to include the added tokensDict[str, int]The vocabulary Get the underlying vocabularywith_added_tokens (
bool, defaults toTrue) -- Whether to include the added tokensintThe size of the vocabulary Get the size of the underlying vocabularyid (
int) -- The id to convertOptional[str]An optional token,Noneif out of vocabulary Convert the given id to its corresponding token if it exists
Disable padding
Disable truncation
Return the number of special tokens that would be added for single/pair sentences. :param is_pair: Boolean indicating if the input would be a single sentence or a pair :return:
encoding (Encoding) -- The Encoding corresponding to the main sequence.
pair (Encoding, optional) -- An optional Encoding corresponding to the pair sequence.
add_special_tokens (
bool) -- Whether to add the special tokensEncodingThe final post-processed encoding Apply all the post-processing steps to the given encodings.
The various steps are:
- Truncate according to the set truncation params (provided with
enable_truncation()) - Apply the
PostProcessor - Pad according to the set padding params (provided with
enable_padding())
path (
str) -- A path to a file in which to save the serialized tokenizer.pretty (
bool, defaults toTrue) -- Whether the JSON file should be pretty formatted. Save the Tokenizer to the file at the given path.pretty (
bool, defaults toFalse) -- Whether the JSON string should be pretty formatted.strA string representing the serialized Tokenizer Gets a serialized string representing this Tokenizer.token (
str) -- The token to convertOptional[int]An optional id,Noneif out of vocabulary Convert the given token to its corresponding id if it existsfiles (
List[str]) -- A list of path to the files that we should use for trainingtrainer (
~tokenizers.trainers.Trainer, optional) -- An optional trainer that should be used to train our Model Train the Tokenizer using the given files.
Reads the files line by line, while keeping all the whitespace, even new lines.
If you want to train from data store in-memory, you can check
train_from_iterator()
iterator (
Iterator) -- Any iterator over strings or list of stringstrainer (
~tokenizers.trainers.Trainer, optional) -- An optional trainer that should be used to train our Modellength (
int, optional) -- The total number of sequences in the iterator. This is used to provide meaningful progress tracking Train the Tokenizer using the provided iterator.
You can provide anything that is a Python Iterator
- A list of sequences
List[str] - A generator that yields
strorList[str] - A Numpy array of strings
- ...
The Rust API Reference is available directly on the Docs.rs website.
The node API has not been documented yet.
Xet Storage Details
- Size:
- 17.6 kB
- Xet hash:
- ceb815208ed22631aa0f931f791dd0b56e4ef09b7f67ee00339e1f16815a15df
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.