text stringlengths 5 58.6k | source stringclasses 470
values | url stringlengths 49 167 | source_section stringlengths 0 90 | file_type stringclasses 1
value | id stringlengths 3 6 |
|---|---|---|---|---|---|
Gradient Low-Rank Projection (GaLore) is a memory-efficient low-rank training strategy that allows full-parameter learning but is more memory-efficient than common low-rank adaptation methods, such as LoRA.
First make sure to install GaLore official repository:
```bash
pip install galore-torch
```
Then simply add... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/trainer.md | https://huggingface.co/docs/transformers/en/trainer/#galore | #galore | .md | 24_10 |
The LOMO optimizers have been introduced in [Full Parameter Fine-Tuning for Large Language Models with Limited Resources](https://hf.co/papers/2306.09782) and [AdaLomo: Low-memory Optimization with Adaptive Learning Rate](https://hf.co/papers/2310.10195).
They both consist of an efficient full-parameter fine-tuning met... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/trainer.md | https://huggingface.co/docs/transformers/en/trainer/#lomo-optimizer | #lomo-optimizer | .md | 24_11 |
The GrokAdamW optimizer is designed to enhance training performance and stability, particularly for models that benefit from grokking signal functions. To use GrokAdamW, first install the optimizer package with `pip install grokadamw`.
<Tip>
GrokAdamW is particularly useful for models that require advanced optimiza... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/trainer.md | https://huggingface.co/docs/transformers/en/trainer/#grokadamw-optimizer | #grokadamw-optimizer | .md | 24_12 |
The Schedule Free optimizers have been introduced in [The Road Less Scheduled](https://hf.co/papers/2405.15682).
Schedule-Free learning replaces the momentum of the base optimizer with a combination of averaging and interpolation, to completely remove the need to anneal the learning rate with a traditional schedule.
Su... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/trainer.md | https://huggingface.co/docs/transformers/en/trainer/#schedule-free-optimizer | #schedule-free-optimizer | .md | 24_13 |
The [`Trainer`] class is powered by [Accelerate](https://hf.co/docs/accelerate), a library for easily training PyTorch models in distributed environments with support for integrations such as [FullyShardedDataParallel (FSDP)](https://pytorch.org/blog/introducing-pytorch-fully-sharded-data-parallel-api/) and [DeepSpeed]... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/trainer.md | https://huggingface.co/docs/transformers/en/trainer/#accelerate-and-trainer | #accelerate-and-trainer | .md | 24_14 |
<!--Copyright 2022 The HuggingFace Team. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agr... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/run_scripts.md | https://huggingface.co/docs/transformers/en/run_scripts/ | .md | 25_0 | |
Along with the 🤗 Transformers [notebooks](./notebooks), there are also example scripts demonstrating how to train a model for a task with [PyTorch](https://github.com/huggingface/transformers/tree/main/examples/pytorch), [TensorFlow](https://github.com/huggingface/transformers/tree/main/examples/tensorflow), or [JAX/F... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/run_scripts.md | https://huggingface.co/docs/transformers/en/run_scripts/#train-with-a-script | #train-with-a-script | .md | 25_1 |
To successfully run the latest version of the example scripts, you have to **install 🤗 Transformers from source** in a new virtual environment:
```bash
git clone https://github.com/huggingface/transformers
cd transformers
pip install .
```
For older versions of the example scripts, click on the toggle below:
<de... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/run_scripts.md | https://huggingface.co/docs/transformers/en/run_scripts/#setup | #setup | .md | 25_2 |
<frameworkcontent>
<pt>
The example script downloads and preprocesses a dataset from the 🤗 [Datasets](https://huggingface.co/docs/datasets/) library. Then the script fine-tunes a dataset with the [Trainer](https://huggingface.co/docs/transformers/main_classes/trainer) on an architecture that supports summarization. Th... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/run_scripts.md | https://huggingface.co/docs/transformers/en/run_scripts/#run-a-script | #run-a-script | .md | 25_3 |
The [Trainer](https://huggingface.co/docs/transformers/main_classes/trainer) supports distributed training and mixed precision, which means you can also use it in a script. To enable both of these features:
- Add the `fp16` or `bf16` argument to enable mixed precision. XPU devices only supports `bf16` for mixed preci... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/run_scripts.md | https://huggingface.co/docs/transformers/en/run_scripts/#distributed-training-and-mixed-precision | #distributed-training-and-mixed-precision | .md | 25_4 |
<frameworkcontent>
<pt>
Tensor Processing Units (TPUs) are specifically designed to accelerate performance. PyTorch supports TPUs with the [XLA](https://www.tensorflow.org/xla) deep learning compiler (see [here](https://github.com/pytorch/xla/blob/master/README.md) for more details). To use a TPU, launch the `xla_spawn... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/run_scripts.md | https://huggingface.co/docs/transformers/en/run_scripts/#run-a-script-on-a-tpu | #run-a-script-on-a-tpu | .md | 25_5 |
🤗 [Accelerate](https://huggingface.co/docs/accelerate) is a PyTorch-only library that offers a unified method for training a model on several types of setups (CPU-only, multiple GPUs, TPUs) while maintaining complete visibility into the PyTorch training loop. Make sure you have 🤗 Accelerate installed if you don't alr... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/run_scripts.md | https://huggingface.co/docs/transformers/en/run_scripts/#run-a-script-with--accelerate | #run-a-script-with--accelerate | .md | 25_6 |
The summarization script supports custom datasets as long as they are a CSV or JSON Line file. When you use your own dataset, you need to specify several additional arguments:
- `train_file` and `validation_file` specify the path to your training and validation files.
- `text_column` is the input text to summarize.
-... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/run_scripts.md | https://huggingface.co/docs/transformers/en/run_scripts/#use-a-custom-dataset | #use-a-custom-dataset | .md | 25_7 |
It is often a good idea to run your script on a smaller number of dataset examples to ensure everything works as expected before committing to an entire dataset which may take hours to complete. Use the following arguments to truncate the dataset to a maximum number of samples:
- `max_train_samples`
- `max_eval_sampl... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/run_scripts.md | https://huggingface.co/docs/transformers/en/run_scripts/#test-a-script | #test-a-script | .md | 25_8 |
Another helpful option to enable is resuming training from a previous checkpoint. This will ensure you can pick up where you left off without starting over if your training gets interrupted. There are two methods to resume training from a checkpoint.
The first method uses the `output_dir previous_output_dir` argument... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/run_scripts.md | https://huggingface.co/docs/transformers/en/run_scripts/#resume-training-from-checkpoint | #resume-training-from-checkpoint | .md | 25_9 |
All scripts can upload your final model to the [Model Hub](https://huggingface.co/models). Make sure you are logged into Hugging Face before you begin:
```bash
huggingface-cli login
```
Then add the `push_to_hub` argument to the script. This argument will create a repository with your Hugging Face username and the ... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/run_scripts.md | https://huggingface.co/docs/transformers/en/run_scripts/#share-your-model | #share-your-model | .md | 25_10 |
<!--Copyright 2020 The HuggingFace Team. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agr... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/custom_models.md | https://huggingface.co/docs/transformers/en/custom_models/ | .md | 26_0 | |
The 🤗 Transformers library is designed to be easily extensible. Every model is fully coded in a given subfolder
of the repository with no abstraction, so you can easily copy a modeling file and tweak it to your needs.
If you are writing a brand new model, it might be easier to start from scratch. In this tutorial, w... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/custom_models.md | https://huggingface.co/docs/transformers/en/custom_models/#building-custom-models | #building-custom-models | .md | 26_1 |
Before we dive into the model, let's first write its configuration. The configuration of a model is an object that
will contain all the necessary information to build the model. As we will see in the next section, the model can only
take a `config` to be initialized, so we really need that object to be as complete as p... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/custom_models.md | https://huggingface.co/docs/transformers/en/custom_models/#writing-a-custom-configuration | #writing-a-custom-configuration | .md | 26_2 |
Now that we have our ResNet configuration, we can go on writing the model. We will actually write two: one that
extracts the hidden features from a batch of images (like [`BertModel`]) and one that is suitable for image
classification (like [`BertForSequenceClassification`]).
As we mentioned before, we'll only write ... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/custom_models.md | https://huggingface.co/docs/transformers/en/custom_models/#writing-a-custom-model | #writing-a-custom-model | .md | 26_3 |
If you are writing a library that extends 🤗 Transformers, you may want to extend the auto classes to include your own
model. This is different from pushing the code to the Hub in the sense that users will need to import your library to
get the custom models (contrarily to automatically downloading the model code from ... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/custom_models.md | https://huggingface.co/docs/transformers/en/custom_models/#registering-a-model-with-custom-code-to-the-auto-classes | #registering-a-model-with-custom-code-to-the-auto-classes | .md | 26_4 |
<Tip warning={true}>
This API is experimental and may have some slight breaking changes in the next releases.
</Tip>
First, make sure your model is fully defined in a `.py` file. It can rely on relative imports to some other files as
long as all the files are in the same directory (we don't support submodules for... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/custom_models.md | https://huggingface.co/docs/transformers/en/custom_models/#sending-the-code-to-the-hub | #sending-the-code-to-the-hub | .md | 26_5 |
You can use any configuration, model or tokenizer with custom code files in its repository with the auto-classes and
the `from_pretrained` method. All files and code uploaded to the Hub are scanned for malware (refer to the [Hub security](https://huggingface.co/docs/hub/security#malware-scanning) documentation for more... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/custom_models.md | https://huggingface.co/docs/transformers/en/custom_models/#using-a-model-with-custom-code | #using-a-model-with-custom-code | .md | 26_6 |
<!--Copyright 2022 The HuggingFace Team. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agr... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/autoclass_tutorial.md | https://huggingface.co/docs/transformers/en/autoclass_tutorial/ | .md | 27_0 | |
With so many different Transformer architectures, it can be challenging to create one for your checkpoint. As a part of 🤗 Transformers core philosophy to make the library easy, simple and flexible to use, an `AutoClass` automatically infers and loads the correct architecture from a given checkpoint. The `from_pretrain... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/autoclass_tutorial.md | https://huggingface.co/docs/transformers/en/autoclass_tutorial/#load-pretrained-instances-with-an-autoclass | #load-pretrained-instances-with-an-autoclass | .md | 27_1 |
Nearly every NLP task begins with a tokenizer. A tokenizer converts your input into a format that can be processed by the model.
Load a tokenizer with [`AutoTokenizer.from_pretrained`]:
```py
>>> from transformers import AutoTokenizer
>>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
`... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/autoclass_tutorial.md | https://huggingface.co/docs/transformers/en/autoclass_tutorial/#autotokenizer | #autotokenizer | .md | 27_2 |
For vision tasks, an image processor processes the image into the correct input format.
```py
>>> from transformers import AutoImageProcessor
>>> image_processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224")
``` | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/autoclass_tutorial.md | https://huggingface.co/docs/transformers/en/autoclass_tutorial/#autoimageprocessor | #autoimageprocessor | .md | 27_3 |
<div style="text-align: center">
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/Swin%20Stages.png">
<figcaption class="mt-2 text-center text-sm text-gray-500">A Swin backbone with multiple stages for outputting a feature map.</figcaption>
</div>
The [`AutoBackbone... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/autoclass_tutorial.md | https://huggingface.co/docs/transformers/en/autoclass_tutorial/#autobackbone | #autobackbone | .md | 27_4 |
For audio tasks, a feature extractor processes the audio signal into the correct input format.
Load a feature extractor with [`AutoFeatureExtractor.from_pretrained`]:
```py
>>> from transformers import AutoFeatureExtractor
>>> feature_extractor = AutoFeatureExtractor.from_pretrained(
... "ehcalabres/wav2vec2-l... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/autoclass_tutorial.md | https://huggingface.co/docs/transformers/en/autoclass_tutorial/#autofeatureextractor | #autofeatureextractor | .md | 27_5 |
Multimodal tasks require a processor that combines two types of preprocessing tools. For example, the [LayoutLMV2](model_doc/layoutlmv2) model requires an image processor to handle images and a tokenizer to handle text; a processor combines both of them.
Load a processor with [`AutoProcessor.from_pretrained`]:
```p... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/autoclass_tutorial.md | https://huggingface.co/docs/transformers/en/autoclass_tutorial/#autoprocessor | #autoprocessor | .md | 27_6 |
<frameworkcontent>
<pt>
The `AutoModelFor` classes let you load a pretrained model for a given task (see [here](model_doc/auto) for a complete list of available tasks). For example, load a model for sequence classification with [`AutoModelForSequenceClassification.from_pretrained`].
> [!WARNING]
> By default, the wei... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/autoclass_tutorial.md | https://huggingface.co/docs/transformers/en/autoclass_tutorial/#automodel | #automodel | .md | 27_7 |
<!--Copyright 2022 The HuggingFace Team. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agr... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/perf_infer_cpu.md | https://huggingface.co/docs/transformers/en/perf_infer_cpu/ | .md | 28_0 | |
With some optimizations, it is possible to efficiently run large model inference on a CPU. One of these optimization techniques involves compiling the PyTorch code into an intermediate format for high-performance environments like C++. The other technique fuses multiple operations into one kernel to reduce the overhead... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/perf_infer_cpu.md | https://huggingface.co/docs/transformers/en/perf_infer_cpu/#cpu-inference | #cpu-inference | .md | 28_1 |
BetterTransformer accelerates inference with its fastpath (native PyTorch specialized implementation of Transformer functions) execution. The two optimizations in the fastpath execution are:
1. fusion, which combines multiple sequential operations into a single "kernel" to reduce the number of computation steps
2. sk... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/perf_infer_cpu.md | https://huggingface.co/docs/transformers/en/perf_infer_cpu/#bettertransformer | #bettertransformer | .md | 28_2 |
TorchScript is an intermediate PyTorch model representation that can be run in production environments where performance is important. You can train a model in PyTorch and then export it to TorchScript to free the model from Python performance constraints. PyTorch [traces](https://pytorch.org/docs/stable/generated/torc... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/perf_infer_cpu.md | https://huggingface.co/docs/transformers/en/perf_infer_cpu/#torchscript | #torchscript | .md | 28_3 |
Intel® Extension for PyTorch (IPEX) provides further optimizations in JIT mode for Intel CPUs, and we recommend combining it with TorchScript for even faster performance. The IPEX [graph optimization](https://intel.github.io/intel-extension-for-pytorch/cpu/latest/tutorials/features/graph_optimization.html) fuses operat... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/perf_infer_cpu.md | https://huggingface.co/docs/transformers/en/perf_infer_cpu/#ipex-graph-optimization | #ipex-graph-optimization | .md | 28_4 |
<Tip>
Learn more details about using ORT with 🤗 Optimum in the [Optimum Inference with ONNX Runtime](https://huggingface.co/docs/optimum/onnxruntime/usage_guides/models) guide. This section only provides a brief and simple example.
</Tip>
ONNX Runtime (ORT) is a model accelerator that runs inference on CPUs by d... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/perf_infer_cpu.md | https://huggingface.co/docs/transformers/en/perf_infer_cpu/#-optimum | #-optimum | .md | 28_5 |
<!--Copyright 2020 The HuggingFace Team. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agr... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/bertology.md | https://huggingface.co/docs/transformers/en/bertology/ | .md | 29_0 | |
There is a growing field of study concerned with investigating the inner working of large-scale transformers like BERT
(that some call "BERTology"). Some good examples of this field are:
- BERT Rediscovers the Classical NLP Pipeline by Ian Tenney, Dipanjan Das, Ellie Pavlick:
https://arxiv.org/abs/1905.05950
- Are Si... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/bertology.md | https://huggingface.co/docs/transformers/en/bertology/#bertology | #bertology | .md | 29_1 |
<!---
Copyright 2023 The HuggingFace Team. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or a... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/notebooks.md | https://huggingface.co/docs/transformers/en/notebooks/ | .md | 30_0 | |
You can find here a list of the official notebooks provided by Hugging Face.
Also, we would like to list here interesting content created by the community.
If you wrote some notebook(s) leveraging 🤗 Transformers and would like to be listed here, please open a
Pull Request so it can be included under the Community no... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/notebooks.md | https://huggingface.co/docs/transformers/en/notebooks/#-transformers-notebooks | #-transformers-notebooks | .md | 30_1 |
You can open any page of the documentation as a notebook in Colab (there is a button directly on said pages) but they are also listed here if you need them:
| Notebook | Description | | |
|:----------|:-------------|:-------------|------:|
| [Quicktour of the library](https://github.com/huggingface/... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/notebooks.md | https://huggingface.co/docs/transformers/en/notebooks/#documentation-notebooks | #documentation-notebooks | .md | 30_2 |
| Notebook | Description | | |
|:----------|:-------------|:-------------|------:|
| [Train your tokenizer](https://github.com/huggingface/notebooks/blob/main/examples/tokenizer_training.ipynb) | How to train and use your very own tokenizer |[| Show how to preprocess the data and fine-tune a pretrained Speech model o... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/notebooks.md | https://huggingface.co/docs/transformers/en/notebooks/#audiopytorch-audio | #audiopytorch-audio | .md | 30_5 |
| Notebook | Description | | |
|:----------|:----------------------------------------------------------------------------------------|:-------------|------:|
| [How to fine-tune a pre-trained protein model](https://github.com/huggingfac... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/notebooks.md | https://huggingface.co/docs/transformers/en/notebooks/#biological-sequencespytorch-bio | #biological-sequencespytorch-bio | .md | 30_6 |
| Notebook | Description | | |
|:----------|:----------------------------------------------------------------------------------------|:-------------|------:|
| [Probabilistic Time Series Forecasting](https://github.com/huggingface/noteb... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/notebooks.md | https://huggingface.co/docs/transformers/en/notebooks/#other-modalitiespytorch-other | #other-modalitiespytorch-other | .md | 30_7 |
| Notebook | Description | | |
|:----------|:-------------|:-------------|------:|
| [How to export model to ONNX](https://github.com/huggingface/notebooks/blob/main/examples/onnx-export.ipynb)| Highlight how to export and run inference workloads through ONNX | [ | How to train and use your very own tokenizer |[ | See how to tokenize proteins and fine-tune a large pre-trained protein "... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/notebooks.md | https://huggingface.co/docs/transformers/en/notebooks/#biological-sequencestensorflow-bio | #biological-sequencestensorflow-bio | .md | 30_11 |
| Notebook | Description | | |
|:----------|:-------------|:-------------|------:|
| [How to train TF/Keras models on TPU](... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/notebooks.md | https://huggingface.co/docs/transformers/en/notebooks/#utility-notebookstensorflow-utility | #utility-notebookstensorflow-utility | .md | 30_12 |
🤗 [Optimum](https://github.com/huggingface/optimum) is an extension of 🤗 Transformers, providing a set of performance optimization tools enabling maximum efficiency to train and run models on targeted hardwares.
| Notebook | Description | | |
|:----------|:-------------|:-------------|------:|
| ... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/notebooks.md | https://huggingface.co/docs/transformers/en/notebooks/#optimum-notebooks | #optimum-notebooks | .md | 30_13 |
More notebooks developed by the community are available [here](https://hf.co/docs/transformers/community#community-notebooks). | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/notebooks.md | https://huggingface.co/docs/transformers/en/notebooks/#community-notebooks | #community-notebooks | .md | 30_14 |
<!--Copyright 2020 The HuggingFace Team. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agr... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/ | .md | 31_0 | |
Let's take a look at how 🤗 Transformers models are tested and how you can write new tests and improve the existing ones.
There are 2 test suites in the repository:
1. `tests` -- tests for the general API
2. `examples` -- tests primarily for various applications that aren't part of the API | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#testing | #testing | .md | 31_1 |
1. Once a PR is submitted it gets tested with 9 CircleCi jobs. Every new commit to that PR gets retested. These jobs
are defined in this [config file](https://github.com/huggingface/transformers/tree/main/.circleci/config.yml), so that if needed you can reproduce the same
environment on your machine.
These CI jobs do... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#how-transformers-are-tested | #how-transformers-are-tested | .md | 31_2 |
This document goes into many details of how tests can be run. If after reading everything, you need even more details
you will find them [here](https://docs.pytest.org/en/latest/usage.html).
Here are some most useful ways of running tests.
Run all:
```console
pytest
```
or:
```bash
make test
```
Note that t... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#choosing-which-tests-to-run | #choosing-which-tests-to-run | .md | 31_3 |
All tests of the test suite:
```bash
pytest --collect-only -q
```
All tests of a given test file:
```bash
pytest tests/test_optimization.py --collect-only -q
``` | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#getting-the-list-of-all-tests | #getting-the-list-of-all-tests | .md | 31_4 |
To run an individual test module:
```bash
pytest tests/utils/test_logging.py
``` | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#run-a-specific-test-module | #run-a-specific-test-module | .md | 31_5 |
Since unittest is used inside most of the tests, to run specific subtests you need to know the name of the unittest
class containing those tests. For example, it could be:
```bash
pytest tests/test_optimization.py::OptimizationTest::test_adam_w
```
Here:
- `tests/test_optimization.py` - the file with tests
- `Opt... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#run-specific-tests | #run-specific-tests | .md | 31_6 |
Sometimes you need to run `accelerate` tests on your models. For that you can just add `-m accelerate_tests` to your command, if let's say you want to run these tests on `OPT` run:
```bash
RUN_SLOW=1 pytest -m accelerate_tests tests/models/opt/test_modeling_opt.py
``` | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#run-accelerate-tests | #run-accelerate-tests | .md | 31_7 |
In order to test whether the documentation examples are correct, you should check that the `doctests` are passing.
As an example, let's use [`WhisperModel.forward`'s docstring](https://github.com/huggingface/transformers/blob/1124d95dbb1a3512d3e80791d73d0f541d1d7e9f/src/transformers/models/whisper/modeling_whisper.py#L... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#run-documentation-tests | #run-documentation-tests | .md | 31_8 |
You can run the tests related to the unstaged files or the current branch (according to Git) by using [pytest-picked](https://github.com/anapaulagomes/pytest-picked). This is a great way of quickly testing your changes didn't break
anything, since it won't run the tests related to files you didn't touch.
```bash
pip ... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#run-only-modified-tests | #run-only-modified-tests | .md | 31_9 |
[pytest-xdist](https://github.com/pytest-dev/pytest-xdist) provides a very useful feature of detecting all failed
tests, and then waiting for you to modify files and continuously re-rerun those failing tests until they pass while you
fix them. So that you don't need to re start pytest after you made the fix. This is re... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#automatically-rerun-failed-tests-on-source-modification | #automatically-rerun-failed-tests-on-source-modification | .md | 31_10 |
If you want to run all test modules, except a few you can exclude them by giving an explicit list of tests to run. For
example, to run all except `test_modeling_*.py` tests:
```bash
pytest *ls -1 tests/*py | grep -v test_modeling*
``` | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#skip-a-test-module | #skip-a-test-module | .md | 31_11 |
CI builds and when isolation is important (against speed), cache should be cleared:
```bash
pytest --cache-clear tests
``` | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#clearing-state | #clearing-state | .md | 31_12 |
As mentioned earlier `make test` runs tests in parallel via `pytest-xdist` plugin (`-n X` argument, e.g. `-n 2`
to run 2 parallel jobs).
`pytest-xdist`'s `--dist=` option allows one to control how the tests are grouped. `--dist=loadfile` puts the
tests located in one file onto the same process.
Since the order of e... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#running-tests-in-parallel | #running-tests-in-parallel | .md | 31_13 |
It's good to repeat the tests several times, in sequence, randomly, or in sets, to detect any potential
inter-dependency and state-related bugs (tear down). And the straightforward multiple repetition is just good to detect
some problems that get uncovered by randomness of DL. | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#test-order-and-repetition | #test-order-and-repetition | .md | 31_14 |
- [pytest-flakefinder](https://github.com/dropbox/pytest-flakefinder):
```bash
pip install pytest-flakefinder
```
And then run every test multiple times (50 by default):
```bash
pytest --flake-finder --flake-runs=5 tests/test_failing_test.py
```
<Tip>
This plugin doesn't work with `-n` flag from `pytest-xdist... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#repeat-tests | #repeat-tests | .md | 31_15 |
```bash
pip install pytest-random-order
```
Important: the presence of `pytest-random-order` will automatically randomize tests, no configuration change or
command line options is required.
As explained earlier this allows detection of coupled tests - where one test's state affects the state of another. When
`pytes... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#run-tests-in-a-random-order | #run-tests-in-a-random-order | .md | 31_16 |
[pytest-sugar](https://github.com/Frozenball/pytest-sugar) is a plugin that improves the look-n-feel, adds a
progressbar, and show tests that fail and the assert instantly. It gets activated automatically upon installation.
```bash
pip install pytest-sugar
```
To run tests without it, run:
```bash
pytest -p no:su... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#pytest-sugar | #pytest-sugar | .md | 31_17 |
For a single or a group of tests via `pytest` (after `pip install pytest-pspec`):
```bash
pytest --pspec tests/test_optimization.py
``` | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#report-each-sub-test-name-and-its-progress | #report-each-sub-test-name-and-its-progress | .md | 31_18 |
[pytest-instafail](https://github.com/pytest-dev/pytest-instafail) shows failures and errors instantly instead of
waiting until the end of test session.
```bash
pip install pytest-instafail
```
```bash
pytest --instafail
``` | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#instantly-shows-failed-tests | #instantly-shows-failed-tests | .md | 31_19 |
On a GPU-enabled setup, to test in CPU-only mode add `CUDA_VISIBLE_DEVICES=""` for CUDA GPUs:
```bash
CUDA_VISIBLE_DEVICES="" pytest tests/utils/test_logging.py
```
or if you have multiple gpus, you can specify which one is to be used by `pytest`. For example, to use only the
second gpu if you have gpus `0` and `1`... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#to-gpu-or-not-to-gpu | #to-gpu-or-not-to-gpu | .md | 31_20 |
To run the test suite on a specific torch device add `TRANSFORMERS_TEST_DEVICE="$device"` where `$device` is the target backend. For example, to test on CPU only:
```bash
TRANSFORMERS_TEST_DEVICE="cpu" pytest tests/utils/test_logging.py
```
This variable is useful for testing custom or less common PyTorch backends ... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#testing-with-a-specific-pytorch-backend-or-device | #testing-with-a-specific-pytorch-backend-or-device | .md | 31_21 |
`pytest` can't deal with distributed training directly. If this is attempted - the sub-processes don't do the right
thing and end up thinking they are `pytest` and start running the test suite in loops. It works, however, if one
spawns a normal process that then spawns off multiple workers and manages the IO pipes.
H... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#distributed-training | #distributed-training | .md | 31_22 |
During test execution any output sent to `stdout` and `stderr` is captured. If a test or a setup method fails, its
according captured output will usually be shown along with the failure traceback.
To disable output capturing and to get the `stdout` and `stderr` normally, use `-s` or `--capture=no`:
```bash
pytest -... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#output-capture | #output-capture | .md | 31_23 |
To have no color (e.g., yellow on white background is not readable):
```bash
pytest --color=no tests/utils/test_logging.py
``` | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#color-control | #color-control | .md | 31_24 |
Creating a URL for each test failure:
```bash
pytest --pastebin=failed tests/utils/test_logging.py
```
This will submit test run information to a remote Paste service and provide a URL for each failure. You may select
tests as usual or add for example -x if you only want to send one particular failure.
Creating a... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#sending-test-report-to-online-pastebin-service | #sending-test-report-to-online-pastebin-service | .md | 31_25 |
🤗 transformers tests are based on `unittest`, but run by `pytest`, so most of the time features from both systems
can be used.
You can read [here](https://docs.pytest.org/en/stable/unittest.html) which features are supported, but the important
thing to remember is that most `pytest` fixtures don't work. Neither para... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#writing-tests | #writing-tests | .md | 31_26 |
Often, there is a need to run the same test multiple times, but with different arguments. It could be done from within
the test, but then there is no way of running that test for just one set of arguments.
```python
# test_this1.py
import unittest
from parameterized import parameterized
class TestMathUnitTest(unitt... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#parametrization | #parametrization | .md | 31_27 |
In tests often we need to know where things are relative to the current test file, and it's not trivial since the test
could be invoked from more than one directory or could reside in sub-directories with different depths. A helper class
`transformers.test_utils.TestCasePlus` solves this problem by sorting out all the ... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#files-and-directories | #files-and-directories | .md | 31_28 |
Using unique temporary files and directories are essential for parallel test running, so that the tests won't overwrite
each other's data. Also we want to get the temporary files and directories removed at the end of each test that created
them. Therefore, using packages like `tempfile`, which address these needs is es... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#temporary-files-and-directories | #temporary-files-and-directories | .md | 31_29 |
If you need to temporary override `sys.path` to import from another test for example, you can use the
`ExtendSysPath` context manager. Example:
```python
import os
from transformers.testing_utils import ExtendSysPath
bindir = os.path.abspath(os.path.dirname(__file__))
with ExtendSysPath(f"{bindir}/.."):
from test_tr... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#temporary-syspath-override | #temporary-syspath-override | .md | 31_30 |
This is useful when a bug is found and a new test is written, yet the bug is not fixed yet. In order to be able to
commit it to the main repository we need make sure it's skipped during `make test`.
Methods:
- A **skip** means that you expect your test to pass only if some conditions are met, otherwise pytest shou... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#skipping-tests | #skipping-tests | .md | 31_31 |
- Here is how to skip whole test unconditionally:
```python no-style
@unittest.skip(reason="this bug needs to be fixed")
def test_feature_x():
```
or via pytest:
```python no-style
@pytest.mark.skip(reason="this bug needs to be fixed")
```
or the `xfail` way:
```python no-style
@pytest.mark.xfail
def test_fea... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#implementation | #implementation | .md | 31_32 |
The library of tests is ever-growing, and some of the tests take minutes to run, therefore we can't afford waiting for
an hour for the test suite to complete on CI. Therefore, with some exceptions for essential tests, slow tests should be
marked as in the example below:
```python no-style
from transformers.testing_ut... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#slow-tests | #slow-tests | .md | 31_33 |
In order to test functions that write to `stdout` and/or `stderr`, the test can access those streams using the
`pytest`'s [capsys system](https://docs.pytest.org/en/latest/capture.html). Here is how this is accomplished:
```python
import sys
def print_to_stdout(s):
print(s)
def print_to_stderr(s):
sys.stderr.writ... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#testing-the-stdoutstderr-output | #testing-the-stdoutstderr-output | .md | 31_34 |
If you need to validate the output of a logger, you can use `CaptureLogger`:
```python
from transformers import logging
from transformers.testing_utils import CaptureLogger
msg = "Testing 1, 2, 3"
logging.set_verbosity_info()
logger = logging.get_logger("transformers.models.bart.tokenization_bart")
with CaptureLogge... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#capturing-logger-stream | #capturing-logger-stream | .md | 31_35 |
If you want to test the impact of environment variables for a specific test you can use a helper decorator
`transformers.testing_utils.mockenv`
```python
from transformers.testing_utils import mockenv
class HfArgumentParserTest(unittest.TestCase):
@mockenv(TRANSFORMERS_VERBOSITY="error")
def test_env_override(self)... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#testing-with-environment-variables | #testing-with-environment-variables | .md | 31_36 |
In some situations you may want to remove randomness for your tests. To get identical reproducible results set, you
will need to fix the seed:
```python
seed = 42
# python RNG
import random
random.seed(seed)
# pytorch RNGs
import torch
torch.manual_seed(seed)
torch.backends.cudnn.deterministic = True
if torch.cud... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#getting-reproducible-results | #getting-reproducible-results | .md | 31_37 |
To start a debugger at the point of the warning, do this:
```bash
pytest tests/utils/test_logging.py -W error::UserWarning --pdb
``` | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#debugging-tests | #debugging-tests | .md | 31_38 |
To trigger a self-push workflow CI job, you must:
1. Create a new branch on `transformers` origin (not a fork!).
2. The branch name has to start with either `ci_` or `ci-` (`main` triggers it too, but we can't do PRs on
`main`). It also gets triggered only for specific paths - you can find the up-to-date definition i... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#working-with-github-actions-workflows | #working-with-github-actions-workflows | .md | 31_39 |
Testing CI features can be potentially problematic as it can interfere with the normal CI functioning. Therefore if a
new CI feature is to be added, it should be done as following.
1. Create a new dedicated job that tests what needs to be tested
2. The new job must always succeed so that it gives us a green ✓ (detail... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#testing-experimental-ci-features | #testing-experimental-ci-features | .md | 31_40 |
For a PR that involves the DeepSpeed integration, keep in mind our CircleCI PR CI setup doesn't have GPUs. Tests requiring GPUs are run on a different CI nightly. This means if you get a passing CI report in your PR, it doesn’t mean the DeepSpeed tests pass.
To run DeepSpeed tests:
```bash
RUN_SLOW=1 pytest tests/d... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#deepspeed-integration | #deepspeed-integration | .md | 31_41 |
<!---
Copyright 2021 The HuggingFace Team. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or a... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/performance.md | https://huggingface.co/docs/transformers/en/performance/ | .md | 32_0 | |
Training large transformer models and deploying them to production present various challenges.
During training, the model may require more GPU memory than available or exhibit slow training speed. In the deployment
phase, the model can struggle to handle the required throughput in a production environment.
This docum... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/performance.md | https://huggingface.co/docs/transformers/en/performance/#performance-and-scalability | #performance-and-scalability | .md | 32_1 |
Training large transformer models efficiently requires an accelerator such as a GPU or TPU. The most common case is where
you have a single GPU. The methods that you can apply to improve training efficiency on a single GPU extend to other setups
such as multiple GPU. However, there are also techniques that are specific... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/performance.md | https://huggingface.co/docs/transformers/en/performance/#training | #training | .md | 32_2 |
Efficient inference with large models in a production environment can be as challenging as training them. In the following
sections we go through the steps to run inference on CPU and single/multi-GPU setups.
* [Inference on a single CPU](perf_infer_cpu)
* [Inference on a single GPU](perf_infer_gpu_one)
* [Multi-GPU ... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/performance.md | https://huggingface.co/docs/transformers/en/performance/#inference | #inference | .md | 32_3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.