code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def run_test_in_subprocess(test_case, target_func, inputs=None, timeout=600): """ To run a test in a subprocess. In particular, this can avoid (GPU) memory issue. Args: test_case (`unittest.TestCase`): The test that will run `target_func`. target_func (`Callable`): T...
To run a test in a subprocess. In particular, this can avoid (GPU) memory issue. Args: test_case (`unittest.TestCase`): The test that will run `target_func`. target_func (`Callable`): The function implementing the actual testing logic. inputs (`dict`, *optional*...
run_test_in_subprocess
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/testing_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/testing_utils.py
Apache-2.0
def shape_list(tensor: Union[tf.Tensor, np.ndarray]) -> List[int]: """ Deal with dynamic shape in tensorflow cleanly. Args: tensor (`tf.Tensor` or `np.ndarray`): The tensor we want the shape of. Returns: `List[int]`: The shape of the tensor as a list. """ if isinstance(tensor, ...
Deal with dynamic shape in tensorflow cleanly. Args: tensor (`tf.Tensor` or `np.ndarray`): The tensor we want the shape of. Returns: `List[int]`: The shape of the tensor as a list.
shape_list
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tf_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tf_utils.py
Apache-2.0
def stable_softmax(logits: tf.Tensor, axis: Optional[int] = None, name: Optional[str] = None) -> tf.Tensor: """ Stable wrapper that returns the same output as `tf.nn.softmax`, but that works reliably with XLA on CPU. It is meant as a workaround for the [following issue](https://github.com/tensorflow/tensorf...
Stable wrapper that returns the same output as `tf.nn.softmax`, but that works reliably with XLA on CPU. It is meant as a workaround for the [following issue](https://github.com/tensorflow/tensorflow/issues/55682), and will be removed after it gets fixed. The arguments and outputs are the same as `tf.nn.so...
stable_softmax
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tf_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tf_utils.py
Apache-2.0
def split(self, text: str) -> List[str]: """ Will look for the words added to the trie within `text`. Output is the original string splitted along the boundaries of the words found. This trie will match the longest possible word first ! Example: ```python >>> t...
Will look for the words added to the trie within `text`. Output is the original string splitted along the boundaries of the words found. This trie will match the longest possible word first ! Example: ```python >>> trie = Trie() >>> trie.split("[CLS] This is a...
split
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils.py
Apache-2.0
def _is_whitespace(char): """Checks whether `char` is a whitespace character.""" # \t, \n, and \r are technically control characters but we treat them # as whitespace since they are generally considered as such. if char == " " or char == "\t" or char == "\n" or char == "\r": return True cat ...
Checks whether `char` is a whitespace character.
_is_whitespace
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils.py
Apache-2.0
def _is_control(char): """Checks whether `char` is a control character.""" # These are technically control characters but we count them as whitespace # characters. if char == "\t" or char == "\n" or char == "\r": return False cat = unicodedata.category(char) if cat.startswith("C"): ...
Checks whether `char` is a control character.
_is_control
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils.py
Apache-2.0
def _is_punctuation(char): """Checks whether `char` is a punctuation character.""" cp = ord(char) # We treat all non-letter/number ASCII as punctuation. # Characters such as "^", "$", and "`" are not in the Unicode # Punctuation class but we treat them as punctuation anyways, for # consistency. ...
Checks whether `char` is a punctuation character.
_is_punctuation
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils.py
Apache-2.0
def _is_end_of_word(text): """Checks whether the last character in text is one of a punctuation, control or whitespace character.""" last_char = text[-1] return bool(_is_control(last_char) | _is_punctuation(last_char) | _is_whitespace(last_char))
Checks whether the last character in text is one of a punctuation, control or whitespace character.
_is_end_of_word
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils.py
Apache-2.0
def _is_start_of_word(text): """Checks whether the first character in text is one of a punctuation, control or whitespace character.""" first_char = text[0] return bool(_is_control(first_char) | _is_punctuation(first_char) | _is_whitespace(first_char))
Checks whether the first character in text is one of a punctuation, control or whitespace character.
_is_start_of_word
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils.py
Apache-2.0
def _insert_one_token_to_ordered_list(token_list: List[str], new_token: str): """ Inserts one token to an ordered list if it does not already exist. Note: token_list must be sorted. """ insertion_idx = bisect.bisect_left(token_list, new_token) # Checks if new_token is already in the ordered token_li...
Inserts one token to an ordered list if it does not already exist. Note: token_list must be sorted.
_insert_one_token_to_ordered_list
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils.py
Apache-2.0
def _add_tokens(self, new_tokens: Union[List[str], List[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 the current vocabulary. ...
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 the current vocabulary. Args: new_tokens (`List[str]`or `List[tokenizers.AddedToken]`): Token(s) to add in vocabul...
_add_tokens
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils.py
Apache-2.0
def num_special_tokens_to_add(self, pair: bool = False) -> int: """ Returns the number of added tokens when encoding a sequence with special tokens. <Tip> This encodes a dummy input and checks the number of added tokens, and is therefore not efficient. Do not put this inside yo...
Returns the number of added tokens when encoding a sequence with special tokens. <Tip> This encodes a dummy input and checks the number of added tokens, and is therefore not efficient. Do not put this inside your training loop. </Tip> Args: pair (`bool`, ...
num_special_tokens_to_add
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils.py
Apache-2.0
def tokenize(self, text: TextInput, **kwargs) -> List[str]: """ Converts a string in a sequence of tokens, using the tokenizer. Split in words for word-based vocabulary or sub-words for sub-word-based vocabularies (BPE/SentencePieces/WordPieces). Takes care of added tokens. Arg...
Converts a string in a sequence of tokens, using the tokenizer. Split in words for word-based vocabulary or sub-words for sub-word-based vocabularies (BPE/SentencePieces/WordPieces). Takes care of added tokens. Args: text (`str`): The sequence to be encoded...
tokenize
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils.py
Apache-2.0
def convert_tokens_to_ids(self, tokens: Union[str, List[str]]) -> Union[int, List[int]]: """ Converts a token string (or a sequence of tokens) in a single integer id (or a sequence of ids), using the vocabulary. Args: tokens (`str` or `List[str]`): One or several token(s) to...
Converts a token string (or a sequence of tokens) in a single integer id (or a sequence of ids), using the vocabulary. Args: tokens (`str` or `List[str]`): One or several token(s) to convert to token id(s). Returns: `int` or `List[int]`: The token id or list of...
convert_tokens_to_ids
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils.py
Apache-2.0
def _batch_prepare_for_model( self, batch_ids_pairs: List[Union[PreTokenizedInputPair, Tuple[List[int], None]]], add_special_tokens: bool = True, padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD, truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TR...
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 ...
_batch_prepare_for_model
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils.py
Apache-2.0
def prepare_for_tokenization( self, text: str, is_split_into_words: bool = False, **kwargs ) -> Tuple[str, Dict[str, Any]]: """ Performs any necessary transformations before tokenization. This method should pop the arguments from kwargs and return the remaining `kwargs` as well. We ...
Performs any necessary transformations before tokenization. This method should pop the arguments from kwargs and return the remaining `kwargs` as well. We test the `kwargs` at the end of the encoding process to be sure all the arguments have been used. Args: text (`str`): ...
prepare_for_tokenization
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils.py
Apache-2.0
def get_special_tokens_mask( self, token_ids_0: List, token_ids_1: Optional[List] = None, already_has_special_tokens: bool = False ) -> List[int]: """ Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding special tokens using the...
Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding special tokens using the tokenizer `prepare_for_model` or `encode_plus` methods. Args: token_ids_0 (`List[int]`): List of ids of the first sequence. ...
get_special_tokens_mask
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils.py
Apache-2.0
def convert_ids_to_tokens( self, ids: Union[int, List[int]], skip_special_tokens: bool = False ) -> Union[str, List[str]]: """ Converts a single index or a sequence of indices in a token or a sequence of tokens, using the vocabulary and added tokens. Args: ids (`...
Converts a single index or a sequence of indices in a token or a sequence of tokens, using the vocabulary and added tokens. Args: ids (`int` or `List[int]`): The token id (or token ids) to convert to tokens. skip_special_tokens (`bool`, *optional*, defau...
convert_ids_to_tokens
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils.py
Apache-2.0
def __getitem__(self, item: Union[int, str]) -> Union[Any, EncodingFast]: """ If the key is a string, returns the value of the dict associated to `key` ('input_ids', 'attention_mask', etc.). If the key is an integer, get the `tokenizers.Encoding` for batch item with index `key`. ...
If the key is a string, returns the value of the dict associated to `key` ('input_ids', 'attention_mask', etc.). If the key is an integer, get the `tokenizers.Encoding` for batch item with index `key`.
__getitem__
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
def tokens(self, batch_index: int = 0) -> List[str]: """ Return the list of tokens (sub-parts of the input strings after word/subword splitting and before conversion to integer indices) at a given batch index (only works for the output of a fast tokenizer). Args: batch_index...
Return the list of tokens (sub-parts of the input strings after word/subword splitting and before conversion to integer indices) at a given batch index (only works for the output of a fast tokenizer). Args: batch_index (`int`, *optional*, defaults to 0): The index to access in the ...
tokens
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
def sequence_ids(self, batch_index: int = 0) -> List[Optional[int]]: """ Return a list mapping the tokens to the id of their original sentences: - `None` for special tokens added around or between sequences, - `0` for tokens corresponding to words in the first sequence, ...
Return a list mapping the tokens to the id of their original sentences: - `None` for special tokens added around or between sequences, - `0` for tokens corresponding to words in the first sequence, - `1` for tokens corresponding to words in the second sequence when a pair o...
sequence_ids
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
def words(self, batch_index: int = 0) -> List[Optional[int]]: """ Return a list mapping the tokens to their actual word in the initial sentence for a fast tokenizer. Args: batch_index (`int`, *optional*, defaults to 0): The index to access in the batch. Returns: ...
Return a list mapping the tokens to their actual word in the initial sentence for a fast tokenizer. Args: batch_index (`int`, *optional*, defaults to 0): The index to access in the batch. Returns: `List[Optional[int]]`: A list indicating the word corresponding to each ...
words
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
def token_to_sequence(self, batch_or_token_index: int, token_index: Optional[int] = None) -> int: """ Get the index of the sequence represented by the given token. In the general use case, this method returns `0` for a single sequence or the first sequence of a pair, and `1` for the second seque...
Get the index of the sequence represented by the given token. In the general use case, this method returns `0` for a single sequence or the first sequence of a pair, and `1` for the second sequence of a pair Can be called as: - `self.token_to_sequence(token_index)` if batch size is 1 ...
token_to_sequence
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
def token_to_word(self, batch_or_token_index: int, token_index: Optional[int] = None) -> int: """ Get the index of the word corresponding (i.e. comprising) to an encoded token in a sequence of the batch. Can be called as: - `self.token_to_word(token_index)` if batch size is 1 -...
Get the index of the word corresponding (i.e. comprising) to an encoded token in a sequence of the batch. Can be called as: - `self.token_to_word(token_index)` if batch size is 1 - `self.token_to_word(batch_index, token_index)` if batch size is greater than 1 This method is p...
token_to_word
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
def word_to_tokens( self, batch_or_word_index: int, word_index: Optional[int] = None, sequence_index: int = 0 ) -> Optional[TokenSpan]: """ Get the encoded token span corresponding to a word in a sequence of the batch. Token spans are returned as a [`~tokenization_utils_base.TokenSp...
Get the encoded token span corresponding to a word in a sequence of the batch. Token spans are returned as a [`~tokenization_utils_base.TokenSpan`] with: - **start** -- Index of the first token. - **end** -- Index of the token following the last token. Can be called as: ...
word_to_tokens
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
def token_to_chars(self, batch_or_token_index: int, token_index: Optional[int] = None) -> CharSpan: """ Get the character span corresponding to an encoded token in a sequence of the batch. Character spans are returned as a [`~tokenization_utils_base.CharSpan`] with: - **start** -- Inde...
Get the character span corresponding to an encoded token in a sequence of the batch. Character spans are returned as a [`~tokenization_utils_base.CharSpan`] with: - **start** -- Index of the first character in the original string associated to the token. - **end** -- Index of the char...
token_to_chars
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
def char_to_token( self, batch_or_char_index: int, char_index: Optional[int] = None, sequence_index: int = 0 ) -> int: """ Get the index of the token in the encoded output comprising a character in the original string for a sequence of the batch. Can be called as: -...
Get the index of the token in the encoded output comprising a character in the original string for a sequence of the batch. Can be called as: - `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...
char_to_token
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
def word_to_chars( self, batch_or_word_index: int, word_index: Optional[int] = None, sequence_index: int = 0 ) -> CharSpan: """ Get the character span in the original string corresponding to given word in a sequence of the batch. Character spans are returned as a CharSpan NamedTuple...
Get the character span in the original string corresponding to given word in a sequence of the batch. Character spans are returned as a CharSpan NamedTuple with: - start: index of the first character in the original string - end: index of the character following the last character in ...
word_to_chars
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
def char_to_word(self, batch_or_char_index: int, char_index: Optional[int] = None, sequence_index: int = 0) -> int: """ Get the word in the original string corresponding to a character in the original string of a sequence of the batch. Can be called as: - `self.char_to_word(cha...
Get the word in the original string corresponding to a character in the original string of a sequence of the batch. Can be called as: - `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 Th...
char_to_word
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
def convert_to_tensors( self, tensor_type: Optional[Union[str, TensorType]] = None, prepend_batch_axis: bool = False ): """ Convert the inner content to tensors. Args: tensor_type (`str` or [`~utils.TensorType`], *optional*): The type of tensors to use. I...
Convert the inner content to tensors. 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...
convert_to_tensors
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
def to(self, device: Union[str, "torch.device"]) -> "BatchEncoding": """ Send all values to device by calling `v.to(device)` (PyTorch only). Args: device (`str` or `torch.device`): The device to put the tensors on. Returns: [`BatchEncoding`]: The same instance a...
Send all values to device by calling `v.to(device)` (PyTorch only). Args: device (`str` or `torch.device`): The device to put the tensors on. Returns: [`BatchEncoding`]: The same instance after modification.
to
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
def add_special_tokens(self, special_tokens_dict: Dict[str, Union[str, AddedToken]]) -> int: """ Add a dictionary of special tokens (eos, pad, cls, etc.) to the encoder and link them to class attributes. If special tokens are NOT in the vocabulary, they are added to it (indexed starting from the...
Add a dictionary of special tokens (eos, pad, cls, etc.) to the encoder and link them to class attributes. If special tokens are NOT in the vocabulary, they are added to it (indexed starting from the last index of the current vocabulary). Note,None When adding new tokens to the vocabul...
add_special_tokens
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
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...
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 the current vocabulary and and will be isolated before the tokenization algorithm is applied. Added tokens and tokens from the vocabulary of th...
add_tokens
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
def bos_token(self) -> str: """ `str`: Beginning of sentence token. Log an error if used while not having been set. """ if self._bos_token is None: if self.verbose: logger.error("Using bos_token, but it is not set yet.") return None return ...
`str`: Beginning of sentence token. Log an error if used while not having been set.
bos_token
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
def eos_token(self) -> str: """ `str`: End of sentence token. Log an error if used while not having been set. """ if self._eos_token is None: if self.verbose: logger.error("Using eos_token, but it is not set yet.") return None return str(se...
`str`: End of sentence token. Log an error if used while not having been set.
eos_token
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
def unk_token(self) -> str: """ `str`: Unknown token. Log an error if used while not having been set. """ if self._unk_token is None: if self.verbose: logger.error("Using unk_token, but it is not set yet.") return None return str(self._unk_...
`str`: Unknown token. Log an error if used while not having been set.
unk_token
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
def sep_token(self) -> str: """ `str`: Separation token, to separate context and query in an input sequence. Log an error if used while not having been set. """ if self._sep_token is None: if self.verbose: logger.error("Using sep_token, but it is not s...
`str`: Separation token, to separate context and query in an input sequence. Log an error if used while not having been set.
sep_token
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
def pad_token(self) -> str: """ `str`: Padding token. Log an error if used while not having been set. """ if self._pad_token is None: if self.verbose: logger.error("Using pad_token, but it is not set yet.") return None return str(self._pad_...
`str`: Padding token. Log an error if used while not having been set.
pad_token
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
def cls_token(self) -> str: """ `str`: Classification token, to extract a summary of an input sequence leveraging self-attention along the full depth of the model. Log an error if used while not having been set. """ if self._cls_token is None: if self.verbose: ...
`str`: Classification token, to extract a summary of an input sequence leveraging self-attention along the full depth of the model. Log an error if used while not having been set.
cls_token
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
def mask_token(self) -> str: """ `str`: Mask token, to use when training a model with masked-language modeling. Log an error if used while not having been set. """ if self._mask_token is None: if self.verbose: logger.error("Using mask_token, but it is ...
`str`: Mask token, to use when training a model with masked-language modeling. Log an error if used while not having been set.
mask_token
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
def additional_special_tokens(self) -> List[str]: """ `List[str]`: All the additional special tokens you may want to use. Log an error if used while not having been set. """ if self._additional_special_tokens is None: if self.verbose: logger.error("Usi...
`List[str]`: All the additional special tokens you may want to use. Log an error if used while not having been set.
additional_special_tokens
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
def bos_token_id(self) -> Optional[int]: """ `Optional[int]`: Id of the beginning of sentence token in the vocabulary. Returns `None` if the token has not been set. """ if self._bos_token is None: return None return self.convert_tokens_to_ids(self.bos_token)
`Optional[int]`: Id of the beginning of sentence token in the vocabulary. Returns `None` if the token has not been set.
bos_token_id
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
def eos_token_id(self) -> Optional[int]: """ `Optional[int]`: Id of the end of sentence token in the vocabulary. Returns `None` if the token has not been set. """ if self._eos_token is None: return None return self.convert_tokens_to_ids(self.eos_token)
`Optional[int]`: Id of the end of sentence token in the vocabulary. Returns `None` if the token has not been set.
eos_token_id
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
def unk_token_id(self) -> Optional[int]: """ `Optional[int]`: Id of the unknown token in the vocabulary. Returns `None` if the token has not been set. """ if self._unk_token is None: return None return self.convert_tokens_to_ids(self.unk_token)
`Optional[int]`: Id of the unknown token in the vocabulary. Returns `None` if the token has not been set.
unk_token_id
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
def sep_token_id(self) -> Optional[int]: """ `Optional[int]`: Id of the separation token in the vocabulary, to separate context and query in an input sequence. Returns `None` if the token has not been set. """ if self._sep_token is None: return None return sel...
`Optional[int]`: Id of the separation token in the vocabulary, to separate context and query in an input sequence. Returns `None` if the token has not been set.
sep_token_id
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
def pad_token_id(self) -> Optional[int]: """ `Optional[int]`: Id of the padding token in the vocabulary. Returns `None` if the token has not been set. """ if self._pad_token is None: return None return self.convert_tokens_to_ids(self.pad_token)
`Optional[int]`: Id of the padding token in the vocabulary. Returns `None` if the token has not been set.
pad_token_id
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
def cls_token_id(self) -> Optional[int]: """ `Optional[int]`: Id of the classification token in the vocabulary, to extract a summary of an input sequence leveraging self-attention along the full depth of the model. Returns `None` if the token has not been set. """ if sel...
`Optional[int]`: Id of the classification token in the vocabulary, to extract a summary of an input sequence leveraging self-attention along the full depth of the model. Returns `None` if the token has not been set.
cls_token_id
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
def mask_token_id(self) -> Optional[int]: """ `Optional[int]`: Id of the mask token in the vocabulary, used when training a model with masked-language modeling. Returns `None` if the token has not been set. """ if self._mask_token is None: return None return s...
`Optional[int]`: Id of the mask token in the vocabulary, used when training a model with masked-language modeling. Returns `None` if the token has not been set.
mask_token_id
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
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 `tokenizers.AddedToken...
`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 `tokenizers.AddedToken` type to string.
special_tokens_map
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
def special_tokens_map_extended(self) -> Dict[str, Union[str, AddedToken, List[Union[str, AddedToken]]]]: """ `Dict[str, Union[str, tokenizers.AddedToken, List[Union[str, tokenizers.AddedToken]]]]`: A dictionary mapping special token class attributes (`cls_token`, `unk_token`, etc.) to their val...
`Dict[str, Union[str, tokenizers.AddedToken, List[Union[str, tokenizers.AddedToken]]]]`: A dictionary mapping special token class attributes (`cls_token`, `unk_token`, etc.) to their values (`'<unk>'`, `'<cls>'`, etc.). Don't convert tokens of `tokenizers.AddedToken` type to string so they can...
special_tokens_map_extended
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
def all_special_tokens_extended(self) -> List[Union[str, AddedToken]]: """ `List[Union[str, tokenizers.AddedToken]]`: All the special tokens (`'<unk>'`, `'<cls>'`, etc.) mapped to class attributes. Don't convert tokens of `tokenizers.AddedToken` type to string so they can be used to con...
`List[Union[str, tokenizers.AddedToken]]`: All the special tokens (`'<unk>'`, `'<cls>'`, etc.) mapped to class attributes. 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_special_tokens_extended
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
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
`List[int]`: List the ids of the special tokens(`'<unk>'`, `'<cls>'`, etc.) mapped to class attributes.
all_special_ids
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
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...
Save the full tokenizer state. This method make sure the full tokenizer can then be re-loaded using the [`~tokenization_utils_base.PreTrainedTokenizer.from_pretrained`] class method.. Warning,None This won't save modifications you may have applied to the tokenizer after the instantia...
save_pretrained
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
def _save_pretrained( self, save_directory: Union[str, os.PathLike], file_names: Tuple[str], legacy_format: Optional[bool] = None, filename_prefix: Optional[str] = None, ) -> Tuple[str]: """ Save a tokenizer using the slow-tokenizer/legacy format: vocabulary +...
Save a tokenizer using the slow-tokenizer/legacy format: vocabulary + added tokens. 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`]
_save_pretrained
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
def encode( self, text: Union[TextInput, PreTokenizedInput, EncodedInput], text_pair: Optional[Union[TextInput, PreTokenizedInput, EncodedInput]] = None, add_special_tokens: bool = True, padding: Union[bool, str, PaddingStrategy] = False, truncation: Union[bool, str, Trun...
Converts a string to a sequence of ids (integer), using the tokenizer and vocabulary. Same as doing `self.convert_tokens_to_ids(self.tokenize(text))`. Args: text (`str`, `List[str]` or `List[int]`): The first sequence to be encoded. This can be a string, a list of ...
encode
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
def _get_padding_truncation_strategies( self, padding=False, truncation=None, max_length=None, pad_to_multiple_of=None, verbose=True, **kwargs ): """ Find the correct padding/truncation strategy with backward compatibility for old arguments (truncation_strategy and pad_to_max_length)...
Find the correct padding/truncation strategy with backward compatibility for old arguments (truncation_strategy and pad_to_max_length) and behaviors.
_get_padding_truncation_strategies
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
def __call__( self, text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None, text_pair: Optional[Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]]] = None, text_target: Union[TextInput, PreTokenizedInput, List[TextInput], Lis...
Main method to tokenize and prepare for the model one or several sequence(s) or one or several pair(s) of sequences. 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 ...
__call__
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
def encode_plus( self, text: Union[TextInput, PreTokenizedInput, EncodedInput], text_pair: Optional[Union[TextInput, PreTokenizedInput, EncodedInput]] = None, add_special_tokens: bool = True, padding: Union[bool, str, PaddingStrategy] = False, truncation: Union[bool, str,...
Tokenize and prepare for the model a sequence or a pair of sequences. <Tip warning={true}> This method is deprecated, `__call__` should be used instead. </Tip> Args: text (`str`, `List[str]` or `List[int]` (the latter only for not-fast tokenizers)): ...
encode_plus
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
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_tok...
Tokenize and prepare for the model a list of sequences or a list of pairs of sequences. <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]...
batch_encode_plus
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
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...
Pad a single encoded input or a batch of encoded inputs up to predefined length or to the max sequence length in the batch. Padding side (left/right) padding token ids are defined at the tokenizer level (with `self.padding_side`, `self.pad_token_id` and `self.pad_token_type_id`). ...
pad
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
def create_token_type_ids_from_sequences( self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None ) -> List[int]: """ Create the token type IDs corresponding to the sequences passed. [What are token type IDs?](../glossary#token-type-ids) Should be overridden in...
Create the token type IDs corresponding to the sequences passed. [What are token type IDs?](../glossary#token-type-ids) Should be overridden in a subclass if the model has a special way of building those. Args: token_ids_0 (`List[int]`): The first tokenized sequence. ...
create_token_type_ids_from_sequences
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
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...
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and adding special tokens. This implementation does not add special tokens and this method should be overridden in a subclass. Args: token_ids_0 (`List[int]`): The f...
build_inputs_with_special_tokens
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
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: Union[bool, str, TruncationStrategy] = None, max_length: Optional[int] = None, ...
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. Pleas...
prepare_for_model
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
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]]: """ ...
Truncates a sequence pair in-place following the strategy. 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]`, *o...
truncate_sequences
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
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, return_attention_mask: Optional[bool] = None, ) -...
Pad encoded inputs (on left/right and up to predefined length or max length in the batch) Args: encoded_inputs: Dictionary of tokenized inputs (`List[int]`) or batch of tokenized inputs (`List[List[int]]`). max_length: maximum length of the returned list and opt...
_pad
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
def batch_decode( self, sequences: Union[List[int], List[List[int]], "np.ndarray", "torch.Tensor", "tf.Tensor"], skip_special_tokens: bool = False, clean_up_tokenization_spaces: bool = True, **kwargs ) -> List[str]: """ Convert a list of lists of token ids int...
Convert a list of lists of token ids into a list of strings by calling decode. Args: sequences (`Union[List[int], List[List[int]], np.ndarray, torch.Tensor, tf.Tensor]`): List of tokenized input ids. Can be obtained using the `__call__` method. skip_special_toke...
batch_decode
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
def decode( self, token_ids: Union[int, List[int], "np.ndarray", "torch.Tensor", "tf.Tensor"], skip_special_tokens: bool = False, clean_up_tokenization_spaces: bool = True, **kwargs ) -> str: """ Converts a sequence of ids in a string, using the tokenizer and ...
Converts a sequence of ids in a string, using the tokenizer and vocabulary with options to remove special tokens and clean up tokenization spaces. Similar to doing `self.convert_tokens_to_string(self.convert_ids_to_tokens(token_ids))`. Args: token_ids (`Union[int, List[int...
decode
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
def clean_up_tokenization(out_string: str) -> str: """ Clean up a list of simple English tokenization artifacts like spaces before punctuations and abbreviated forms. Args: out_string (`str`): The text to clean up. Returns: `str`: The cleaned-up string. ...
Clean up a list of simple English tokenization artifacts like spaces before punctuations and abbreviated forms. Args: out_string (`str`): The text to clean up. Returns: `str`: The cleaned-up string.
clean_up_tokenization
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
def _eventual_warn_about_too_long_sequence(self, ids: List[int], max_length: Optional[int], verbose: bool): """ Depending on the input and internal state we might trigger a warning about a sequence that is too long for its corresponding model Args: ids (`List[str]`): The ids...
Depending on the input and internal state we might trigger a warning about a sequence that is too long for its corresponding model Args: ids (`List[str]`): The ids produced by the tokenization max_length (`int`, *optional*): The max_length desired (does not trigger a wa...
_eventual_warn_about_too_long_sequence
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
def as_target_tokenizer(self): """ Temporarily sets the tokenizer for encoding the targets. Useful for tokenizer associated to sequence-to-sequence models that need a slightly different processing for the labels. """ warnings.warn( "`as_target_tokenizer` is deprecated...
Temporarily sets the tokenizer for encoding the targets. Useful for tokenizer associated to sequence-to-sequence models that need a slightly different processing for the labels.
as_target_tokenizer
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
def register_for_auto_class(cls, auto_class="AutoTokenizer"): """ Register this class with a given auto class. This should only be used for custom tokenizers as the ones in the library are already mapped with `AutoTokenizer`. <Tip warning={true}> This API is experimental and ma...
Register this class with a given auto class. This should only be used for custom tokenizers as the ones in the library are already mapped with `AutoTokenizer`. <Tip warning={true}> This API is experimental and may have some slight breaking changes in the next releases. </Tip>...
register_for_auto_class
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
def prepare_seq2seq_batch( self, src_texts: List[str], tgt_texts: Optional[List[str]] = None, max_length: Optional[int] = None, max_target_length: Optional[int] = None, padding: str = "longest", return_tensors: str = None, truncation: bool = True, ...
Prepare model inputs for translation. For best performance, translate one sentence at a time. Arguments: src_texts (`List[str]`): List of documents to summarize or source language texts. tgt_texts (`list`, *optional*): List of summaries or target...
prepare_seq2seq_batch
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
def get_fast_tokenizer_file(tokenization_files: List[str]) -> str: """ Get the tokenization file to use for this version of transformers. Args: tokenization_files (`List[str]`): The list of available configuration files. Returns: `str`: The tokenization file to use. """ tokeniz...
Get the tokenization file to use for this version of transformers. Args: tokenization_files (`List[str]`): The list of available configuration files. Returns: `str`: The tokenization file to use.
get_fast_tokenizer_file
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_base.py
Apache-2.0
def get_added_vocab(self) -> Dict[str, int]: """ Returns the added tokens in the vocabulary as a dictionary of token to index. Returns: `Dict[str, int]`: The added tokens. """ base_vocab = self._tokenizer.get_vocab(with_added_tokens=False) full_vocab = self._...
Returns the added tokens in the vocabulary as a dictionary of token to index. Returns: `Dict[str, int]`: The added tokens.
get_added_vocab
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_fast.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_fast.py
Apache-2.0
def _convert_encoding( self, encoding: EncodingFast, 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...
Convert the encoding representation (from low-level HuggingFace tokenizer output) to a python Dict and a list of encodings, take care of building a batch from overflowing tokens. Overflowing tokens are converted to additional examples (like batches) so the output values of the dict are ...
_convert_encoding
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_fast.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_fast.py
Apache-2.0
def set_truncation_and_padding( self, padding_strategy: PaddingStrategy, truncation_strategy: TruncationStrategy, max_length: int, stride: int, pad_to_multiple_of: Optional[int], ): """ Define the truncation and the padding strategies for fast tokenize...
Define the truncation and the padding strategies for fast tokenizers (provided by HuggingFace tokenizers library) and restore the tokenizer settings afterwards. The provided tokenizer has no padding / truncation strategy before the managed section. If your tokenizer set a padding / tru...
set_truncation_and_padding
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_fast.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_fast.py
Apache-2.0
def _save_pretrained( self, save_directory: Union[str, os.PathLike], file_names: Tuple[str], legacy_format: Optional[bool] = None, filename_prefix: Optional[str] = None, ) -> Tuple[str]: """ Save a tokenizer using the slow-tokenizer/legacy format: vocabulary +...
Save a tokenizer using the slow-tokenizer/legacy format: vocabulary + added tokens as well as in a unique JSON file containing {config + vocab + added-tokens}.
_save_pretrained
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/tokenization_utils_fast.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/tokenization_utils_fast.py
Apache-2.0
def get_train_dataloader(self) -> DataLoader: """ Returns the training [`~torch.utils.data.DataLoader`]. Will use no sampler if `train_dataset` does not implement `__len__`, a random sampler (adapted to distributed training if necessary) otherwise. Subclass and override this me...
Returns the training [`~torch.utils.data.DataLoader`]. Will use no sampler if `train_dataset` does not implement `__len__`, a random sampler (adapted to distributed training if necessary) otherwise. Subclass and override this method if you want to inject some custom behavior.
get_train_dataloader
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer.py
Apache-2.0
def get_eval_dataloader(self, eval_dataset: Optional[Dataset] = None) -> DataLoader: """ Returns the evaluation [`~torch.utils.data.DataLoader`]. Subclass and override this method if you want to inject some custom behavior. Args: eval_dataset (`torch.utils.data.Dataset`, *o...
Returns the evaluation [`~torch.utils.data.DataLoader`]. Subclass and override this method if you want to inject some custom behavior. Args: eval_dataset (`torch.utils.data.Dataset`, *optional*): If provided, will override `self.eval_dataset`. If it is a [`~dataset...
get_eval_dataloader
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer.py
Apache-2.0
def get_test_dataloader(self, test_dataset: Dataset) -> DataLoader: """ Returns the test [`~torch.utils.data.DataLoader`]. Subclass and override this method if you want to inject some custom behavior. Args: test_dataset (`torch.utils.data.Dataset`, *optional*): ...
Returns the test [`~torch.utils.data.DataLoader`]. Subclass and override this method if you want to inject some custom behavior. Args: test_dataset (`torch.utils.data.Dataset`, *optional*): The test dataset to use. If it is a [`~datasets.Dataset`], columns not acce...
get_test_dataloader
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer.py
Apache-2.0
def create_optimizer_and_scheduler(self, num_training_steps: int): """ Setup the optimizer and the learning rate scheduler. We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the Trainer's init through `optimizers`, or subclass an...
Setup the optimizer and the learning rate scheduler. We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the Trainer's init through `optimizers`, or subclass and override this method (or `create_optimizer` and/or `create_scheduler...
create_optimizer_and_scheduler
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer.py
Apache-2.0
def get_optimizer_cls_and_kwargs(args: TrainingArguments) -> Tuple[Any, Any]: """ Returns the optimizer class and optimizer parameters based on the training arguments. Args: args (`transformers.training_args.TrainingArguments`): The training arguments for the trainin...
Returns the optimizer class and optimizer parameters based on the training arguments. Args: args (`transformers.training_args.TrainingArguments`): The training arguments for the training session.
get_optimizer_cls_and_kwargs
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer.py
Apache-2.0
def create_scheduler(self, num_training_steps: int, optimizer: torch.optim.Optimizer = None): """ Setup the scheduler. The optimizer of the trainer must have been set up either before this method is called or passed as an argument. Args: num_training_steps (int): The number ...
Setup the scheduler. The optimizer of the trainer must have been set up either before this method is called or passed as an argument. Args: num_training_steps (int): The number of training steps to do.
create_scheduler
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer.py
Apache-2.0
def train( self, resume_from_checkpoint: Optional[Union[str, bool]] = None, trial: Union["optuna.Trial", Dict[str, Any]] = None, ignore_keys_for_eval: Optional[List[str]] = None, **kwargs, ): """ Main training entry point. Args: resume_fro...
Main training entry point. Args: resume_from_checkpoint (`str` or `bool`, *optional*): If a `str`, local path to a saved checkpoint as saved by a previous instance of [`Trainer`]. If a `bool` and equals `True`, load the last checkpoint in *args.output_dir* a...
train
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer.py
Apache-2.0
def hyperparameter_search( self, hp_space: Optional[Callable[["optuna.Trial"], Dict[str, float]]] = None, compute_objective: Optional[Callable[[Dict[str, float]], float]] = None, n_trials: int = 20, direction: str = "minimize", backend: Optional[Union["str", HPSearchBacke...
Launch an hyperparameter search using `optuna` or `Ray Tune` or `SigOpt`. The optimized quantity is determined by `compute_objective`, which defaults to a function returning the evaluation loss when no metric is provided, the sum of all metrics otherwise. <Tip warning={true}> ...
hyperparameter_search
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer.py
Apache-2.0
def compute_loss_context_manager(self): """ A helper wrapper to group together context managers. """ return ContextManagers( [ self.torchdynamo_smart_context_manager(), self.autocast_smart_context_manager(), ] )
A helper wrapper to group together context managers.
compute_loss_context_manager
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer.py
Apache-2.0
def training_step(self, model: nn.Module, inputs: Dict[str, Union[torch.Tensor, Any]]) -> torch.Tensor: """ Perform a training step on a batch of inputs. Subclass and override to inject custom behavior. Args: model (`nn.Module`): The model to train. ...
Perform a training step on a batch of inputs. Subclass and override to inject custom behavior. Args: model (`nn.Module`): The model to train. inputs (`Dict[str, Union[torch.Tensor, Any]]`): The inputs and targets of the model. ...
training_step
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer.py
Apache-2.0
def compute_loss(self, model, inputs, return_outputs=False): """ How the loss is computed by Trainer. By default, all models return the loss in the first element. Subclass and override for custom behavior. """ if self.label_smoother is not None and "labels" in inputs: ...
How the loss is computed by Trainer. By default, all models return the loss in the first element. Subclass and override for custom behavior.
compute_loss
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer.py
Apache-2.0
def save_model(self, output_dir: Optional[str] = None, _internal_call: bool = False): """ Will save the model, so you can reload it using `from_pretrained()`. Will only save from the main process. """ if output_dir is None: output_dir = self.args.output_dir ...
Will save the model, so you can reload it using `from_pretrained()`. Will only save from the main process.
save_model
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer.py
Apache-2.0
def evaluate( self, eval_dataset: Optional[Dataset] = None, ignore_keys: Optional[List[str]] = None, metric_key_prefix: str = "eval", ) -> Dict[str, float]: """ Run evaluation and returns metrics. The calling script will be responsible for providing a method ...
Run evaluation and returns metrics. The calling script will be responsible for providing a method to compute metrics, as they are task-dependent (pass it to the init `compute_metrics` argument). You can also subclass and override this method to inject custom behavior. Args: ...
evaluate
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer.py
Apache-2.0
def predict( self, test_dataset: Dataset, ignore_keys: Optional[List[str]] = None, metric_key_prefix: str = "test" ) -> PredictionOutput: """ Run prediction and returns predictions and potential metrics. Depending on the dataset and your use case, your test dataset may contain label...
Run prediction and returns predictions and potential metrics. Depending on the dataset and your use case, your test dataset may contain labels. In that case, this method will also return metrics, like in `evaluate()`. Args: test_dataset (`Dataset`): Dataset...
predict
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer.py
Apache-2.0
def evaluation_loop( self, dataloader: DataLoader, description: str, prediction_loss_only: Optional[bool] = None, ignore_keys: Optional[List[str]] = None, metric_key_prefix: str = "eval", ) -> EvalLoopOutput: """ Prediction/evaluation loop, shared by `...
Prediction/evaluation loop, shared by `Trainer.evaluate()` and `Trainer.predict()`. Works both with or without labels.
evaluation_loop
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer.py
Apache-2.0
def prediction_step( self, model: nn.Module, inputs: Dict[str, Union[torch.Tensor, Any]], prediction_loss_only: bool, ignore_keys: Optional[List[str]] = None, ) -> Tuple[Optional[torch.Tensor], Optional[torch.Tensor], Optional[torch.Tensor]]: """ Perform an ev...
Perform an evaluation step on `model` using `inputs`. Subclass and override to inject custom behavior. Args: model (`nn.Module`): The model to evaluate. inputs (`Dict[str, Union[torch.Tensor, Any]]`): The inputs and targets of the model....
prediction_step
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer.py
Apache-2.0
def floating_point_ops(self, inputs: Dict[str, Union[torch.Tensor, Any]]): """ For models that inherit from [`PreTrainedModel`], uses that method to compute the number of floating point operations for every backward + forward pass. If using another model, either implement such a method in the ...
For models that inherit from [`PreTrainedModel`], uses that method to compute the number of floating point operations for every backward + forward pass. If using another model, either implement such a method in the model or subclass and override this method. Args: inputs (`...
floating_point_ops
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer.py
Apache-2.0
def init_git_repo(self, at_init: bool = False): """ Initializes a git repo in `self.args.hub_model_id`. Args: at_init (`bool`, *optional*, defaults to `False`): Whether this function is called before any training or not. If `self.args.overwrite_output_dir` is ...
Initializes a git repo in `self.args.hub_model_id`. Args: at_init (`bool`, *optional*, defaults to `False`): Whether this function is called before any training or not. If `self.args.overwrite_output_dir` is `True` and `at_init` is `True`, the path to the re...
init_git_repo
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer.py
Apache-2.0
def save_to_json(self, json_path: str): """Save the content of this instance in JSON format inside `json_path`.""" json_string = json.dumps(dataclasses.asdict(self), indent=2, sort_keys=True) + "\n" with open(json_path, "w", encoding="utf-8") as f: f.write(json_string)
Save the content of this instance in JSON format inside `json_path`.
save_to_json
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer_callback.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer_callback.py
Apache-2.0
def load_from_json(cls, json_path: str): """Create an instance from the content of `json_path`.""" with open(json_path, "r", encoding="utf-8") as f: text = f.read() return cls(**json.loads(text))
Create an instance from the content of `json_path`.
load_from_json
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer_callback.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer_callback.py
Apache-2.0
def _new_step(self): """Internal method that resets the variable for a new step.""" self.should_save = False self.should_evaluate = False self.should_log = False
Internal method that resets the variable for a new step.
_new_step
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer_callback.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer_callback.py
Apache-2.0
def torch_pad_and_concatenate(tensor1, tensor2, padding_index=-100): """Concatenates `tensor1` and `tensor2` on first axis, applying padding on the second if necessary.""" tensor1 = atleast_1d(tensor1) tensor2 = atleast_1d(tensor2) if len(tensor1.shape) == 1 or tensor1.shape[1] == tensor2.shape[1]: ...
Concatenates `tensor1` and `tensor2` on first axis, applying padding on the second if necessary.
torch_pad_and_concatenate
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer_pt_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer_pt_utils.py
Apache-2.0
def numpy_pad_and_concatenate(array1, array2, padding_index=-100): """Concatenates `array1` and `array2` on first axis, applying padding on the second if necessary.""" array1 = atleast_1d(array1) array2 = atleast_1d(array2) if len(array1.shape) == 1 or array1.shape[1] == array2.shape[1]: return...
Concatenates `array1` and `array2` on first axis, applying padding on the second if necessary.
numpy_pad_and_concatenate
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer_pt_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer_pt_utils.py
Apache-2.0