Tokenizer
Tokenizer
PythonRustNode
Tokenizer
class tokenizers.Tokenizer
( model )
Parameters
model (Model) β The core algorithm that this
Tokenizer
should be using.
A Tokenizer
works as a pipeline. It processes some raw text as input and outputs an Encoding.
propertydecoder
The optional Decoder
in use by the Tokenizer
propertymodel
The Model in use by the Tokenizer
propertynormalizer
The optional Normalizer in use by the Tokenizer
propertypadding
Returns
(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
propertypost_processor
The optional PostProcessor
in use by the Tokenizer
propertypre_tokenizer
The optional PreTokenizer in use by the Tokenizer
propertytruncation
Returns
(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
add_special_tokens
( tokens ) β int
Parameters
tokens (A
List
of 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.
Returns
int
The 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.
add_tokens
( tokens ) β int
Parameters
tokens (A
List
of 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.
Returns
int
The 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.
decode
( idsskip_special_tokens = True ) β str
Parameters
ids (A
List/Tuple
ofint
) β The list of ids that we want to decodeskip_special_tokens (
bool
, defaults toTrue
) β Whether the special tokens should be removed from the decoded string
Returns
str
The decoded string
Decode the given list of ids back to a string
This is used to decode anything coming back from a Language Model
decode_batch
( sequencesskip_special_tokens = True ) β List[str]
Parameters
sequences (
List
ofList[int]
) β The batch of sequences we want to decodeskip_special_tokens (
bool
, defaults toTrue
) β Whether the special tokens should be removed from the decoded strings
Returns
List[str]
A list of decoded strings
Decode a batch of ids back to their corresponding string
enable_padding
( direction = 'right'pad_id = 0pad_type_id = 0pad_token = '[PAD]'length = Nonepad_to_multiple_of = None )
Parameters
direction (
str
, optional, defaults toright
) β The direction in which to pad. Can be eitherright
orleft
pad_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=8
then 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 padding
enable_truncation
( max_lengthstride = 0strategy = 'longest_first'direction = 'right' )
Parameters
max_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_first
oronly_second
.direction (
str
, defaults toright
) β Truncate direction
Enable truncation
encode
( sequencepair = Noneis_pretokenized = Falseadd_special_tokens = True ) β Encoding
Parameters
sequence (
~tokenizers.InputSequence
) β The main input sequence we want to encode. This sequence can be either raw text or pre-tokenized, according to theis_pretokenized
argument:If
is_pretokenized=False
:TextInputSequence
If
is_pretokenized=True
:PreTokenizedInputSequence()
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 tokens
Returns
The 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:
Copied
encode_batch
( inputis_pretokenized = Falseadd_special_tokens = True ) β A List
of [`~tokenizers.Encodingβ]
Parameters
input (A
List
/`Tuple
of~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()
is_pretokenized (
bool
, defaults toFalse
) β Whether the input is already pre-tokenizedadd_special_tokens (
bool
, defaults toTrue
) β Whether to add the special tokens
Returns
A List
of [`~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.
Example:
Here are some examples of the inputs that are accepted:
Copied
from_buffer
( buffer ) β Tokenizer
Parameters
buffer (
bytes
) β A buffer containing a previously serialized Tokenizer
Returns
The new tokenizer
Instantiate a new Tokenizer from the given buffer.
from_file
( path ) β Tokenizer
Parameters
path (
str
) β A path to a local JSON file representing a previously serialized Tokenizer
Returns
The new tokenizer
Instantiate a new Tokenizer from the file at the given path.
from_pretrained
( identifierrevision = 'main'auth_token = None ) β Tokenizer
Parameters
identifier (
str
) β The identifier of a Model on the BOINC AI Hub, that contains a tokenizer.json filerevision (
str
, defaults to main) β A branch or commit idauth_token (
str
, optional, defaults to None) β An optional auth token used to access private repositories on the BOINC AI Hub
Returns
The new tokenizer
Instantiate a new Tokenizer from an existing file on the BOINC AI Hub.
from_str
( json ) β Tokenizer
Parameters
json (
str
) β A valid JSON string representing a previously serialized Tokenizer
Returns
The new tokenizer
Instantiate a new Tokenizer from the given JSON string.
get_vocab
( with_added_tokens = True ) β Dict[str, int]
Parameters
with_added_tokens (
bool
, defaults toTrue
) β Whether to include the added tokens
Returns
Dict[str, int]
The vocabulary
Get the underlying vocabulary
get_vocab_size
( with_added_tokens = True ) β int
Parameters
with_added_tokens (
bool
, defaults toTrue
) β Whether to include the added tokens
Returns
int
The size of the vocabulary
Get the size of the underlying vocabulary
id_to_token
( id ) β Optional[str]
Parameters
id (
int
) β The id to convert
Returns
Optional[str]
An optional token, None
if out of vocabulary
Convert the given id to its corresponding token if it exists
no_padding
( )
Disable padding
no_truncation
( )
Disable truncation
num_special_tokens_to_add
( is_pair )
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:
post_process
( encodingpair = Noneadd_special_tokens = True ) β Encoding
Parameters
add_special_tokens (
bool
) β Whether to add the special tokens
Returns
The 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()
)
save
( pathpretty = True )
Parameters
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.
to_str
( pretty = False ) β str
Parameters
pretty (
bool
, defaults toFalse
) β Whether the JSON string should be pretty formatted.
Returns
str
A string representing the serialized Tokenizer
Gets a serialized string representing this Tokenizer.
token_to_id
( token ) β Optional[int]
Parameters
token (
str
) β The token to convert
Returns
Optional[int]
An optional id, None
if out of vocabulary
Convert the given token to its corresponding id if it exists
train
( filestrainer = None )
Parameters
files (
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()
train_from_iterator
( iteratortrainer = Nonelength = None )
Parameters
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
str
orList[str]
A Numpy array of strings
β¦
Last updated