text stringlengths 1 1.02k | class_index int64 0 10.8k | source stringlengths 85 188 |
|---|---|---|
Returns:
[`~tokenization_utils_base.CharSpan`]: Span of characters in the original string, or None, if the token
(e.g. <s>, </s>) doesn't correspond to any chars in the origin string.
"""
if not self._encodings:
raise ValueError("token_to_chars() is not available whe... | 73 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
- `self.char_to_token(char_index)` if batch size is 1
- `self.char_to_token(batch_index, char_index)` if batch size is greater or equal to 1
This method is particularly suited when the input sequences are provided as pre-tokenized sequences (i.e. words
are defined by the user). In this case it ... | 73 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
Args:
batch_or_char_index (`int`):
Index of the sequence in the batch. If the batch only comprise one sequence, this can be the index of
the word in the sequence
char_index (`int`, *optional*):
If a batch index is provided in *batch_or_token_index*... | 73 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
if not self._encodings:
raise ValueError("char_to_token() is not available when using Python based tokenizers")
if char_index is not None:
batch_index = batch_or_char_index
else:
batch_index = 0
char_index = batch_or_char_index
return self._encodin... | 73 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
- `self.word_to_chars(word_index)` if batch size is 1
- `self.word_to_chars(batch_index, word_index)` if batch size is greater or equal to 1
Args:
batch_or_word_index (`int`):
Index of the sequence in the batch. If the batch only comprise one sequence, this can be the index ... | 73 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
- start: index of the first character associated to the token in the original string
- end: index of the character following the last character associated to the token in the original
string
"""
if not self._encodings:
raise ValueError("word_to_chars() is n... | 73 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
- `self.char_to_word(char_index)` if batch size is 1
- `self.char_to_word(batch_index, char_index)` if batch size is greater than 1
This method is particularly suited when the input sequences are provided as pre-tokenized sequences (i.e. words
are defined by the user). In this case it allows to... | 73 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
Args:
batch_or_char_index (`int`):
Index of the sequence in the batch. If the batch only comprise one sequence, this can be the index of
the character in the original string.
char_index (`int`, *optional*):
If a batch index is provided in *batch_or... | 73 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
if not self._encodings:
raise ValueError("char_to_word() is not available when using Python based tokenizers")
if char_index is not None:
batch_index = batch_or_char_index
else:
batch_index = 0
char_index = batch_or_char_index
return self._encoding... | 73 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
Args:
tensor_type (`str` or [`~utils.TensorType`], *optional*):
The type of tensors to use. If `str`, should be one of the values of the enum [`~utils.TensorType`]. If
`None`, no modification is done.
prepend_batch_axis (`int`, *optional*, defaults to `False`):
... | 73 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
as_tensor = tf.constant
is_tensor = tf.is_tensor
elif tensor_type == TensorType.PYTORCH:
if not is_torch_available():
raise ImportError("Unable to convert output to PyTorch tensors format, PyTorch is not installed.")
import torch
is_tensor = torch... | 73 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
elif tensor_type == TensorType.MLX:
if not is_mlx_available():
raise ImportError("Unable to convert output to MLX tensors format, MLX is not installed.")
import mlx.core as mx
as_tensor = mx.array
def is_tensor(obj):
return isinstance(obj... | 73 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
# Do the tensor conversion in batch
for key, value in self.items():
try:
if prepend_batch_axis:
value = [value]
if not is_tensor(value):
tensor = as_tensor(value)
# Removing this for now in favor of control... | 73 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
self[key] = tensor
except Exception as e:
if key == "overflowing_tokens":
raise ValueError(
"Unable to create tensor returning overflowing tokens of different lengths. "
"Please see if a fast version of this tokenizer is ava... | 73 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
def to(self, device: Union[str, "torch.device"], *, non_blocking: bool = False) -> "BatchEncoding":
"""
Send all values to device by calling `v.to(device, non_blocking=non_blocking)` (PyTorch only).
Args:
device (`str` or `torch.device`): The device to put the tensors on.
... | 73 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
# This check catches things like APEX blindly calling "to" on all inputs to a module
# Otherwise it passes the casts down and casts the LongTensor containing the token idxs
# into a HalfTensor
if isinstance(device, str) or is_torch_device(device) or isinstance(device, int):
self.data... | 73 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
class SpecialTokensMixin:
"""
A mixin derived by [`PreTrainedTokenizer`] and [`PreTrainedTokenizerFast`] to handle specific behaviors related to
special tokens. In particular, this class hold the attributes which can be used to directly access these special
tokens in a model-independent manner and allow... | 74 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
Args:
bos_token (`str` or `tokenizers.AddedToken`, *optional*):
A special token representing the beginning of a sentence.
eos_token (`str` or `tokenizers.AddedToken`, *optional*):
A special token representing the end of a sentence.
unk_token (`str` or `tokenizers.AddedTok... | 74 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
mask_token (`str` or `tokenizers.AddedToken`, *optional*):
A special token representing a masked token (used by masked-language modeling pretraining objectives, like
BERT).
additional_special_tokens (tuple or list of `str` or `tokenizers.AddedToken`, *optional*):
A tuple or a... | 74 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
SPECIAL_TOKENS_ATTRIBUTES = [
"bos_token",
"eos_token",
"unk_token",
"sep_token",
"pad_token",
"cls_token",
"mask_token",
"additional_special_tokens",
]
def __init__(self, verbose=False, **kwargs):
self._pad_token_type_id = 0
self.... | 74 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
for key, value in kwargs.items():
if value is None:
continue
if key in self.SPECIAL_TOKENS_ATTRIBUTES:
if key == "additional_special_tokens":
assert isinstance(value, (list, tuple)), f"Value {value} is not a list or tuple"
a... | 74 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
def sanitize_special_tokens(self) -> int:
"""
The `sanitize_special_tokens` is now deprecated kept for backward compatibility and will be removed in
transformers v5.
"""
logger.warning_once("The `sanitize_special_tokens` will be removed in transformers v5.")
return self.a... | 74 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
In order to do that, please use the [`~PreTrainedModel.resize_token_embeddings`] method.
Using `add_special_tokens` will ensure your special tokens can be used in several ways:
- Special tokens can be skipped when decoding using `skip_special_tokens = True`.
- Special tokens are carefully hand... | 74 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
Args:
special_tokens_dict (dictionary *str* to *str* or `tokenizers.AddedToken`):
Keys should be in the list of predefined special attributes: [`bos_token`, `eos_token`, `unk_token`,
`sep_token`, `pad_token`, `cls_token`, `mask_token`, `additional_special_tokens`]. | 74 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
Tokens are only added if they are not already in the vocabulary (tested by checking if the tokenizer
assign the index of the `unk_token` to them).
replace_additional_special_tokens (`bool`, *optional*,, defaults to `True`):
If `True`, the existing list of additional special t... | 74 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
Returns:
`int`: Number of tokens added to the vocabulary.
Examples:
```python
# Let's see how to add a new classification token to GPT-2
tokenizer = GPT2Tokenizer.from_pretrained("openai-community/gpt2")
model = GPT2Model.from_pretrained("openai-community/gpt2")
... | 74 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
if self.verbose:
logger.info(f"Assigning {value} to the {key} key of the tokenizer")
if key == "additional_special_tokens":
assert isinstance(value, (list, tuple)) and all(
isinstance(t, (str, AddedToken)) for t in value
), f"Tokens {value... | 74 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
to_add = []
for token in value:
if isinstance(token, str):
# for legacy purpose we default to stripping. `test_add_tokens_tokenizer` depends on this
token = AddedToken(token, rstrip=False, lstrip=False, normalized=False, special=True)
... | 74 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
else:
if not isinstance(value, (str, AddedToken)):
raise ValueError(f"Token {value} for key {key} should be a str or an AddedToken instance")
if isinstance(value, (str)):
# for legacy purpose we default to stripping. `False` depends on this
... | 74 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
def add_tokens(
self, new_tokens: Union[str, AddedToken, List[Union[str, AddedToken]]], special_tokens: bool = False
) -> int:
"""
Add a list of new tokens to the tokenizer class. If the new tokens are not in the vocabulary, they are added to
it with indices starting from length of t... | 74 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
Args:
new_tokens (`str`, `tokenizers.AddedToken` or a list of *str* or `tokenizers.AddedToken`):
Tokens are only added if they are not already in the vocabulary. `tokenizers.AddedToken` wraps a string
token to let you personalize its behavior: whether this token should only m... | 74 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
```python
# Let's see how to increase the vocabulary of Bert model and tokenizer
tokenizer = BertTokenizerFast.from_pretrained("google-bert/bert-base-uncased")
model = BertModel.from_pretrained("google-bert/bert-base-uncased")
num_added_toks = tokenizer.add_tokens(["new_tok1", "my_new-t... | 74 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
@property
def pad_token_type_id(self) -> int:
"""
`int`: Id of the padding token type in the vocabulary.
"""
return self._pad_token_type_id
def __setattr__(self, key, value):
key_without_id = key
key_is_special_id = key.endswith("_id") or key.endswith("_ids")
... | 74 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
if key != "additional_special_tokens" and not isinstance(value, (str, AddedToken)) and value is not None:
raise ValueError(f"Cannot set a non-string value as the {key}")
self._special_tokens_map[key] = value
else:
super().__setattr__(key, value)
def __getattr__(self,... | 74 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
if self.__dict__.get("_special_tokens_map", None) is not None and any(
name in self.__dict__["_special_tokens_map"] for name in [key, key_without_id]
):
_special_tokens_map = self.__dict__["_special_tokens_map"]
if not key_is_special_id:
if _special_tokens_map... | 74 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
@property
def special_tokens_map(self) -> Dict[str, Union[str, List[str]]]:
"""
`Dict[str, Union[str, List[str]]]`: A dictionary mapping special token class attributes (`cls_token`,
`unk_token`, etc.) to their values (`'<unk>'`, `'<cls>'`, etc.).
Convert potential tokens of `tokeniz... | 74 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
Don't convert tokens of `tokenizers.AddedToken` type to string so they can be used to control more finely how
special tokens are tokenized.
"""
set_attr = {}
for attr in self.SPECIAL_TOKENS_ATTRIBUTES:
attr_value = self._special_tokens_map[attr]
if attr_value:
... | 74 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
Don't convert tokens of `tokenizers.AddedToken` type to string so they can be used to control more finely how
special tokens are tokenized.
"""
all_tokens = []
seen = set()
for value in self.special_tokens_map_extended.values():
if isinstance(value, (list, tuple)):
... | 74 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
@property
def all_special_ids(self) -> List[int]:
"""
`List[int]`: List the ids of the special tokens(`'<unk>'`, `'<cls>'`, etc.) mapped to class attributes.
"""
all_toks = self.all_special_tokens
all_ids = self.convert_tokens_to_ids(all_toks)
return all_ids | 74 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
def _set_model_specific_special_tokens(self, special_tokens: List[str]):
"""
Adds new special tokens to the "SPECIAL_TOKENS_ATTRIBUTES" list which will be part
of "self.special_tokens" and saved as a special token in tokenizer's config.
This allows us to dynamically add new model-type sp... | 74 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
class PreTrainedTokenizerBase(SpecialTokensMixin, PushToHubMixin):
"""
Base class for [`PreTrainedTokenizer`] and [`PreTrainedTokenizerFast`].
Handles shared (mostly boiler plate) methods for those two classes.
"""
vocab_files_names: Dict[str, str] = {}
pretrained_vocab_files_map: Dict[str, Di... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
def __init__(self, **kwargs):
# inputs and kwargs for saving and re-loading (see ``from_pretrained`` and ``save_pretrained``)
self.init_inputs = ()
for key in kwargs:
if hasattr(self, key) and callable(getattr(self, key)):
raise AttributeError(f"{key} conflicts with t... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
# Padding and truncation side are right by default and overridden in subclasses. If specified in the kwargs, it
# is changed.
self.padding_side = kwargs.pop("padding_side", self.padding_side)
if self.padding_side not in ["right", "left"]:
raise ValueError(
f"Padding s... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
# By default, do not split special tokens for both fast and slow tokenizers
self.split_special_tokens = kwargs.pop("split_special_tokens", False)
self.deprecation_warnings = {} # Use to store when we have already noticed a deprecation warning (avoid overlogging).
self._in_target_context_manage... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
@property
def max_len_single_sentence(self) -> int:
"""
`int`: The maximum length of a sentence that can be fed to the model.
"""
return self.model_max_length - self.num_special_tokens_to_add(pair=False)
@property
def max_len_sentences_pair(self) -> int:
"""
... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
@max_len_single_sentence.setter
def max_len_single_sentence(self, value) -> int:
# For backward compatibility, allow to try to setup 'max_len_single_sentence'.
if value == self.model_max_length - self.num_special_tokens_to_add(pair=False) and self.verbose:
if not self.deprecation_warning... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
@max_len_sentences_pair.setter
def max_len_sentences_pair(self, value) -> int:
# For backward compatibility, allow to try to setup 'max_len_sentences_pair'.
if value == self.model_max_length - self.num_special_tokens_to_add(pair=True) and self.verbose:
if not self.deprecation_warnings.ge... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
def __repr__(self) -> str:
added_tokens_decoder_rep = "\n\t".join([f"{k}: {v.__repr__()}," for k, v in self.added_tokens_decoder.items()])
return (
f"{self.__class__.__name__}(name_or_path='{self.name_or_path}',"
f" vocab_size={self.vocab_size}, model_max_length={self.model_max_l... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
Returns:
`Dict[str, int]`: The vocabulary.
"""
raise NotImplementedError() | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
def apply_chat_template(
self,
conversation: Union[List[Dict[str, str]], List[List[Dict[str, str]]]],
tools: Optional[List[Union[Dict, Callable]]] = None,
documents: Optional[List[Dict[str, str]]] = None,
chat_template: Optional[str] = None,
add_generation_prompt: bool = ... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
ids. This method is intended for use with chat models, and will read the tokenizer's chat_template attribute to
determine the format and control tokens to use when converting. | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
Args:
conversation (Union[List[Dict[str, str]], List[List[Dict[str, str]]]]): A list of dicts
with "role" and "content" keys, representing the chat history so far.
tools (`List[Dict]`, *optional*):
A list of tools (callable functions) that will be accessible to th... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
(retrieval-augmented generation). If the template does not support RAG, this argument will have no
effect. We recommend that each document should be a dict containing "title" and "text" keys. Please
see the RAG section of the [chat templating guide](https://huggingface.co/docs/transforme... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
Note that this argument will be passed to the chat template, and so it must be supported in the
template for this argument to have any effect.
continue_final_message (bool, *optional*):
If this is set, the chat will be formatted so that the final
message in th... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
Whether to truncate sequences at the maximum length. Has no effect if tokenize is `False`.
max_length (`int`, *optional*):
Maximum length (in tokens) to use for padding or truncation. Has no effect if tokenize is `False`. If
not specified, the tokenizer's `max_length` attribu... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
tokenizer_kwargs (`Dict[str: Any]`, *optional*): Additional kwargs to pass to the tokenizer.
return_assistant_tokens_mask (`bool`, defaults to `False`):
Whether to return a mask of the assistant generated tokens. For tokens generated by the assistant,
the mask will contain 1.... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
Returns:
`Union[List[int], Dict]`: A list of token ids representing the tokenized chat so far, including control tokens. This
output is ready to pass to the model, either directly or via methods like `generate()`. If `return_dict` is
set, will return a dict of tokenizer outputs inste... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
if return_assistant_tokens_mask and not re.search(r"\{\%-?\s*generation\s*-?\%\}", chat_template):
logger.warning_once(
"return_assistant_tokens_mask==True but chat template does not contain `{% generation %}` keyword."
)
# Compilation function uses a cache to avoid reco... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
if continue_final_message:
if add_generation_prompt:
raise ValueError(
"continue_final_message and add_generation_prompt are not compatible. Use continue_final_message when you want the model to continue the final message, and add_generation_prompt when you want to add a ... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
# We accept either JSON schemas or functions for tools. If we get functions, we convert them to schemas
if tools is not None:
tool_schemas = []
for tool in tools:
if isinstance(tool, dict):
tool_schemas.append(tool)
elif isfunction(tool... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
rendered = []
all_generation_indices = []
template_kwargs = {**self.special_tokens_map, **kwargs} # kwargs overwrite special tokens if both are present
for chat in conversations:
if hasattr(chat, "messages"):
# Indicates it's a Conversation object
cha... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
documents=documents,
add_generation_prompt=add_generation_prompt,
**template_kwargs,
)
if continue_final_message:
final_message = chat[-1]["content"]
if isinstance(final_message, (list, tuple)):
final... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
if not is_batched:
rendered = rendered[0] | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
if tokenize:
out = self(
rendered,
padding=padding,
truncation=truncation,
max_length=max_length,
add_special_tokens=False,
return_tensors=return_tensors,
**tokenizer_kwargs,
)
... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
if start_token is None:
# start_token is out of bounds maybe due to truncation.
break
for token_id in range(start_token, end_token + 1 if end_token else len(input_ids[i])):
current_mask[token_id] ... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
def get_chat_template(self, chat_template: Optional[str] = None, tools: Optional[List[Dict]] = None) -> str:
"""
Retrieve the chat template string used for tokenizing chat messages. This template is used
internally by the `apply_chat_template` method and can also be used externally to retrieve t... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
Args:
chat_template (`str`, *optional*):
A Jinja template or the name of a template to use for this conversion.
It is usually not necessary to pass anything to this argument,
as the model's template will be used by default.
tools (`List[Dict]`, *op... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
Returns:
`str`: The chat template string.
"""
# First, handle the cases when the model has a dict of multiple templates
if isinstance(self.chat_template, dict):
template_dict = self.chat_template
if chat_template is not None and chat_template in template_dict:... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
"template or the name of the template you wish to use to the `chat_template` argument. Available "
f"template names are {sorted(template_dict.keys())}."
) | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
elif chat_template is None:
# These are the cases when the model has a single template
# priority: `chat_template` argument > `tokenizer.chat_template`
if self.chat_template is not None:
chat_template = self.chat_template
else:
raise ValueE... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
@classmethod
def from_pretrained(
cls,
pretrained_model_name_or_path: Union[str, os.PathLike],
*init_inputs,
cache_dir: Optional[Union[str, os.PathLike]] = None,
force_download: bool = False,
local_files_only: bool = False,
token: Optional[Union[str, bool]] = ... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
- A string, the *model id* of a predefined tokenizer hosted inside a model repo on huggingface.co.
- A path to a *directory* containing vocabulary files required by the tokenizer, for instance saved
using the [`~tokenization_utils_base.PreTrainedTokenizerBase.save_pretrained`] method, ... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
Whether or not to force the (re-)download the vocabulary files and override the cached versions if they
exist.
resume_download:
Deprecated and ignored. All downloads are now resumed by default when possible.
Will be removed in v5 of Transformers.
p... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
revision (`str`, *optional*, defaults to `"main"`):
The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
identifier allowe... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
execute code present on the Hub on your local machine.
kwargs (additional keyword arguments, *optional*):
Will be passed to the Tokenizer `__init__` method. Can be used to set special tokens like `bos_token`,
`eos_token`, `unk_token`, `sep_token`, `pad_token`, `cls_token`, `m... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
<Tip>
Passing `token=True` is required when you want to use a private model.
</Tip>
Examples:
```python
# We can't instantiate directly the base class *PreTrainedTokenizerBase* so let's show our examples on a derived class: BertTokenizer
# Download vocabulary from hug... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
# You can link tokens to special vocabulary when instantiating
tokenizer = BertTokenizer.from_pretrained("google-bert/bert-base-uncased", unk_token="<unk>")
# You should be sure '<unk>' is in the vocabulary when doing that.
# Otherwise use tokenizer.add_special_tokens({'unk_token': '<unk>'}) ins... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
if use_auth_token is not None:
warnings.warn(
"The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.",
FutureWarning,
)
if token is not None:
raise ValueError(
... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
is_local = os.path.isdir(pretrained_model_name_or_path)
single_file_id = None
if os.path.isfile(pretrained_model_name_or_path) or is_remote_url(pretrained_model_name_or_path):
if len(cls.vocab_files_names) > 1 and not gguf_file:
raise ValueError(
f"Calling... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
vocab_files[file_id] = pretrained_model_name_or_path
single_file_id = file_id
else:
if gguf_file:
vocab_files["vocab_file"] = gguf_file
else:
# At this point pretrained_model_name_or_path is either a directory or a model identifier name
... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
if "tokenizer_file" in vocab_files:
# Try to get the tokenizer config to see if there are versioned tokenizer files.
fast_tokenizer_file = FULL_TOKENIZER_FILE
resolved_config_file = cached_file(
pretrained_model_name_or_path,
... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
_commit_hash=commit_hash,
)
commit_hash = extract_commit_hash(resolved_config_file, commit_hash)
if resolved_config_file is not None:
with open(resolved_config_file, encoding="utf-8") as reader:
tokenizer_con... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
# Get files from url, cache, or disk depending on the case
resolved_vocab_files = {}
unresolved_files = []
for file_id, file_path in vocab_files.items():
if file_path is None:
resolved_vocab_files[file_id] = None
elif single_file_id == file_id:
... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
user_agent=user_agent,
revision=revision,
subfolder=subfolder,
_raise_exceptions_for_gated_repo=False,
_raise_exceptions_for_missing_entries=False,
_raise_exceptions_for_connection_errors=False,
_comm... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
if len(unresolved_files) > 0:
logger.info(
f"Can't load following files from cache: {unresolved_files} and cannot check if these "
"files are necessary for the tokenizer to operate."
)
# If one passes a GGUF file path to `gguf_file` there is no need for t... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
for file_id, file_path in vocab_files.items():
if file_id not in resolved_vocab_files:
continue
if is_local:
logger.info(f"loading file {file_path}")
else:
logger.info(f"loading file {file_path} from cache at {resolved_vocab_files[file... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
@classmethod
def _from_pretrained(
cls,
resolved_vocab_files,
pretrained_model_name_or_path,
init_configuration,
*init_inputs,
token=None,
cache_dir=None,
local_files_only=False,
_commit_hash=None,
_is_local=False,
trust_remote_... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
# If one passes a GGUF file path to `gguf_file` there is no need for this check as the tokenizer will be
# loaded directly from the GGUF file.
if (from_slow or not has_tokenizer_file) and cls.slow_tokenizer_class is not None and not gguf_file:
slow_tokenizer = (cls.slow_tokenizer_class)._fro... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
# Prepare tokenizer initialization kwargs
# Did we saved some inputs and kwargs to reload ?
tokenizer_config_file = resolved_vocab_files.pop("tokenizer_config_file", None)
if tokenizer_config_file is not None:
with open(tokenizer_config_file, encoding="utf-8") as tokenizer_config_han... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
# If an independent chat template file exists, it takes priority over template entries in the tokenizer config
chat_template_file = resolved_vocab_files.pop("chat_template_file", None)
if chat_template_file is not None:
with open(chat_template_file) as chat_template_handle:
i... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
if not _is_local:
if "auto_map" in init_kwargs:
# For backward compatibility with odl format.
if isinstance(init_kwargs["auto_map"], (tuple, list)):
init_kwargs["auto_map"] = {"AutoTokenizer": init_kwargs["auto_map"]}
init_kwargs["auto_map"... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
if config_tokenizer_class is None:
# Matt: This entire block is only used to decide if the tokenizer class matches the class in the repo.
# If not, it raises a warning, but otherwise continues. Since we mostly load tokenizers with
# AutoTokenizer these days, it seems like... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
# Second attempt. If we have not yet found tokenizer_class, let's try to use the config.
try:
config = AutoConfig.from_pretrained(
pretrained_model_name_or_path,
token=token,
cache_dir=cache_dir,
local_files_only... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
if hasattr(config, "model_type"):
model_type = config.model_type
else:
# Fallback: use pattern matching on the string.
model_type = None
for pattern in TOKENIZER_MAPPING_NAMES.keys():
if pattern in st... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
if config_tokenizer_class is not None:
if cls.__name__.replace("Fast", "") != config_tokenizer_class.replace("Fast", ""):
logger.warning(
"The tokenizer class you load from this checkpoint is not the same type as the class this"
" function is called fr... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
# Merge resolved_vocab_files arguments in init_kwargs.
added_tokens_file = resolved_vocab_files.pop("added_tokens_file", None)
special_tokens_map_file = resolved_vocab_files.pop("special_tokens_map_file", None)
for args_name, file_path in resolved_vocab_files.items():
if args_name no... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
#### Handle tokenizer serialization of added and special tokens
added_tokens_decoder: Dict[int, AddedToken] = {}
added_tokens_map: Dict[str, AddedToken] = {}
# if we have info on the slow added tokens
if "added_tokens_decoder" in init_kwargs:
for idx, token in init_kwargs["ad... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
with open(special_tokens_map_file, encoding="utf-8") as special_tokens_map_handle:
special_tokens_map = json.load(special_tokens_map_handle)
for key, value in special_tokens_map.items():
if key in kwargs and kwargs[key]:
# This ... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
token["special"] = True
token = AddedToken(**token)
if token not in additional_special_tokens:
additional_special_tokens.append(token)
value = additional_special_tokens
... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
# slow -> slow|fast, legacy: convert the `"added_tokens.json"` file to `added_tokens_decoder`.
# this is for legacy purpose. We don't add the tokens after init for efficiency.
if added_tokens_file is not None:
special_tokens = []
for key in cls.SPECIAL_TOKENS_ATTR... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.