text
stringlengths
1
1.02k
class_index
int64
0
10.8k
source
stringlengths
85
188
with open(added_tokens_file, encoding="utf-8") as added_tokens_handle: added_tok_encoder = json.load(added_tokens_handle) for str_token, index in added_tok_encoder.items(): # if index not in added_tokens_decoder and str_token not in added_tokens_map: ...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
# allows converting a fast -> slow: add the `tokenizer.json`'s `"added_tokens"` to the slow tokenizer # if `tokenizer_config.json` is `None` if tokenizer_file is not None: # This is for slow so can be done before with open(tokenizer_file, encoding="utf-8") as toke...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
# Passing AddedTokens and not strings to the class to prevent it from casting the string to a different AddedToken # convert {'__type': 'AddedToken', 'content': '<ent>', 'lstrip': False, 'normalized': True, ...} to AddedTokens init_kwargs["added_tokens_decoder"] = added_tokens_decoder init_kwarg...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
# Instantiate the tokenizer. try: tokenizer = cls(*init_inputs, **init_kwargs) except import_protobuf_decode_error(): logger.info( "Unable to load tokenizer model from SPM, loading from TikToken will be attempted instead." "(Google protobuf error: ...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
if added_tokens_decoder != {} and max(list(added_tokens_decoder.keys())[-1], 0) > tokenizer.vocab_size: logger.info( "Special tokens have been added in the vocabulary, make sure the associated word embeddings are" " fine-tuned or trained." ) return tokeniz...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
@classmethod def convert_added_tokens(cls, obj: Union[AddedToken, Any], save=False, add_type_field=True): if isinstance(obj, dict) and "__type" in obj and obj["__type"] == "AddedToken": obj.pop("__type") return AddedToken(**obj) if isinstance(obj, AddedToken) and save: ...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
def save_pretrained( self, save_directory: Union[str, os.PathLike], legacy_format: Optional[bool] = None, filename_prefix: Optional[str] = None, push_to_hub: bool = False, **kwargs, ) -> Tuple[str]: """ Save the full tokenizer state. This met...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
Args: save_directory (`str` or `os.PathLike`): The path to a directory where the tokenizer will be saved. legacy_format (`bool`, *optional*): Only applicable for a fast tokenizer. If unset (default), will save the tokenizer in the unified JSON format as well as in...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
If `True`, will save the tokenizer in legacy format. If the "slow" tokenizer doesn't exits, a value error is raised. filename_prefix (`str`, *optional*): A prefix to add to the names of the files saved by the tokenizer. push_to_hub (`bool`, *optional*, defaults to...
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 kwargs.get("token", None) is not None: raise ValueEr...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
special_tokens_map_file = os.path.join( save_directory, (filename_prefix + "-" if filename_prefix else "") + SPECIAL_TOKENS_MAP_FILE ) tokenizer_config_file = os.path.join( save_directory, (filename_prefix + "-" if filename_prefix else "") + TOKENIZER_CONFIG_FILE ) ...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
# Let's make sure we properly save the special tokens tokenizer_config.update(self.special_tokens_map) if "extra_special_tokens" not in tokenizer_config: tokenizer_config["extra_special_tokens"] = self.extra_special_tokens tokenizer_config.update(self.extra_special_tokens)
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
saved_raw_chat_template = False if self.chat_template is not None: if isinstance(self.chat_template, dict): # Chat template dicts are saved to the config as lists of dicts with fixed key names. # They will be reconstructed as a single dict during loading. ...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
tokenizer_config.pop("chat_template") # To ensure it doesn't somehow end up in the config too else: tokenizer_config["chat_template"] = self.chat_template
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
if len(self.init_inputs) > 0: tokenizer_config["init_inputs"] = copy.deepcopy(self.init_inputs) for file_id in self.vocab_files_names.keys(): tokenizer_config.pop(file_id, None) # no typefields, this way old fast and slow can load it tokenizer_config = self.convert_added...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
# Add tokenizer class to the tokenizer config to be able to reload it with from_pretrained tokenizer_class = self.__class__.__name__ # Remove the Fast at the end unless we have a special `PreTrainedTokenizerFast` if tokenizer_class.endswith("Fast") and tokenizer_class != "PreTrainedTokenizerFast...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
# remove private information if "name_or_path" in tokenizer_config: tokenizer_config.pop("name_or_path") tokenizer_config.pop("special_tokens_map_file", None) tokenizer_config.pop("tokenizer_file", None) if "device_map" in tokenizer_config: tokenizer_confi...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
# kept for forward compatibility, will be removed in transoformers 5. Typefields are not saved for FC, special should not be save either write_dict = self.convert_added_tokens(self.special_tokens_map_extended, save=True, add_type_field=False) with open(special_tokens_map_file, "w", encoding="utf-8") as ...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
if push_to_hub: self._upload_modified_files( save_directory, repo_id, files_timestamps, commit_message=commit_message, token=kwargs.get("token"), ) return save_files def _save_pretrained( self, ...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
Fast tokenizers can also be saved in a unique JSON file containing {config + vocab + added-tokens} using the specific [`~tokenization_utils_fast.PreTrainedTokenizerFast._save_pretrained`] """ if legacy_format is False: raise ValueError( "Only fast tokenizers (instance...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
added_tokens_file = os.path.join( save_directory, (filename_prefix + "-" if filename_prefix else "") + ADDED_TOKENS_FILE ) # the new get_added_vocab() also returns special tokens and tokens that have an index < vocab_size added_vocab = {tok: index for tok, index in self.added_tokens_...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]: """ Save only the vocabulary of the tokenizer (vocabulary + added tokens). This method won't save the configuration and special token mappings of the tokenizer. Use [`~PreTrainedTokenize...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
Args: text (`str`): The sequence to be encoded. pair (`str`, *optional*): A second sequence to be encoded with the first. add_special_tokens (`bool`, *optional*, defaults to `False`): Whether or not to add the special tokens associated ...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
@add_end_docstrings( ENCODE_KWARGS_DOCSTRING, """ **kwargs: Passed along to the `.tokenize()` method. """, """ Returns: `List[int]`, `torch.Tensor`, `tf.Tensor` or `np.ndarray`: The tokenized ids of the text. """, ) def encode( self...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
Same as doing `self.convert_tokens_to_ids(self.tokenize(text))`.
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
Args: text (`str`, `List[str]` or `List[int]`): The first sequence to be encoded. This can be a string, a list of strings (tokenized string using the `tokenize` method) or a list of integers (tokenized string ids using the `convert_tokens_to_ids` method). ...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
**kwargs, )
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
return encoded_inputs["input_ids"] def num_special_tokens_to_add(self, pair: bool = False) -> int: raise NotImplementedError def _get_padding_truncation_strategies( self, padding=False, truncation=None, max_length=None, pad_to_multiple_of=None, verbose=True, **kwargs ): """ ...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
# Backward compatibility for previous behavior, maybe we should deprecate it: # If you only set max_length, it activates truncation for max_length if max_length is not None and padding is False and truncation is None: if verbose: if not self.deprecation_warnings.get("Truncati...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
truncation = "longest_first"
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
# Get padding strategy if padding is False and old_pad_to_max_length: if verbose: warnings.warn( "The `pad_to_max_length` argument is deprecated and will be removed in a future version, " "use `padding=True` or `padding='longest'` to pad to the...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
if max_length is not None and ( truncation is None or truncation is False or truncation == "do_not_truncate" ): warnings.warn( "`max_length` is ignored when `padding`=`True` and there is no truncation strategy. " ...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
# Get truncation strategy if truncation is None and old_truncation_strategy != "do_not_truncate": if verbose: warnings.warn( "The `truncation_strategy` argument is deprecated and will be removed in a future version, use" " `truncation=True` to ...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
" in the pairs).", FutureWarning, ) truncation_strategy = TruncationStrategy(old_truncation_strategy) elif truncation is not False and truncation is not None: if truncation is True: truncation_strategy = ( Truncation...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
# Set max length if needed if max_length is None: if padding_strategy == PaddingStrategy.MAX_LENGTH: if self.model_max_length > LARGE_INTEGER: if verbose: if not self.deprecation_warnings.get("Asking-to-pad-to-max_length", False): ...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
if truncation_strategy != TruncationStrategy.DO_NOT_TRUNCATE: if self.model_max_length > LARGE_INTEGER: if verbose: if not self.deprecation_warnings.get("Asking-to-truncate-to-max_length", False): logger.warning( ...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
# Test if we have a padding token if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.pad_token is None or self.pad_token_id < 0): raise ValueError( "Asking to pad but the tokenizer does not have a padding token. " "Please select a token to use as `pad_token` ...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
# Check that we will truncate to a multiple of pad_to_multiple_of if both are provided if ( truncation_strategy != TruncationStrategy.DO_NOT_TRUNCATE and padding_strategy != PaddingStrategy.DO_NOT_PAD and pad_to_multiple_of is not None and max_length is not None ...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
@add_end_docstrings(ENCODE_KWARGS_DOCSTRING, ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING) def __call__( self, text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None, text_pair: Optional[Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInpu...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
return_tensors: Optional[Union[str, TensorType]] = None, return_token_type_ids: Optional[bool] = None, return_attention_mask: Optional[bool] = None, return_overflowing_tokens: bool = False, return_special_tokens_mask: bool = False, return_offsets_mapping: bool = False, re...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
Args: text (`str`, `List[str]`, `List[List[str]]`, *optional*): The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set ...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
list of strings (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set `is_split_into_words=True` (to lift the ambiguity with a batch of sequences). text_pair_target (`str`, `List[str]`, `List[List[str]]`, *optional*): The sequenc...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
"padding_side": padding_side, "return_tensors": return_tensors, "return_token_type_ids": return_token_type_ids, "return_attention_mask": return_attention_mask, "return_overflowing_tokens": return_overflowing_tokens, "return_special_tokens_mask": return_special...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
self._switch_to_input_mode() encodings = self._call_one(text=text, text_pair=text_pair, **all_kwargs) if text_target is not None: self._switch_to_target_mode() target_encodings = self._call_one(text=text_target, text_pair=text_pair_target, **all_kwargs) # Leave back t...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
if text_target is None: return encodings elif text is None: return target_encodings else: encodings["labels"] = target_encodings["input_ids"] return encodings
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
def _call_one( self, text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]], text_pair: Optional[Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]]] = None, add_special_tokens: bool = True, padding: Union[bool, str, PaddingS...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
split_special_tokens: bool = False, **kwargs, ) -> BatchEncoding: # Input type checking for clearer error def _is_valid_text_input(t): if isinstance(t, str): # Strings are fine return True elif isinstance(t, (list, tuple)): ...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
if not _is_valid_text_input(text): raise ValueError( "text input must be of type `str` (single example), `List[str]` (batch or single pretokenized example) " "or `List[List[str]]` (batch of pretokenized examples)." ) if text_pair is not None and not _is_v...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
if is_batched: if isinstance(text_pair, str): raise TypeError( "when tokenizing batches of text, `text_pair` must be a list or tuple with the same length as" " `text`." ) if text_pair is not None and len(text) != len(text_pa...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
pad_to_multiple_of=pad_to_multiple_of, padding_side=padding_side, return_tensors=return_tensors, return_token_type_ids=return_token_type_ids, return_attention_mask=return_attention_mask, return_overflowing_tokens=return_overflowing_tokens, ...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
pad_to_multiple_of=pad_to_multiple_of, padding_side=padding_side, return_tensors=return_tensors, return_token_type_ids=return_token_type_ids, return_attention_mask=return_attention_mask, return_overflowing_tokens=return_overflowing_tokens, ...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
@add_end_docstrings(ENCODE_KWARGS_DOCSTRING, ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING) def encode_plus( self, text: Union[TextInput, PreTokenizedInput, EncodedInput], text_pair: Optional[Union[TextInput, PreTokenizedInput, EncodedInput]] = None, add_special_tokens: bool = True, ...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
verbose: bool = True, **kwargs, ) -> BatchEncoding: """ Tokenize and prepare for the model a sequence or a pair of sequences.
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
<Tip warning={true}> This method is deprecated, `__call__` should be used instead. </Tip> Args: text (`str`, `List[str]` or (for non-fast tokenizers) `List[int]`): The first sequence to be encoded. This can be a string, a list of strings (tokenized string using the...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
# Backward compatibility for 'truncation_strategy', 'pad_to_max_length' padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies( padding=padding, truncation=truncation, max_length=max_length, pad_to_multiple_of=pad_to_mu...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
return self._encode_plus( text=text, text_pair=text_pair, add_special_tokens=add_special_tokens, padding_strategy=padding_strategy, truncation_strategy=truncation_strategy, max_length=max_length, stride=stride, is_split_into...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
def _encode_plus( self, text: Union[TextInput, PreTokenizedInput, EncodedInput], text_pair: Optional[Union[TextInput, PreTokenizedInput, EncodedInput]] = None, add_special_tokens: bool = True, padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD, truncation_stra...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
**kwargs, ) -> BatchEncoding: raise NotImplementedError
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
@add_end_docstrings(ENCODE_KWARGS_DOCSTRING, ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING) def batch_encode_plus( self, batch_text_or_text_pairs: Union[ List[TextInput], List[TextInputPair], List[PreTokenizedInput], List[PreTokenizedInputPair], ...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
return_special_tokens_mask: bool = False, return_offsets_mapping: bool = False, return_length: bool = False, verbose: bool = True, split_special_tokens: bool = False, **kwargs, ) -> BatchEncoding: """ Tokenize and prepare for the model a list of sequences or a...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
<Tip warning={true}> This method is deprecated, `__call__` should be used instead. </Tip> Args: batch_text_or_text_pairs (`List[str]`, `List[Tuple[str, str]]`, `List[List[str]]`, `List[Tuple[List[str], List[str]]]`, and for not-fast tokenizers, also `List[List[int]]`, `List[Tuple[...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
return self._batch_encode_plus( batch_text_or_text_pairs=batch_text_or_text_pairs, add_special_tokens=add_special_tokens, padding_strategy=padding_strategy, truncation_strategy=truncation_strategy, max_length=max_length, stride=stride, ...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
def _batch_encode_plus( self, batch_text_or_text_pairs: Union[ List[TextInput], List[TextInputPair], List[PreTokenizedInput], List[PreTokenizedInputPair], List[EncodedInput], List[EncodedInputPair], ], add_special_to...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
return_offsets_mapping: bool = False, return_length: bool = False, verbose: bool = True, split_special_tokens: bool = False, **kwargs, ) -> BatchEncoding: raise NotImplementedError
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
def pad( self, encoded_inputs: Union[ BatchEncoding, List[BatchEncoding], Dict[str, EncodedInput], Dict[str, List[EncodedInput]], List[Dict[str, EncodedInput]], ], padding: Union[bool, str, PaddingStrategy] = True, max_l...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
Please note that with a fast tokenizer, using the `__call__` method is faster than using a method to encode the text followed by a call to the `pad` method to get a padded encoding. <Tip> If the `encoded_inputs` passed are dictionary of numpy arrays, PyTorch tensors or TensorFlow tensors, the ...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
Args: encoded_inputs ([`BatchEncoding`], list of [`BatchEncoding`], `Dict[str, List[int]]`, `Dict[str, List[List[int]]` or `List[Dict[str, List[int]]]`): Tokenized inputs. Can represent one input ([`BatchEncoding`] or `Dict[str, List[int]]`) or a batch of tokenized inputs (li...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
- `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence if provided). - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that ...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability `>= 7.5` (Volta). padding_side (`str`, *optional*): The side on which the model should have padding applied. Should be selected between ['right', 'left']. De...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
- `'tf'`: Return TensorFlow `tf.constant` objects. - `'pt'`: Return PyTorch `torch.Tensor` objects. - `'np'`: Return Numpy `np.ndarray` objects. verbose (`bool`, *optional*, defaults to `True`): Whether or not to print more information and warnings. ""...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
# If we have a list of dicts, let's convert it in a dict of lists # We do this to allow using this method as a collate_fn function in PyTorch Dataloader if isinstance(encoded_inputs, (list, tuple)) and isinstance(encoded_inputs[0], Mapping): encoded_inputs = {key: [example[key] for example i...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
if required_input is None or (isinstance(required_input, Sized) and len(required_input) == 0): if return_attention_mask: encoded_inputs["attention_mask"] = [] return encoded_inputs # If we have PyTorch/TF/NumPy tensors/arrays as inputs, we cast them as python objects ...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
first_element = required_input[0] if isinstance(first_element, (list, tuple)): # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element. for item in required_input: if len(item) != 0: first_element = item[0...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
f"type of {first_element} unknown: {type(first_element)}. " "Should be one of a python, numpy, pytorch or tensorflow object." )
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
for key, value in encoded_inputs.items(): encoded_inputs[key] = to_py_obj(value) # Convert padding_strategy in PaddingStrategy padding_strategy, _, max_length, _ = self._get_padding_truncation_strategies( padding=padding, max_length=max_length, verbose=verbose ) ...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
batch_size = len(required_input) assert all( len(v) == batch_size for v in encoded_inputs.values() ), "Some items in the output dictionary have a different batch size than others." if padding_strategy == PaddingStrategy.LONGEST: max_length = max(len(inputs) for inputs in...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
for key, value in outputs.items(): if key not in batch_outputs: batch_outputs[key] = [] batch_outputs[key].append(value) return BatchEncoding(batch_outputs, tensor_type=return_tensors) def create_token_type_ids_from_sequences( self, token_ids_0: ...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
def build_inputs_with_special_tokens( self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None ) -> List[int]: """ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and adding special tokens. This impleme...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
@add_end_docstrings(ENCODE_KWARGS_DOCSTRING, ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING) def prepare_for_model( self, ids: List[int], pair_ids: Optional[List[int]] = None, add_special_tokens: bool = True, padding: Union[bool, str, PaddingStrategy] = False, truncation: Un...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
Prepares a sequence of input id, or a pair of sequences of inputs ids so that it can be used by the model. It adds special tokens, truncates sequences if overflowing while taking into account the special tokens and manages a moving window (with user defined stride) for overflowing tokens. Please Note, f...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
Args: ids (`List[int]`): Tokenized input ids of the first sequence. Can be obtained from a string by chaining the `tokenize` and `convert_tokens_to_ids` methods. pair_ids (`List[int]`, *optional*): Tokenized input ids of the second sequence. Can be...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
if return_token_type_ids and not add_special_tokens: raise ValueError( "Asking to return token_type_ids while setting add_special_tokens to False " "results in an undefined behavior. Please set add_special_tokens to True or " "set return_token_type_ids to None...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
# Load from model defaults if return_token_type_ids is None: return_token_type_ids = "token_type_ids" in self.model_input_names if return_attention_mask is None: return_attention_mask = "attention_mask" in self.model_input_names encoded_inputs = {} # Compute the...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
if return_overflowing_tokens: encoded_inputs["overflowing_tokens"] = overflowing_tokens encoded_inputs["num_truncated_tokens"] = total_len - max_length # Add special tokens if add_special_tokens: sequence = self.build_inputs_with_special_tokens(ids, pair_ids) ...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
# Check lengths self._eventual_warn_about_too_long_sequence(encoded_inputs["input_ids"], max_length, verbose) # Padding if padding_strategy != PaddingStrategy.DO_NOT_PAD or return_attention_mask: encoded_inputs = self.pad( encoded_inputs, max_length=m...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
def truncate_sequences( self, ids: List[int], pair_ids: Optional[List[int]] = None, num_tokens_to_remove: int = 0, truncation_strategy: Union[str, TruncationStrategy] = "longest_first", stride: int = 0, ) -> Tuple[List[int], List[int], List[int]]: """ ...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
Args: ids (`List[int]`): Tokenized input ids of the first sequence. Can be obtained from a string by chaining the `tokenize` and `convert_tokens_to_ids` methods. pair_ids (`List[int]`, *optional*): Tokenized input ids of the second sequence. Can be...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
- `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will truncate token by token, removing a token from the longest sequence in the pair if a pair of ...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided. - `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths greater than the model maximum admissible input size). stride (`int`, *optional*, de...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
Returns: `Tuple[List[int], List[int], List[int]]`: The truncated `ids`, the truncated `pair_ids` and the list of overflowing tokens. Note: The *longest_first* strategy returns empty list of overflowing tokens if a pair of sequences (or a batch of pairs) is provided. """ ...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
overflowing_tokens = [] if truncation_strategy == TruncationStrategy.ONLY_FIRST or ( truncation_strategy == TruncationStrategy.LONGEST_FIRST and pair_ids is None ): if len(ids) > num_tokens_to_remove: window_len = min(len(ids), stride + num_tokens_to_remove) ...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
else: error_msg = ( f"We need to remove {num_tokens_to_remove} to truncate the input " f"but the first sequence has a length {len(ids)}. " ) if truncation_strategy == TruncationStrategy.ONLY_FIRST: error_msg = ( ...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
len_pair_ids = len(pair_ids) if pair_ids is not None else 0 len_ids = len(ids) first_remove = min(abs(len_pair_ids - len_ids), num_tokens_to_remove) second_remove = num_tokens_to_remove - first_remove if len_ids > len_pair_ids: ids_to_move = first_remove +...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
if self.truncation_side == "right": ids = ids[:-ids_to_move] if ids_to_move > 0 else ids pair_ids = pair_ids[:-pair_ids_to_move] if pair_ids is not None and pair_ids_to_move > 0 else pair_ids elif self.truncation_side == "left": ids = ids[ids_to_move:] ...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
elif truncation_strategy == TruncationStrategy.ONLY_SECOND and pair_ids is not None: if len(pair_ids) > num_tokens_to_remove: window_len = min(len(pair_ids), stride + num_tokens_to_remove) if self.truncation_side == "right": overflowing_tokens = pair_ids[-...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
"for instance 'longest_first' or 'only_first'." )
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
return (ids, pair_ids, overflowing_tokens) def _pad( self, encoded_inputs: Union[Dict[str, EncodedInput], BatchEncoding], max_length: Optional[int] = None, padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD, pad_to_multiple_of: Optional[int] = None, paddi...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
- PaddingStrategy.LONGEST Pad to the longest sequence in the batch - PaddingStrategy.MAX_LENGTH: Pad to the max length (default) - PaddingStrategy.DO_NOT_PAD: Do not pad The tokenizer padding sides are defined in `padding_side` argument:
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
- 'left': pads on the left of the sequences - 'right': pads on the right of the sequences pad_to_multiple_of: (optional) Integer if set will pad the sequence to a multiple of the provided value. This is especially useful to enable the use of Tensor Core on NVIDIA hardware...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py
if padding_strategy == PaddingStrategy.LONGEST: max_length = len(required_input) if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of needs_to_be_padde...
75
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py