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 from_args_and_dict(cls, args, processor_dict: dict[str, Any], **kwargs): """ Instantiates a type of [`~processing_utils.ProcessingMixin`] from a Python dictionary of parameters. Args: processor_dict (`Dict[str, Any]`): Dictionary that will be used to instantiate ...
Instantiates a type of [`~processing_utils.ProcessingMixin`] from a Python dictionary of parameters. Args: processor_dict (`Dict[str, Any]`): Dictionary that will be used to instantiate the processor object. Such a dictionary can be retrieved from a pretrain...
from_args_and_dict
python
huggingface/transformers
src/transformers/processing_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/processing_utils.py
Apache-2.0
def _merge_kwargs( self, ModelProcessorKwargs: ProcessingKwargs, tokenizer_init_kwargs: Optional[dict] = None, **kwargs, ) -> dict[str, dict]: """ Method to merge dictionaries of kwargs cleanly separated by modality within a Processor instance. The order of op...
Method to merge dictionaries of kwargs cleanly separated by modality within a Processor instance. The order of operations is as follows: 1) kwargs passed as before have highest priority to preserve BC. ```python high_priority_kwargs = {"crop_size" = {"height"...
_merge_kwargs
python
huggingface/transformers
src/transformers/processing_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/processing_utils.py
Apache-2.0
def from_pretrained( cls, pretrained_model_name_or_path: Union[str, os.PathLike], cache_dir: Optional[Union[str, os.PathLike]] = None, force_download: bool = False, local_files_only: bool = False, token: Optional[Union[str, bool]] = None, revision: str = "main", ...
Instantiate a processor associated with a pretrained model. <Tip> This class method is simply calling the feature extractor [`~feature_extraction_utils.FeatureExtractionMixin.from_pretrained`], image processor [`~image_processing_utils.ImageProcessingMixin`] and the tokenizer ...
from_pretrained
python
huggingface/transformers
src/transformers/processing_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/processing_utils.py
Apache-2.0
def register_for_auto_class(cls, auto_class="AutoProcessor"): """ Register this class with a given auto class. This should only be used for custom feature extractors as the ones in the library are already mapped with `AutoProcessor`. Args: auto_class (`str` or `type`, *opt...
Register this class with a given auto class. This should only be used for custom feature extractors as the ones in the library are already mapped with `AutoProcessor`. Args: auto_class (`str` or `type`, *optional*, defaults to `"AutoProcessor"`): The auto class to...
register_for_auto_class
python
huggingface/transformers
src/transformers/processing_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/processing_utils.py
Apache-2.0
def _get_arguments_from_pretrained(cls, pretrained_model_name_or_path, **kwargs): """ Identify and instantiate the subcomponents of Processor classes, like image processors and tokenizers. This method uses the Processor attributes like `tokenizer_class` to figure out what class those sub...
Identify and instantiate the subcomponents of Processor classes, like image processors and tokenizers. This method uses the Processor attributes like `tokenizer_class` to figure out what class those subcomponents should be. Note that any subcomponents must either be library classes that are acc...
_get_arguments_from_pretrained
python
huggingface/transformers
src/transformers/processing_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/processing_utils.py
Apache-2.0
def prepare_and_validate_optional_call_args(self, *args): """ Matches optional positional arguments to their corresponding names in `optional_call_args` in the processor class in the order they are passed to the processor call. Note that this should only be used in the `__call__` method...
Matches optional positional arguments to their corresponding names in `optional_call_args` in the processor class in the order they are passed to the processor call. Note that this should only be used in the `__call__` method of the processors with special arguments. Special arguments ...
prepare_and_validate_optional_call_args
python
huggingface/transformers
src/transformers/processing_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/processing_utils.py
Apache-2.0
def _process_messages_for_chat_template( self, conversation: List[List[Dict[str, str]]], batch_images: List[ImageInput], batch_videos: List[VideoInput], batch_video_metadata: List[List[Dict[str, any]]], **mm_load_kwargs: Unpack[ChatTemplateLoadKwargs], ): """ ...
Used within `apply_chat_template` when a model has a special way to process conversation history. For example, video models might want to specify in the prompt the duration of video or which frame indices at which timestamps were sampled. This information cannot be accessed before the video is ...
_process_messages_for_chat_template
python
huggingface/transformers
src/transformers/processing_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/processing_utils.py
Apache-2.0
def apply_chat_template( self, conversation: Union[list[dict[str, str]], list[list[dict[str, str]]]], chat_template: Optional[str] = None, **kwargs: Unpack[AllKwargsForChatTemplate], ) -> str: """ Similar to the `apply_chat_template` method on tokenizers, this method ...
Similar to the `apply_chat_template` method on tokenizers, this method applies a Jinja template to input conversations to turn them into a single tokenizable string. The input is expected to be in the following format, where each message content is a list consisting of text and optiona...
apply_chat_template
python
huggingface/transformers
src/transformers/processing_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/processing_utils.py
Apache-2.0
def _load_video_for_model( self, video: Union[str, "VideoInput"], num_frames: Optional[int] = None, fps: Optional[int] = None, backend: str = "opencv", **kwargs, ) -> np.array: """ Loads `video` to a numpy array. Args: video (`str`...
Loads `video` to a numpy array. Args: video (`str` or `VideoInput`): The video to convert to the numpy array format. Can be a link to video or local path. num_frames (`int`, *optional*): Number of frames to sample uniformly. If not passed, the wh...
_load_video_for_model
python
huggingface/transformers
src/transformers/processing_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/processing_utils.py
Apache-2.0
def _check_special_mm_tokens(self, text: list[str], text_inputs: "BatchFeature", modalities: list[str]): """ Checks that number of special tokens in text and processed text is same. The count can be different if tokenized text was truncated, leading to issues in model code. """ f...
Checks that number of special tokens in text and processed text is same. The count can be different if tokenized text was truncated, leading to issues in model code.
_check_special_mm_tokens
python
huggingface/transformers
src/transformers/processing_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/processing_utils.py
Apache-2.0
def _validate_images_text_input_order(images, text): """ For backward compatibility: reverse the order of `images` and `text` inputs if they are swapped. This method should only be called for processors where `images` and `text` have been swapped for uniformization purposes. Note that this method assume...
For backward compatibility: reverse the order of `images` and `text` inputs if they are swapped. This method should only be called for processors where `images` and `text` have been swapped for uniformization purposes. Note that this method assumes that two `None` inputs are valid inputs. If this is not th...
_validate_images_text_input_order
python
huggingface/transformers
src/transformers/processing_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/processing_utils.py
Apache-2.0
def isin_mps_friendly(elements: torch.Tensor, test_elements: torch.Tensor | int) -> torch.Tensor: """ Same as `torch.isin` without flags, but MPS-friendly. We can remove this function when we stop supporting torch <= 2.3. See https://github.com/pytorch/pytorch/issues/77764#issuecomment-2067838075 Args:...
Same as `torch.isin` without flags, but MPS-friendly. We can remove this function when we stop supporting torch <= 2.3. See https://github.com/pytorch/pytorch/issues/77764#issuecomment-2067838075 Args: elements (`torch.Tensor`): Input elements test_elements (`torch.Tensor` or `int`): The e...
isin_mps_friendly
python
huggingface/transformers
src/transformers/pytorch_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/pytorch_utils.py
Apache-2.0
def compile_compatible_method_lru_cache(*lru_args, **lru_kwargs): """ LRU cache decorator from standard functools library, but with a workaround to disable caching when torchdynamo is compiling. Expected to work with class methods. """ def decorator(func): @wraps(func) def wrapper(s...
LRU cache decorator from standard functools library, but with a workaround to disable caching when torchdynamo is compiling. Expected to work with class methods.
compile_compatible_method_lru_cache
python
huggingface/transformers
src/transformers/pytorch_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/pytorch_utils.py
Apache-2.0
def is_agent_test(test_case): """ Decorator marking a test as an agent test. If RUN_TOOL_TESTS is set to a falsy value, those tests will be skipped. """ if not _run_agent_tests: return unittest.skip(reason="test is an agent test")(test_case) else: try: import pytest # We...
Decorator marking a test as an agent test. If RUN_TOOL_TESTS is set to a falsy value, those tests will be skipped.
is_agent_test
python
huggingface/transformers
src/transformers/testing_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/testing_utils.py
Apache-2.0
def apply_skip_if_not_implemented(cls): """ Class decorator to apply @skip_if_not_implemented to all test methods. """ for attr_name in dir(cls): if attr_name.startswith("test_"): attr = getattr(cls, attr_name) if callable(attr): setattr(cls, attr_name, sk...
Class decorator to apply @skip_if_not_implemented to all test methods.
apply_skip_if_not_implemented
python
huggingface/transformers
src/transformers/testing_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/testing_utils.py
Apache-2.0
def require_accelerate(test_case, min_version: str = ACCELERATE_MIN_VERSION): """ Decorator marking a test that requires accelerate. These tests are skipped when accelerate isn't installed. """ return unittest.skipUnless( is_accelerate_available(min_version), f"test requires accelerate version >...
Decorator marking a test that requires accelerate. These tests are skipped when accelerate isn't installed.
require_accelerate
python
huggingface/transformers
src/transformers/testing_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/testing_utils.py
Apache-2.0
def require_torch_greater_or_equal(version: str): """ Decorator marking a test that requires PyTorch version >= `version`. These tests are skipped when PyTorch version is less than `version`. """ def decorator(test_case): return unittest.skipUnless(is_torch_greater_or_equal(version), f"tes...
Decorator marking a test that requires PyTorch version >= `version`. These tests are skipped when PyTorch version is less than `version`.
require_torch_greater_or_equal
python
huggingface/transformers
src/transformers/testing_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/testing_utils.py
Apache-2.0
def require_huggingface_hub_greater_or_equal(version: str): """ Decorator marking a test that requires huggingface_hub version >= `version`. These tests are skipped when huggingface_hub version is less than `version`. """ def decorator(test_case): return unittest.skipUnless( is...
Decorator marking a test that requires huggingface_hub version >= `version`. These tests are skipped when huggingface_hub version is less than `version`.
require_huggingface_hub_greater_or_equal
python
huggingface/transformers
src/transformers/testing_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/testing_utils.py
Apache-2.0
def require_read_token(test_case): """ A decorator that loads the HF token for tests that require to load gated models. """ token = os.getenv("HF_HUB_READ_TOKEN") if isinstance(test_case, type): for attr_name in dir(test_case): attr = getattr(test_case, attr_name) if...
A decorator that loads the HF token for tests that require to load gated models.
require_read_token
python
huggingface/transformers
src/transformers/testing_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/testing_utils.py
Apache-2.0
def require_torch_multi_gpu(test_case): """ Decorator marking a test that requires a multi-GPU CUDA setup (in PyTorch). These tests are skipped on a machine without multiple CUDA GPUs. To run *only* the multi_gpu tests, assuming all test names contain multi_gpu: $ pytest -sv ./tests -k "multi_gpu" ...
Decorator marking a test that requires a multi-GPU CUDA setup (in PyTorch). These tests are skipped on a machine without multiple CUDA GPUs. To run *only* the multi_gpu tests, assuming all test names contain multi_gpu: $ pytest -sv ./tests -k "multi_gpu"
require_torch_multi_gpu
python
huggingface/transformers
src/transformers/testing_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/testing_utils.py
Apache-2.0
def require_torch_multi_xpu(test_case): """ Decorator marking a test that requires a multi-XPU setup (in PyTorch). These tests are skipped on a machine without multiple XPUs. To run *only* the multi_xpu tests, assuming all test names contain multi_xpu: $ pytest -sv ./tests -k "multi_xpu" """ if...
Decorator marking a test that requires a multi-XPU setup (in PyTorch). These tests are skipped on a machine without multiple XPUs. To run *only* the multi_xpu tests, assuming all test names contain multi_xpu: $ pytest -sv ./tests -k "multi_xpu"
require_torch_multi_xpu
python
huggingface/transformers
src/transformers/testing_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/testing_utils.py
Apache-2.0
def require_torch_multi_hpu(test_case): """ Decorator marking a test that requires a multi-HPU setup (in PyTorch). These tests are skipped on a machine without multiple HPUs. To run *only* the multi_hpu tests, assuming all test names contain multi_hpu: $ pytest -sv ./tests -k "multi_hpu" """ if...
Decorator marking a test that requires a multi-HPU setup (in PyTorch). These tests are skipped on a machine without multiple HPUs. To run *only* the multi_hpu tests, assuming all test names contain multi_hpu: $ pytest -sv ./tests -k "multi_hpu"
require_torch_multi_hpu
python
huggingface/transformers
src/transformers/testing_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/testing_utils.py
Apache-2.0
def require_large_cpu_ram(test_case, memory: float = 80): """Decorator marking a test that requires a CPU RAM with more than `memory` GiB of memory.""" if not is_psutil_available(): return test_case import psutil return unittest.skipUnless( psutil.virtual_memory().total / 1024**3 > mem...
Decorator marking a test that requires a CPU RAM with more than `memory` GiB of memory.
require_large_cpu_ram
python
huggingface/transformers
src/transformers/testing_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/testing_utils.py
Apache-2.0
def require_torch_large_gpu(test_case, memory: float = 20): """Decorator marking a test that requires a CUDA GPU with more than `memory` GiB of memory.""" if torch_device != "cuda": return unittest.skip(reason=f"test requires a CUDA GPU with more than {memory} GiB of memory")(test_case) return unit...
Decorator marking a test that requires a CUDA GPU with more than `memory` GiB of memory.
require_torch_large_gpu
python
huggingface/transformers
src/transformers/testing_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/testing_utils.py
Apache-2.0
def require_torch_large_accelerator(test_case, memory: float = 20): """Decorator marking a test that requires an accelerator with more than `memory` GiB of memory.""" if torch_device != "cuda" and torch_device != "xpu": return unittest.skip(reason=f"test requires a GPU or XPU with more than {memory} GiB...
Decorator marking a test that requires an accelerator with more than `memory` GiB of memory.
require_torch_large_accelerator
python
huggingface/transformers
src/transformers/testing_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/testing_utils.py
Apache-2.0
def require_torch_gpu_if_bnb_not_multi_backend_enabled(test_case): """ Decorator marking a test that requires a GPU if bitsandbytes multi-backend feature is not enabled. """ if is_bitsandbytes_available() and is_bitsandbytes_multi_backend_available(): return test_case return require_torch_gp...
Decorator marking a test that requires a GPU if bitsandbytes multi-backend feature is not enabled.
require_torch_gpu_if_bnb_not_multi_backend_enabled
python
huggingface/transformers
src/transformers/testing_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/testing_utils.py
Apache-2.0
def require_eetq(test_case): """ Decorator marking a test that requires eetq """ eetq_available = is_eetq_available() if eetq_available: try: import eetq # noqa: F401 except ImportError as exc: if "shard_checkpoint" in str(exc): # EETQ 1.0.0 i...
Decorator marking a test that requires eetq
require_eetq
python
huggingface/transformers
src/transformers/testing_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/testing_utils.py
Apache-2.0
def require_bitsandbytes(test_case): """ Decorator marking a test that requires the bitsandbytes library. Will be skipped when the library or its hard dependency torch is not installed. """ if is_bitsandbytes_available() and is_torch_available(): try: import pytest retur...
Decorator marking a test that requires the bitsandbytes library. Will be skipped when the library or its hard dependency torch is not installed.
require_bitsandbytes
python
huggingface/transformers
src/transformers/testing_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/testing_utils.py
Apache-2.0
def require_flute_hadamard(test_case): """ Decorator marking a test that requires higgs and hadamard """ return unittest.skipUnless( is_flute_available() and is_hadamard_available(), "test requires flute and fast_hadamard_transform" )(test_case)
Decorator marking a test that requires higgs and hadamard
require_flute_hadamard
python
huggingface/transformers
src/transformers/testing_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/testing_utils.py
Apache-2.0
def evaluate_side_effect_factory( side_effect_values: list[dict[str, float]], ) -> Generator[dict[str, float], None, None]: """ Function that returns side effects for the _evaluate method. Used when we're unsure of exactly how many times _evaluate will be called. """ yield from side_effect_value...
Function that returns side effects for the _evaluate method. Used when we're unsure of exactly how many times _evaluate will be called.
evaluate_side_effect_factory
python
huggingface/transformers
src/transformers/testing_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/testing_utils.py
Apache-2.0
def LoggingLevel(level): """ This is a context manager to temporarily change transformers modules logging level to the desired value and have it restored to the original setting at the end of the scope. Example: ```python with LoggingLevel(logging.INFO): AutoModel.from_pretrained("open...
This is a context manager to temporarily change transformers modules logging level to the desired value and have it restored to the original setting at the end of the scope. Example: ```python with LoggingLevel(logging.INFO): AutoModel.from_pretrained("openai-community/gpt2") # calls log...
LoggingLevel
python
huggingface/transformers
src/transformers/testing_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/testing_utils.py
Apache-2.0
def python_one_liner_max_rss(self, one_liner_str): """ Runs the passed python one liner (just the code) and returns how much max cpu memory was used to run the program. Args: one_liner_str (`string`): a python one liner code that gets passed to `python -c` ...
Runs the passed python one liner (just the code) and returns how much max cpu memory was used to run the program. Args: one_liner_str (`string`): a python one liner code that gets passed to `python -c` Returns: max cpu memory bytes used to run t...
python_one_liner_max_rss
python
huggingface/transformers
src/transformers/testing_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/testing_utils.py
Apache-2.0
def is_flaky(max_attempts: int = 5, wait_before_retry: Optional[float] = None, description: Optional[str] = None): """ To decorate flaky tests. They will be retried on failures. Please note that our push tests use `pytest-rerunfailures`, which prompts the CI to rerun certain types of failed tests. More...
To decorate flaky tests. They will be retried on failures. Please note that our push tests use `pytest-rerunfailures`, which prompts the CI to rerun certain types of failed tests. More specifically, if the test exception contains any substring in `FLAKY_TEST_FAILURE_PATTERNS` (in `.circleci/create_cir...
is_flaky
python
huggingface/transformers
src/transformers/testing_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/testing_utils.py
Apache-2.0
def hub_retry(max_attempts: int = 5, wait_before_retry: Optional[float] = 2): """ To decorate tests that download from the Hub. They can fail due to a variety of network issues such as timeouts, connection resets, etc. Args: max_attempts (`int`, *optional*, defaults to 5): The maxim...
To decorate tests that download from the Hub. They can fail due to a variety of network issues such as timeouts, connection resets, etc. Args: max_attempts (`int`, *optional*, defaults to 5): The maximum number of attempts to retry the flaky test. wait_before_retry (`float`, *o...
hub_retry
python
huggingface/transformers
src/transformers/testing_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/testing_utils.py
Apache-2.0
def run_test_using_subprocess(func): """ To decorate a test to run in a subprocess using the `subprocess` module. This could avoid potential GPU memory issues (GPU OOM or a test that causes many subsequential failing with `CUDA error: device-side assert triggered`). """ import pytest @functools...
To decorate a test to run in a subprocess using the `subprocess` module. This could avoid potential GPU memory issues (GPU OOM or a test that causes many subsequential failing with `CUDA error: device-side assert triggered`).
run_test_using_subprocess
python
huggingface/transformers
src/transformers/testing_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/testing_utils.py
Apache-2.0
def score(key: DeviceProperties, other: DeviceProperties) -> int: """ Returns score indicating how similar two instances of the `Properties` tuple are. Points are calculated using bits, but documented as int. Rules are as follows: * Matching `type` gives 8 points. ...
Returns score indicating how similar two instances of the `Properties` tuple are. Points are calculated using bits, but documented as int. Rules are as follows: * Matching `type` gives 8 points. * Semi-matching `type`, for example cuda and rocm, gives 4 points. ...
score
python
huggingface/transformers
src/transformers/testing_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/testing_utils.py
Apache-2.0
def scaled_dot_product_attention( query, key, value, attn_mask=None, dropout_p=0.0, is_causal=False, scale: Optional[float] = None ): """TF equivalent for torch's nn.functional.scaled_dot_product_attention""" if dropout_p != 0.0: raise ValueError( "Dropout is not supported in this implem...
TF equivalent for torch's nn.functional.scaled_dot_product_attention
scaled_dot_product_attention
python
huggingface/transformers
src/transformers/tf_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/tf_utils.py
Apache-2.0
def extensions(self, prefix: str): """ Generates all extensions of a given prefix token in the Trie. Example: ```python >>> trie = Trie() >>> trie.add("apple") >>> trie.add("app") >>> trie.add("application") >>> trie.extensions("app") ['a...
Generates all extensions of a given prefix token in the Trie. Example: ```python >>> trie = Trie() >>> trie.add("apple") >>> trie.add("app") >>> trie.add("application") >>> trie.extensions("app") ['app', 'apple', 'application'] ``` ...
extensions
python
huggingface/transformers
src/transformers/tokenization_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/tokenization_utils.py
Apache-2.0
def _get_node(self, token: str) -> dict: """ Retrieves the node corresponding to the given token in the Trie. Args: token (str): The token for which the corresponding node needs to be retrieved. Returns: dict: The node in the Trie corresponding to the given toke...
Retrieves the node corresponding to the given token in the Trie. Args: token (str): The token for which the corresponding node needs to be retrieved. Returns: dict: The node in the Trie corresponding to the given token.
_get_node
python
huggingface/transformers
src/transformers/tokenization_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/tokenization_utils.py
Apache-2.0
def _collect_tokens(self, node: dict) -> list: """ Generates all tokens in the Trie starting from a given node. Args: node (dict): The node in the Trie from which tokens need to be generated. Returns: list: List of tokens generated from the given node. "...
Generates all tokens in the Trie starting from a given node. Args: node (dict): The node in the Trie from which tokens need to be generated. Returns: list: List of tokens generated from the given node.
_collect_tokens
python
huggingface/transformers
src/transformers/tokenization_utils.py
https://github.com/huggingface/transformers/blob/master/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. Special ...
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. Special tokens are sometimes already in the vocab which is why they have to be handled specifically. Args: ...
_add_tokens
python
huggingface/transformers
src/transformers/tokenization_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/tokenization_utils.py
Apache-2.0
def tokenize(self, text: TextInput, **kwargs) -> list[str]: """ Converts a string into 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. A...
Converts a string into 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 encod...
tokenize
python
huggingface/transformers
src/transformers/tokenization_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/tokenization_utils.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
huggingface/transformers
src/transformers/tokenization_utils_base.py
https://github.com/huggingface/transformers/blob/master/src/transformers/tokenization_utils_base.py
Apache-2.0
def to(self, device: Union[str, "torch.device"], *, non_blocking: bool = False) -> "BatchEncoding": """ Send all values to device by calling `v.to(device, non_blocking=non_blocking)` (PyTorch only). Args: device (`str` or `torch.device`): The device to put the tensors on. ...
Send all values to device by calling `v.to(device, non_blocking=non_blocking)` (PyTorch only). Args: device (`str` or `torch.device`): The device to put the tensors on. non_blocking (`bool`): Whether to perform the copy asynchronously. Returns: [`BatchEncod...
to
python
huggingface/transformers
src/transformers/tokenization_utils_base.py
https://github.com/huggingface/transformers/blob/master/src/transformers/tokenization_utils_base.py
Apache-2.0
def add_special_tokens( self, special_tokens_dict: Dict[str, Union[str, AddedToken, Sequence[Union[str, AddedToken]]]], replace_additional_special_tokens=True, ) -> int: """ Add a dictionary of special tokens (eos, pad, cls, etc.) to the encoder and link them to class attribu...
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). When adding new tokens to the vocabulary, you s...
add_special_tokens
python
huggingface/transformers
src/transformers/tokenization_utils_base.py
https://github.com/huggingface/transformers/blob/master/src/transformers/tokenization_utils_base.py
Apache-2.0
def add_tokens( self, new_tokens: Union[str, AddedToken, Sequence[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 ...
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 will be isolated before the tokenization algorithm is applied. Added tokens and tokens from the vocabulary of the to...
add_tokens
python
huggingface/transformers
src/transformers/tokenization_utils_base.py
https://github.com/huggingface/transformers/blob/master/src/transformers/tokenization_utils_base.py
Apache-2.0
def _set_model_specific_special_tokens(self, special_tokens: List[str]): """ Adds new special tokens to the "SPECIAL_TOKENS_ATTRIBUTES" list which will be part of "self.special_tokens" and saved as a special token in tokenizer's config. This allows us to dynamically add new model-type sp...
Adds new special tokens to the "SPECIAL_TOKENS_ATTRIBUTES" list which will be part of "self.special_tokens" and saved as a special token in tokenizer's config. This allows us to dynamically add new model-type specific tokens after initializing the tokenizer. For example: if the model to...
_set_model_specific_special_tokens
python
huggingface/transformers
src/transformers/tokenization_utils_base.py
https://github.com/huggingface/transformers/blob/master/src/transformers/tokenization_utils_base.py
Apache-2.0
def apply_chat_template( self, conversation: Union[List[Dict[str, str]], List[List[Dict[str, str]]]], tools: Optional[List[Union[Dict, Callable]]] = None, documents: Optional[List[Dict[str, str]]] = None, chat_template: Optional[str] = None, add_generation_prompt: bool = ...
Converts a list of dictionaries with `"role"` and `"content"` keys to a list of token ids. This method is intended for use with chat models, and will read the tokenizer's chat_template attribute to determine the format and control tokens to use when converting. Args: conver...
apply_chat_template
python
huggingface/transformers
src/transformers/tokenization_utils_base.py
https://github.com/huggingface/transformers/blob/master/src/transformers/tokenization_utils_base.py
Apache-2.0
def get_chat_template(self, chat_template: Optional[str] = None, tools: Optional[List[Dict]] = None) -> str: """ Retrieve the chat template string used for tokenizing chat messages. This template is used internally by the `apply_chat_template` method and can also be used externally to retrieve t...
Retrieve the chat template string used for tokenizing chat messages. This template is used internally by the `apply_chat_template` method and can also be used externally to retrieve the model's chat template for better generation tracking. Args: chat_template (`str`, *optio...
get_chat_template
python
huggingface/transformers
src/transformers/tokenization_utils_base.py
https://github.com/huggingface/transformers/blob/master/src/transformers/tokenization_utils_base.py
Apache-2.0
def save_chat_templates( self, save_directory: Union[str, os.PathLike], tokenizer_config: dict, filename_prefix: Optional[str], save_jinja_files: bool, ): """ Writes chat templates out to the save directory if we're using the new format, and removes them from ...
Writes chat templates out to the save directory if we're using the new format, and removes them from the tokenizer config if present. If we're using the legacy format, it doesn't write any files, and instead writes the templates to the tokenizer config in the correct format.
save_chat_templates
python
huggingface/transformers
src/transformers/tokenization_utils_base.py
https://github.com/huggingface/transformers/blob/master/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 """ # Backward compatibility for previous behavior, maybe we should deprecate it...
Find the correct padding/truncation strategy
_get_padding_truncation_strategies
python
huggingface/transformers
src/transformers/tokenization_utils_base.py
https://github.com/huggingface/transformers/blob/master/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 (for non-fast tokenizers) `List[int]`): The first seq...
encode_plus
python
huggingface/transformers
src/transformers/tokenization_utils_base.py
https://github.com/huggingface/transformers/blob/master/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
huggingface/transformers
src/transformers/tokenization_utils_base.py
https://github.com/huggingface/transformers/blob/master/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
huggingface/transformers
src/transformers/tokenization_utils_base.py
https://github.com/huggingface/transformers/blob/master/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, padding_side: Optional[str] = None, return_at...
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
huggingface/transformers
src/transformers/tokenization_utils_base.py
https://github.com/huggingface/transformers/blob/master/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`. Args: auto_class (`str` or `type`, *optional*, ...
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`. Args: auto_class (`str` or `type`, *optional*, defaults to `"AutoTokenizer"`): The auto class to registe...
register_for_auto_class
python
huggingface/transformers
src/transformers/tokenization_utils_base.py
https://github.com/huggingface/transformers/blob/master/src/transformers/tokenization_utils_base.py
Apache-2.0
def can_save_slow_tokenizer(self) -> bool: """ `bool`: Whether or not the slow tokenizer can be saved. For a sentencepiece based slow tokenizer, this can only be `True` if the original `"sentencepiece.model"` was not deleted. """ if "vocab_file" in self.vocab_files_names and self...
`bool`: Whether or not the slow tokenizer can be saved. For a sentencepiece based slow tokenizer, this can only be `True` if the original `"sentencepiece.model"` was not deleted.
can_save_slow_tokenizer
python
huggingface/transformers
src/transformers/tokenization_utils_fast.py
https://github.com/huggingface/transformers/blob/master/src/transformers/tokenization_utils_fast.py
Apache-2.0
def convert_tokens_to_ids(self, tokens: Union[str, Iterable[str]]) -> Union[int, list[int]]: """ Converts a token string (or a sequence of tokens) in a single integer id (or a Iterable of ids), using the vocabulary. Args: tokens (`str` or `Iterable[str]`): One or several tok...
Converts a token string (or a sequence of tokens) in a single integer id (or a Iterable of ids), using the vocabulary. Args: tokens (`str` or `Iterable[str]`): One or several token(s) to convert to token id(s). Returns: `int` or `List[int]`: The token id or lis...
convert_tokens_to_ids
python
huggingface/transformers
src/transformers/tokenization_utils_fast.py
https://github.com/huggingface/transformers/blob/master/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], padding_side: Optional[str], ): """ Define the truncation and the...
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
huggingface/transformers
src/transformers/tokenization_utils_fast.py
https://github.com/huggingface/transformers/blob/master/src/transformers/tokenization_utils_fast.py
Apache-2.0
def get_eval_dataloader(self, eval_dataset: Optional[Union[str, 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 (`str` or `torch.ut...
Returns the evaluation [`~torch.utils.data.DataLoader`]. Subclass and override this method if you want to inject some custom behavior. Args: eval_dataset (`str` or `torch.utils.data.Dataset`, *optional*): If a `str`, will use `self.eval_dataset[eval_dataset]` as th...
get_eval_dataloader
python
huggingface/transformers
src/transformers/trainer.py
https://github.com/huggingface/transformers/blob/master/src/transformers/trainer.py
Apache-2.0
def get_learning_rates(self): """ Returns the learning rate of each parameter from self.optimizer. """ if self.optimizer is None: raise ValueError("Trainer optimizer is None, please make sure you have setup the optimizer before.") return [group["lr"] for group in self...
Returns the learning rate of each parameter from self.optimizer.
get_learning_rates
python
huggingface/transformers
src/transformers/trainer.py
https://github.com/huggingface/transformers/blob/master/src/transformers/trainer.py
Apache-2.0
def get_optimizer_group(self, param: Optional[Union[str, torch.nn.parameter.Parameter]] = None): """ Returns optimizer group for a parameter if given, else returns all optimizer groups for params. Args: param (`str` or `torch.nn.parameter.Parameter`, *optional*): The...
Returns optimizer group for a parameter if given, else returns all optimizer groups for params. Args: param (`str` or `torch.nn.parameter.Parameter`, *optional*): The parameter for which optimizer group needs to be returned.
get_optimizer_group
python
huggingface/transformers
src/transformers/trainer.py
https://github.com/huggingface/transformers/blob/master/src/transformers/trainer.py
Apache-2.0
def setup_low_rank_optimizer( optimizer_name: str, optimizer_mapping: dict[str, Any], optim_kwargs: dict[str, Any], is_layerwise_supported: bool = True, ) -> tuple[Any, Any]: """ Helper function to set up low-rank optimizers like GaLore and...
Helper function to set up low-rank optimizers like GaLore and Apollo. Args: optimizer_name (str): Name of the optimizer. optimizer_mapping (dict): Mapping of optimizer names to their classes. optim_kwargs (dict): Keyword arguments for the optimiz...
setup_low_rank_optimizer
python
huggingface/transformers
src/transformers/trainer.py
https://github.com/huggingface/transformers/blob/master/src/transformers/trainer.py
Apache-2.0
def get_tp_size(self) -> int: """Get the tensor parallel size from either the model or DeepSpeed config.""" # 1. Check model.tp_size first if (model_tp := getattr(self.model, "_tp_size", None)) is not None: return model_tp # 2. Fall back to DeepSpeed config if enabled ...
Get the tensor parallel size from either the model or DeepSpeed config.
get_tp_size
python
huggingface/transformers
src/transformers/trainer.py
https://github.com/huggingface/transformers/blob/master/src/transformers/trainer.py
Apache-2.0
def get_total_train_batch_size(self, args) -> int: """Calculates total batch size (micro_batch * grad_accum * dp_world_size). Note: Only considers DP and TP (dp_world_size = world_size // tp_size).""" dp_world_size = args.world_size // self.get_tp_size() return self._train_batch_size * ...
Calculates total batch size (micro_batch * grad_accum * dp_world_size). Note: Only considers DP and TP (dp_world_size = world_size // tp_size).
get_total_train_batch_size
python
huggingface/transformers
src/transformers/trainer.py
https://github.com/huggingface/transformers/blob/master/src/transformers/trainer.py
Apache-2.0
def _determine_best_metric(self, metrics, trial): """ Determine if the model should be saved based on the evaluation metrics. Returns: bool: True if a new best metric was found, else False """ is_new_best_metric = False if self.args.metric_for_best_model is ...
Determine if the model should be saved based on the evaluation metrics. Returns: bool: True if a new best metric was found, else False
_determine_best_metric
python
huggingface/transformers
src/transformers/trainer.py
https://github.com/huggingface/transformers/blob/master/src/transformers/trainer.py
Apache-2.0
def _load_scaler(self, checkpoint): """If scaler state exists, load it.""" if checkpoint is None: return checkpoint_file_exists = os.path.isfile(os.path.join(checkpoint, SCALER_NAME)) if checkpoint_file_exists: # On TPU we have to take some extra precautions to ...
If scaler state exists, load it.
_load_scaler
python
huggingface/transformers
src/transformers/trainer.py
https://github.com/huggingface/transformers/blob/master/src/transformers/trainer.py
Apache-2.0
def _load_callback_state(self): """If callback states exist and were passed in, restore their states if enabled""" if not self.args.restore_callback_states_from_checkpoint: return # Callback states are stored in stateful_callbacks not_found = [] new_callbacks = [] ...
If callback states exist and were passed in, restore their states if enabled
_load_callback_state
python
huggingface/transformers
src/transformers/trainer.py
https://github.com/huggingface/transformers/blob/master/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: Union[str, list[str]] = "minimize", backend: Optional[Union["s...
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
huggingface/transformers
src/transformers/trainer.py
https://github.com/huggingface/transformers/blob/master/src/transformers/trainer.py
Apache-2.0
def log(self, logs: dict[str, float], start_time: Optional[float] = None) -> None: """ Log `logs` on the various objects watching training. Subclass and override this method to inject custom behavior. Args: logs (`Dict[str, float]`): The values to log. ...
Log `logs` on the various objects watching training. Subclass and override this method to inject custom behavior. Args: logs (`Dict[str, float]`): The values to log. start_time (`Optional[float]`): The start of training.
log
python
huggingface/transformers
src/transformers/trainer.py
https://github.com/huggingface/transformers/blob/master/src/transformers/trainer.py
Apache-2.0
def evaluate( self, eval_dataset: Optional[Union[Dataset, dict[str, 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 responsi...
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
huggingface/transformers
src/transformers/trainer.py
https://github.com/huggingface/transformers/blob/master/src/transformers/trainer.py
Apache-2.0
def propagate_args_to_deepspeed(self, auto_find_batch_size=False): """ Sets values in the deepspeed plugin based on the Trainer args """ from transformers.integrations.deepspeed import HfTrainerDeepSpeedConfig ds_plugin = self.accelerator.state.deepspeed_plugin ds_plugi...
Sets values in the deepspeed plugin based on the Trainer args
propagate_args_to_deepspeed
python
huggingface/transformers
src/transformers/trainer.py
https://github.com/huggingface/transformers/blob/master/src/transformers/trainer.py
Apache-2.0
def set_initial_training_values( self, args: TrainingArguments, dataloader: DataLoader, total_train_batch_size: int ): """ Calculates and returns the following values: - `num_train_epochs` - `num_update_steps_per_epoch` - `num_examples` - `num_train_samples` ...
Calculates and returns the following values: - `num_train_epochs` - `num_update_steps_per_epoch` - `num_examples` - `num_train_samples` - `epoch_based` - `len_dataloader` - `max_steps`
set_initial_training_values
python
huggingface/transformers
src/transformers/trainer.py
https://github.com/huggingface/transformers/blob/master/src/transformers/trainer.py
Apache-2.0
def compute_steps(self, args, max_steps): """ Calculates and stores the absolute value for logging, eval, and save steps based on if it was a proportion or not. """ for step_kind in ("logging", "eval", "save"): num_steps = getattr(args, f"{step_kind}_steps") ...
Calculates and stores the absolute value for logging, eval, and save steps based on if it was a proportion or not.
compute_steps
python
huggingface/transformers
src/transformers/trainer_callback.py
https://github.com/huggingface/transformers/blob/master/src/transformers/trainer_callback.py
Apache-2.0
def init_training_references(self, trainer, max_steps, num_train_epochs, trial): """ Stores the initial training references needed in `self` """ if trainer.hp_name is not None and trainer._trial is not None: # use self._trial because the SigOpt/Optuna hpo only call `_hp_searc...
Stores the initial training references needed in `self`
init_training_references
python
huggingface/transformers
src/transformers/trainer_callback.py
https://github.com/huggingface/transformers/blob/master/src/transformers/trainer_callback.py
Apache-2.0
def __init__(self, max_str_len: int = 100): """ Initialize the callback with optional max_str_len parameter to control string truncation length. Args: max_str_len (`int`): Maximum length of strings to display in logs. Longer strings will be truncated ...
Initialize the callback with optional max_str_len parameter to control string truncation length. Args: max_str_len (`int`): Maximum length of strings to display in logs. Longer strings will be truncated with a message.
__init__
python
huggingface/transformers
src/transformers/trainer_callback.py
https://github.com/huggingface/transformers/blob/master/src/transformers/trainer_callback.py
Apache-2.0
def add(self, tensors) -> None: """Add tensors to the stored objects. If `do_nested_concat=True`, the tensors will be concatenated recursively.""" if self.tensors is None: self.tensors = tensors if self.do_nested_concat else [tensors] elif self.do_nested_concat: self.tens...
Add tensors to the stored objects. If `do_nested_concat=True`, the tensors will be concatenated recursively.
add
python
huggingface/transformers
src/transformers/trainer_pt_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/trainer_pt_utils.py
Apache-2.0
def to_cpu_and_numpy(self) -> None: """Move tensors in stored objects to CPU and convert them to numpy arrays.""" # Check if we have something to add, if not just return if self.tensors is None: return new_arrays = nested_numpify(self.tensors) if self.arrays is None...
Move tensors in stored objects to CPU and convert them to numpy arrays.
to_cpu_and_numpy
python
huggingface/transformers
src/transformers/trainer_pt_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/trainer_pt_utils.py
Apache-2.0
def metrics_format(self, metrics: dict[str, float]) -> dict[str, float]: """ Reformat Trainer metrics values to a human-readable format. Args: metrics (`Dict[str, float]`): The metrics returned from train/evaluate/predict Returns: metrics (`Dict[str, float]`): The reformatt...
Reformat Trainer metrics values to a human-readable format. Args: metrics (`Dict[str, float]`): The metrics returned from train/evaluate/predict Returns: metrics (`Dict[str, float]`): The reformatted metrics
metrics_format
python
huggingface/transformers
src/transformers/trainer_pt_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/trainer_pt_utils.py
Apache-2.0
def log_metrics(self, split, metrics): """ Log metrics in a specially formatted way. Under distributed environment this is done only for a process with rank 0. Args: split (`str`): Mode/split name: one of `train`, `eval`, `test` metrics (`Dict[str, float]`): The...
Log metrics in a specially formatted way. Under distributed environment this is done only for a process with rank 0. Args: split (`str`): Mode/split name: one of `train`, `eval`, `test` metrics (`Dict[str, float]`): The metrics returned from train/evaluate/predictm...
log_metrics
python
huggingface/transformers
src/transformers/trainer_pt_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/trainer_pt_utils.py
Apache-2.0
def save_state(self): """ Saves the Trainer state, since Trainer.save_model saves only the tokenizer with the model. Under distributed environment this is done only for a process with rank 0. """ if not self.is_world_process_zero(): return path = os.path.join(self.args.output_dir, "tra...
Saves the Trainer state, since Trainer.save_model saves only the tokenizer with the model. Under distributed environment this is done only for a process with rank 0.
save_state
python
huggingface/transformers
src/transformers/trainer_pt_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/trainer_pt_utils.py
Apache-2.0
def get_model_param_count(model, trainable_only=False): """ Calculate model's total param count. If trainable_only is True then count only those requiring grads. """ if is_deepspeed_zero3_enabled(): def numel(p): return p.ds_numel if hasattr(p, "ds_numel") else p.numel() else: ...
Calculate model's total param count. If trainable_only is True then count only those requiring grads.
get_model_param_count
python
huggingface/transformers
src/transformers/trainer_pt_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/trainer_pt_utils.py
Apache-2.0
def set_rng_state_for_device(device_name, device_module, checkpoint_rng_state, is_distributed): """Helper to set RNG state for a specific device type (CUDA, NPU, MLU, MUSA)""" device_state_key = device_name.lower() err_template = "Didn't manage to set back the RNG states of the {backend} because of the foll...
Helper to set RNG state for a specific device type (CUDA, NPU, MLU, MUSA)
set_rng_state_for_device
python
huggingface/transformers
src/transformers/trainer_pt_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/trainer_pt_utils.py
Apache-2.0
def load_generation_config(gen_config_arg: Union[str, GenerationConfig]) -> GenerationConfig: """ Loads a `~generation.GenerationConfig` from the `Seq2SeqTrainingArguments.generation_config` arguments. Args: gen_config_arg (`str` or [`~generation.GenerationConfig]`): ...
Loads a `~generation.GenerationConfig` from the `Seq2SeqTrainingArguments.generation_config` arguments. Args: gen_config_arg (`str` or [`~generation.GenerationConfig]`): `Seq2SeqTrainingArguments.generation_config` argument. Returns: A `~generation.Gene...
load_generation_config
python
huggingface/transformers
src/transformers/trainer_seq2seq.py
https://github.com/huggingface/transformers/blob/master/src/transformers/trainer_seq2seq.py
Apache-2.0
def set_seed(seed: int, deterministic: bool = False): """ Helper function for reproducible behavior to set the seed in `random`, `numpy`, `torch` and/or `tf` (if installed). Args: seed (`int`): The seed to set. deterministic (`bool`, *optional*, defaults to `False`): ...
Helper function for reproducible behavior to set the seed in `random`, `numpy`, `torch` and/or `tf` (if installed). Args: seed (`int`): The seed to set. deterministic (`bool`, *optional*, defaults to `False`): Whether to use deterministic algorithms where available. Can...
set_seed
python
huggingface/transformers
src/transformers/trainer_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/trainer_utils.py
Apache-2.0
def is_main_process(local_rank): """ Whether or not the current process is the local process, based on `xr.global_ordinal()` (for TPUs) first, then on `local_rank`. """ if is_torch_xla_available(): import torch_xla.runtime as xr return xr.global_ordinal() == 0 return local_rank ...
Whether or not the current process is the local process, based on `xr.global_ordinal()` (for TPUs) first, then on `local_rank`.
is_main_process
python
huggingface/transformers
src/transformers/trainer_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/trainer_utils.py
Apache-2.0
def speed_metrics(split, start_time, num_samples=None, num_steps=None, num_tokens=None): """ Measure and return speed performance metrics. This function requires a time snapshot `start_time` before the operation to be measured starts and this function should be run immediately after the operation to be...
Measure and return speed performance metrics. This function requires a time snapshot `start_time` before the operation to be measured starts and this function should be run immediately after the operation to be measured has completed. Args: - split: name to prefix metric (like train, eval, test.....
speed_metrics
python
huggingface/transformers
src/transformers/trainer_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/trainer_utils.py
Apache-2.0
def check_target_module_exists(optim_target_modules, key: str, return_is_regex: bool = False): """A helper method to check if the passed module's key name matches any of the target modules in the optim_target_modules. Args: optim_target_modules (`Union[str, List[str]]`): A list of strings t...
A helper method to check if the passed module's key name matches any of the target modules in the optim_target_modules. Args: optim_target_modules (`Union[str, List[str]]`): A list of strings to try to match. Can be also a full string. key (`str`): A key to search any matche...
check_target_module_exists
python
huggingface/transformers
src/transformers/trainer_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/trainer_utils.py
Apache-2.0
def _convert_str_dict(passed_value: dict): "Safely checks that a passed value is a dictionary and converts any string values to their appropriate types." for key, value in passed_value.items(): if isinstance(value, dict): passed_value[key] = _convert_str_dict(value) elif isinstance(v...
Safely checks that a passed value is a dictionary and converts any string values to their appropriate types.
_convert_str_dict
python
huggingface/transformers
src/transformers/training_args.py
https://github.com/huggingface/transformers/blob/master/src/transformers/training_args.py
Apache-2.0
def set_training( self, learning_rate: float = 5e-5, batch_size: int = 8, weight_decay: float = 0, num_epochs: float = 3, max_steps: int = -1, gradient_accumulation_steps: int = 1, seed: int = 42, gradient_checkpointing: bool = False, ): ...
A method that regroups all basic arguments linked to the training. <Tip> Calling this method will automatically set `self.do_train` to `True`. </Tip> Args: learning_rate (`float`, *optional*, defaults to 5e-5): The initial learning rate for the op...
set_training
python
huggingface/transformers
src/transformers/training_args.py
https://github.com/huggingface/transformers/blob/master/src/transformers/training_args.py
Apache-2.0
def set_evaluate( self, strategy: Union[str, IntervalStrategy] = "no", steps: int = 500, batch_size: int = 8, accumulation_steps: Optional[int] = None, delay: Optional[float] = None, loss_only: bool = False, jit_mode: bool = False, ): """ ...
A method that regroups all arguments linked to evaluation. Args: strategy (`str` or [`~trainer_utils.IntervalStrategy`], *optional*, defaults to `"no"`): The evaluation strategy to adopt during training. Possible values are: - `"no"`: No evaluation is d...
set_evaluate
python
huggingface/transformers
src/transformers/training_args.py
https://github.com/huggingface/transformers/blob/master/src/transformers/training_args.py
Apache-2.0
def set_logging( self, strategy: Union[str, IntervalStrategy] = "steps", steps: int = 500, report_to: Union[str, list[str]] = "none", level: str = "passive", first_step: bool = False, nan_inf_filter: bool = False, on_each_node: bool = False, replic...
A method that regroups all arguments linked to logging. Args: strategy (`str` or [`~trainer_utils.IntervalStrategy`], *optional*, defaults to `"steps"`): The logging strategy to adopt during training. Possible values are: - `"no"`: No logging is done du...
set_logging
python
huggingface/transformers
src/transformers/training_args.py
https://github.com/huggingface/transformers/blob/master/src/transformers/training_args.py
Apache-2.0
def set_push_to_hub( self, model_id: str, strategy: Union[str, HubStrategy] = "every_save", token: Optional[str] = None, private_repo: Optional[bool] = None, always_push: bool = False, ): """ A method that regroups all arguments linked to synchronizing...
A method that regroups all arguments linked to synchronizing checkpoints with the Hub. <Tip> Calling this method will set `self.push_to_hub` to `True`, which means the `output_dir` will begin a git directory synced with the repo (determined by `model_id`) and the content will be pushe...
set_push_to_hub
python
huggingface/transformers
src/transformers/training_args.py
https://github.com/huggingface/transformers/blob/master/src/transformers/training_args.py
Apache-2.0
def set_optimizer( self, name: Union[str, OptimizerNames] = "adamw_torch", learning_rate: float = 5e-5, weight_decay: float = 0, beta1: float = 0.9, beta2: float = 0.999, epsilon: float = 1e-8, args: Optional[str] = None, ): """ A metho...
A method that regroups all arguments linked to the optimizer and its hyperparameters. Args: name (`str` or [`training_args.OptimizerNames`], *optional*, defaults to `"adamw_torch"`): The optimizer to use: `"adamw_torch"`, `"adamw_torch_fused"`, `"adamw_apex_fused"`, ...
set_optimizer
python
huggingface/transformers
src/transformers/training_args.py
https://github.com/huggingface/transformers/blob/master/src/transformers/training_args.py
Apache-2.0
def set_lr_scheduler( self, name: Union[str, SchedulerType] = "linear", num_epochs: float = 3.0, max_steps: int = -1, warmup_ratio: float = 0, warmup_steps: int = 0, ): """ A method that regroups all arguments linked to the learning rate scheduler and ...
A method that regroups all arguments linked to the learning rate scheduler and its hyperparameters. Args: name (`str` or [`SchedulerType`], *optional*, defaults to `"linear"`): The scheduler type to use. See the documentation of [`SchedulerType`] for all possible values. ...
set_lr_scheduler
python
huggingface/transformers
src/transformers/training_args.py
https://github.com/huggingface/transformers/blob/master/src/transformers/training_args.py
Apache-2.0
def set_dataloader( self, train_batch_size: int = 8, eval_batch_size: int = 8, drop_last: bool = False, num_workers: int = 0, pin_memory: bool = True, persistent_workers: bool = False, prefetch_factor: Optional[int] = None, auto_find_batch_size: bo...
A method that regroups all arguments linked to the dataloaders creation. Args: drop_last (`bool`, *optional*, defaults to `False`): Whether to drop the last incomplete batch (if the length of the dataset is not divisible by the batch size) or not. ...
set_dataloader
python
huggingface/transformers
src/transformers/training_args.py
https://github.com/huggingface/transformers/blob/master/src/transformers/training_args.py
Apache-2.0
def convert_to_rgb( self, video: "torch.Tensor", ) -> VideoInput: """ Converts a video to RGB format. Args: video (`"torch.Tensor"`): The video to convert. Returns: `torch.Tensor`: The converted video. """ vid...
Converts a video to RGB format. Args: video (`"torch.Tensor"`): The video to convert. Returns: `torch.Tensor`: The converted video.
convert_to_rgb
python
huggingface/transformers
src/transformers/video_processing_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/video_processing_utils.py
Apache-2.0
def _prepare_input_videos( self, videos: VideoInput, input_data_format: Optional[Union[str, ChannelDimension]] = None, device: Optional["torch.device"] = None, ) -> List["torch.Tensor"]: """ Prepare the input videos for processing. """ videos = make_ba...
Prepare the input videos for processing.
_prepare_input_videos
python
huggingface/transformers
src/transformers/video_processing_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/video_processing_utils.py
Apache-2.0
def save_pretrained(self, save_directory: Union[str, os.PathLike], push_to_hub: bool = False, **kwargs): """ Save an video processor object to the directory `save_directory`, so that it can be re-loaded using the [`~video_processing_utils.VideoProcessorBase.from_pretrained`] class method. ...
Save an video processor object to the directory `save_directory`, so that it can be re-loaded using the [`~video_processing_utils.VideoProcessorBase.from_pretrained`] class method. Args: save_directory (`str` or `os.PathLike`): Directory where the video processor JS...
save_pretrained
python
huggingface/transformers
src/transformers/video_processing_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/video_processing_utils.py
Apache-2.0
def get_video_processor_dict( cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs ) -> Tuple[Dict[str, Any], Dict[str, Any]]: """ From a `pretrained_model_name_or_path`, resolve to a dictionary of parameters, to be used for instantiating a video processor of type [`...
From a `pretrained_model_name_or_path`, resolve to a dictionary of parameters, to be used for instantiating a video processor of type [`~video_processing_utils.VideoProcessorBase`] using `from_dict`. Parameters: pretrained_model_name_or_path (`str` or `os.PathLike`): ...
get_video_processor_dict
python
huggingface/transformers
src/transformers/video_processing_utils.py
https://github.com/huggingface/transformers/blob/master/src/transformers/video_processing_utils.py
Apache-2.0