source stringclasses 470
values | url stringlengths 49 167 | file_type stringclasses 1
value | chunk stringlengths 1 512 | chunk_id stringlengths 5 9 |
|---|---|---|---|---|
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#how-transformers-are-tested | .md | `main`. It only runs if a commit on `main` has updated the code in one of the following folders: `src`,
`tests`, `.github` (to prevent running on added model cards, notebooks, etc.)
- [self-hosted runner](https://github.com/huggingface/transformers/tree/main/.github/workflows/self-scheduled.yml): runs normal and slow... | 31_2_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#how-transformers-are-tested | .md | `tests` and `examples`:
```bash
RUN_SLOW=1 pytest tests/
RUN_SLOW=1 pytest examples/
```
The results can be observed [here](https://github.com/huggingface/transformers/actions). | 31_2_3 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#choosing-which-tests-to-run | .md | 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... | 31_3_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#choosing-which-tests-to-run | .md | ```bash
python -m pytest -n auto --dist=loadfile -s -v ./tests/
```
which tells pytest to:
- run as many test processes as they are CPU cores (which could be too many if you don't have a ton of RAM!)
- ensure that all tests from the same file will be run by the same test process
- do not capture output
- run in ver... | 31_3_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#getting-the-list-of-all-tests | .md | 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
``` | 31_4_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#run-a-specific-test-module | .md | To run an individual test module:
```bash
pytest tests/utils/test_logging.py
``` | 31_5_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#run-specific-tests | .md | 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... | 31_6_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#run-specific-tests | .md | - `OptimizationTest` - the name of the class
- `test_adam_w` - the name of the specific test function
If the file contains multiple classes, you can choose to run only tests of a given class. For example:
```bash
pytest tests/test_optimization.py::OptimizationTest
```
will run all the tests inside that class.
A... | 31_6_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#run-specific-tests | .md | ```bash
pytest tests/test_optimization.py::OptimizationTest --collect-only -q
```
You can run tests by keyword expressions.
To run only tests whose name contains `adam`:
```bash
pytest -k adam tests/test_optimization.py
```
Logical `and` and `or` can be used to indicate whether all keywords should match or eith... | 31_6_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#run-specific-tests | .md | To run all tests except those whose name contains `adam`:
```bash
pytest -k "not adam" tests/test_optimization.py
```
And you can combine the two patterns in one:
```bash
pytest -k "ada and not adam" tests/test_optimization.py
```
For example to run both `test_adafactor` and `test_adam_w` you can use:
```bash... | 31_6_3 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#run-specific-tests | .md | ```
Note that we use `or` here, since we want either of the keywords to match to include both.
If you want to include only tests that include both patterns, `and` is to be used:
```bash
pytest -k "test and ada" tests/test_optimization.py
``` | 31_6_4 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#run-accelerate-tests | .md | 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
``` | 31_7_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#run-documentation-tests | .md | 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... | 31_8_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#run-documentation-tests | .md | Example:
```python
>>> import torch
>>> from transformers import WhisperModel, WhisperFeatureExtractor
>>> from datasets import load_dataset
>>> model = WhisperModel.from_pretrained("openai/whisper-base")
>>> feature_extractor = WhisperFeatureExtractor.from_pretrained("openai/whisper-base")
>>> ds = load_dataset("hf-... | 31_8_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#run-documentation-tests | .md | >>> inputs = feature_extractor(ds[0]["audio"]["array"], return_tensors="pt")
>>> input_features = inputs.input_features
>>> decoder_input_ids = torch.tensor([[1, 1]]) * model.config.decoder_start_token_id
>>> last_hidden_state = model(input_features, decoder_input_ids=decoder_input_ids).last_hidden_state
>>> list(last_... | 31_8_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#run-documentation-tests | .md | ```
Just run the following line to automatically test every docstring example in the desired file:
```bash
pytest --doctest-modules <path_to_file_or_dir>
```
If the file has a markdown extention, you should add the `--doctest-glob="*.md"` argument. | 31_8_3 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#run-only-modified-tests | .md | 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 ... | 31_9_0 |
/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 | .md | [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... | 31_10_0 |
/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 | .md | ```bash
pip install pytest-xdist
```
To enter the mode: `pytest -f` or `pytest --looponfail`
File changes are detected by looking at `looponfailroots` root directories and all of their contents (recursively).
If the default for this value does not work for you, you can change it in your project by setting a configu... | 31_10_1 |
/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 | .md | ```
or `pytest.ini`/``tox.ini`` files:
```ini
[pytest]
looponfailroots = transformers tests
```
This would lead to only looking for file changes in the respective directories, specified relatively to the ini-file’s
directory.
[pytest-watch](https://github.com/joeyespo/pytest-watch) is an alternative implementat... | 31_10_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#skip-a-test-module | .md | 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*
``` | 31_11_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#clearing-state | .md | CI builds and when isolation is important (against speed), cache should be cleared:
```bash
pytest --cache-clear tests
``` | 31_12_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#running-tests-in-parallel | .md | 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... | 31_13_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#running-tests-in-parallel | .md | Since the order of executed tests is different and unpredictable, if running the test suite with `pytest-xdist`
produces failures (meaning we have some undetected coupled tests), use [pytest-replay](https://github.com/ESSS/pytest-replay) to replay the tests in the same order, which should help with then somehow
reducin... | 31_13_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#test-order-and-repetition | .md | 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. | 31_14_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#repeat-tests | .md | - [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... | 31_15_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#run-tests-in-a-random-order | .md | ```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... | 31_16_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#run-tests-in-a-random-order | .md | ```bash
pytest tests
[...]
Using --random-order-bucket=module
Using --random-order-seed=573663
```
So that if the given particular sequence fails, you can reproduce it by adding that exact seed, e.g.:
```bash
pytest --random-order-seed=573663
[...]
Using --random-order-bucket=module
Using --random-order-seed=573663... | 31_16_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#run-tests-in-a-random-order | .md | ```
It will only reproduce the exact order if you use the exact same list of tests (or no list at all). Once you start to
manually narrowing down the list you can no longer rely on the seed, but have to list them manually in the exact order
they failed and tell pytest to not randomize them instead using `--random-ord... | 31_16_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#run-tests-in-a-random-order | .md | ```
To disable the shuffling for all tests:
```bash
pytest --random-order-bucket=none
```
By default `--random-order-bucket=module` is implied, which will shuffle the files on the module levels. It can also
shuffle on `class`, `package`, `global` and `none` levels. For the complete details please see its
[documen... | 31_16_3 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#run-tests-in-a-random-order | .md | Another randomization alternative is: [`pytest-randomly`](https://github.com/pytest-dev/pytest-randomly). This
module has a very similar functionality/interface, but it doesn't have the bucket modes available in
`pytest-random-order`. It has the same problem of imposing itself once installed. | 31_16_4 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#pytest-sugar | .md | [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... | 31_17_0 |
/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 | .md | For a single or a group of tests via `pytest` (after `pip install pytest-pspec`):
```bash
pytest --pspec tests/test_optimization.py
``` | 31_18_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#instantly-shows-failed-tests | .md | [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
``` | 31_19_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#to-gpu-or-not-to-gpu | .md | 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`... | 31_20_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#to-gpu-or-not-to-gpu | .md | ```
For Intel GPUs, use `ZE_AFFINITY_MASK` instead of `CUDA_VISIBLE_DEVICES` in the above example.
This is handy when you want to run different tasks on different GPUs.
Some tests must be run on CPU-only, others on either CPU or GPU or TPU, yet others on multiple-GPUs. The following skip
decorators are used to se... | 31_20_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 | .md | - `require_torch` - this test will run only under torch
- `require_torch_gpu` - as `require_torch` plus requires at least 1 GPU
- `require_torch_multi_gpu` - as `require_torch` plus requires at least 2 GPUs
- `require_torch_non_multi_gpu` - as `require_torch` plus requires 0 or 1 GPUs
- `require_torch_up_to_2_gpus` - a... | 31_20_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#to-gpu-or-not-to-gpu | .md | Let's depict the GPU requirements in the following table:
| n gpus | decorator |
|--------|--------------------------------|
| `>= 0` | `@require_torch` |
| `>= 1` | `@require_torch_gpu` |
| `>= 2` | `@require_torch_multi_gpu` |
| `< 2` | `@require_torch_non_multi_gpu... | 31_20_3 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#to-gpu-or-not-to-gpu | .md | ```python no-style
@require_torch_multi_gpu
def test_example_with_multi_gpu():
```
If a test requires `tensorflow` use the `require_tf` decorator. For example:
```python no-style
@require_tf
def test_tf_thing_with_tensorflow():
```
These decorators can be stacked. For example, if a test is slow and requires at le... | 31_20_4 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#to-gpu-or-not-to-gpu | .md | how to set it up:
```python no-style
@require_torch_gpu
@slow
def test_example_slow_on_gpu():
```
Some decorators like `@parametrized` rewrite test names, therefore `@require_*` skip decorators have to be listed
last for them to work correctly. Here is an example of the correct usage:
```python no-style
@paramete... | 31_20_5 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#to-gpu-or-not-to-gpu | .md | ```
This order problem doesn't exist with `@pytest.mark.parametrize`, you can put it first or last and it will still
work. But it only works with non-unittests.
Inside tests:
- How many GPUs are available:
```python
from transformers.testing_utils import get_gpu_count | 31_20_6 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#to-gpu-or-not-to-gpu | .md | n_gpu = get_gpu_count() # works with torch and tf
``` | 31_20_7 |
/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 | .md | 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 ... | 31_21_0 |
/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 | .md | Certain devices will require an additional import after importing `torch` for the first time. This can be specified using the environment variable `TRANSFORMERS_TEST_BACKEND`:
```bash
TRANSFORMERS_TEST_BACKEND="torch_npu" pytest tests/utils/test_logging.py
``` | 31_21_1 |
/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 | .md | ```
Alternative backends may also require the replacement of device-specific functions. For example `torch.cuda.manual_seed` may need to be replaced with a device-specific seed setter like `torch.npu.manual_seed` or `torch.xpu.manual_seed` to correctly set a random seed on the device. To specify a new backend with back... | 31_21_2 |
/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 | .md | ```python
import torch
import torch_npu # for xpu, replace it with `import intel_extension_for_pytorch`
# !! Further additional imports can be added here !! | 31_21_3 |
/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 | .md | # Specify the device name (eg. 'cuda', 'cpu', 'npu', 'xpu', 'mps')
DEVICE_NAME = 'npu' | 31_21_4 |
/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 | .md | # Specify device-specific backends to dispatch to.
# If not specified, will fallback to 'default' in 'testing_utils.py`
MANUAL_SEED_FN = torch.npu.manual_seed
EMPTY_CACHE_FN = torch.npu.empty_cache
DEVICE_COUNT_FN = torch.npu.device_count
``` | 31_21_5 |
/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 | .md | MANUAL_SEED_FN = torch.npu.manual_seed
EMPTY_CACHE_FN = torch.npu.empty_cache
DEVICE_COUNT_FN = torch.npu.device_count
```
This format also allows for specification of any additional imports required. To use this file to replace equivalent methods in the test suite, set the environment variable `TRANSFORMERS_TEST_DEVIC... | 31_21_6 |
/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 | .md | Currently, only `MANUAL_SEED_FN`, `EMPTY_CACHE_FN` and `DEVICE_COUNT_FN` are supported for device-specific dispatch. | 31_21_7 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#distributed-training | .md | `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... | 31_22_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#distributed-training | .md | - [test_deepspeed.py](https://github.com/huggingface/transformers/tree/main/tests/deepspeed/test_deepspeed.py)
To jump right into the execution point, search for the `execute_subprocess_async` call in those tests.
You will need at least 2 GPUs to see these tests in action:
```bash
CUDA_VISIBLE_DEVICES=0,1 RUN_SLO... | 31_22_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#output-capture | .md | 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 -... | 31_23_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#color-control | .md | To have no color (e.g., yellow on white background is not readable):
```bash
pytest --color=no tests/utils/test_logging.py
``` | 31_24_0 |
/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 | .md | 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... | 31_25_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#writing-tests | .md | 🤗 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... | 31_26_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#parametrization | .md | 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 | 31_27_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#parametrization | .md | class TestMathUnitTest(unittest.TestCase):
@parameterized.expand(
[
("negative", -1.5, -2.0),
("integer", 1, 1.0),
("large fraction", 1.6, 1),
]
)
def test_floor(self, name, input, expected):
assert_equal(math.floor(input), expected)
```
Now, by default this test will be run 3 times, each time with the last 3 argumen... | 31_27_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#parametrization | .md | and you could run just the `negative` and `integer` sets of params with:
```bash
pytest -k "negative and integer" tests/test_mytest.py
```
or all but `negative` sub-tests, with:
```bash
pytest -k "not negative" tests/test_mytest.py
```
Besides using the `-k` filter that was just mentioned, you can find out the ... | 31_27_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#parametrization | .md | or all of them using their exact names.
```bash
pytest test_this1.py --collect-only -q
```
and it will list:
```bash
test_this1.py::TestMathUnitTest::test_floor_0_negative
test_this1.py::TestMathUnitTest::test_floor_1_integer
test_this1.py::TestMathUnitTest::test_floor_2_large_fraction
```
So now you can run ju... | 31_27_3 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#parametrization | .md | pytest test_this1.py::TestMathUnitTest::test_floor_0_negative test_this1.py::TestMathUnitTest::test_floor_1_integer
```
The module [parameterized](https://pypi.org/project/parameterized/) which is already in the developer dependencies
of `transformers` works for both: `unittests` and `pytest` tests.
If, however, t... | 31_27_4 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#parametrization | .md | some existing tests, mostly under `examples`).
Here is the same example, this time using `pytest`'s `parametrize` marker:
```python
# test_this2.py
import pytest | 31_27_5 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#parametrization | .md | @pytest.mark.parametrize(
"name, input, expected",
[
("negative", -1.5, -2.0),
("integer", 1, 1.0),
("large fraction", 1.6, 1),
],
)
def test_floor(name, input, expected):
assert_equal(math.floor(input), expected)
```
Same as with `parameterized`, with `pytest.mark.parametrize` you can have a fine control over which ... | 31_27_6 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#parametrization | .md | names for the sub-tests. Here is what they look like:
```bash
pytest test_this2.py --collect-only -q
```
and it will list:
```bash
test_this2.py::test_floor[integer-1-1.0]
test_this2.py::test_floor[negative--1.5--2.0]
test_this2.py::test_floor[large fraction-1.6-1]
```
So now you can run just the specific test:... | 31_27_7 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#files-and-directories | .md | 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 ... | 31_28_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#files-and-directories | .md | - `pathlib` objects (all fully resolved):
- `test_file_path` - the current test file path, i.e. `__file__`
- `test_file_dir` - the directory containing the current test file
- `tests_dir` - the directory of the `tests` test suite
- `examples_dir` - the directory of the `examples` test suite
- `repo_root_dir` - the di... | 31_28_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#files-and-directories | .md | - `src_dir` - the directory of `src` (i.e. where the `transformers` sub-dir resides)
- stringified paths---same as above but these return paths as strings, rather than `pathlib` objects:
- `test_file_path_str`
- `test_file_dir_str`
- `tests_dir_str`
- `examples_dir_str`
- `repo_root_dir_str`
- `src_dir_str`
To st... | 31_28_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#files-and-directories | .md | `transformers.test_utils.TestCasePlus`. For example:
```python
from transformers.testing_utils import TestCasePlus | 31_28_3 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#files-and-directories | .md | class PathExampleTest(TestCasePlus):
def test_something_involving_local_locations(self):
data_dir = self.tests_dir / "fixtures/tests_samples/wmt_en_ro"
```
If you don't need to manipulate paths via `pathlib` or you just need a path as a string, you can always invoked
`str()` on the `pathlib` object or use the accesso... | 31_28_4 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#files-and-directories | .md | class PathExampleTest(TestCasePlus):
def test_something_involving_stringified_locations(self):
examples_dir = self.examples_dir_str
``` | 31_28_5 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#temporary-files-and-directories | .md | 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... | 31_29_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#temporary-files-and-directories | .md | However, when debugging tests, you need to be able to see what goes into the temporary file or directory and you want
to know it's exact path and not having it randomized on every test re-run.
A helper class `transformers.test_utils.TestCasePlus` is best used for such purposes. It's a sub-class of
`unittest.TestCase`... | 31_29_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#temporary-files-and-directories | .md | class ExamplesTests(TestCasePlus):
def test_whatever(self):
tmp_dir = self.get_auto_remove_tmp_dir()
```
This code creates a unique temporary directory, and sets `tmp_dir` to its location.
- Create a unique temporary dir:
```python
def test_whatever(self):
tmp_dir = self.get_auto_remove_tmp_dir()
```
`tmp_dir` ... | 31_29_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#temporary-files-and-directories | .md | ```
`tmp_dir` will contain the path to the created temporary dir. It will be automatically removed at the end of the
test.
- Create a temporary dir of my choice, ensure it's empty before the test starts and don't empty it after the test.
```python
def test_whatever(self):
tmp_dir = self.get_auto_remove_tmp_dir(".... | 31_29_3 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#temporary-files-and-directories | .md | leave any data in there.
- You can override the default behavior by directly overriding the `before` and `after` args, leading to one of the
following behaviors:
- `before=True`: the temporary dir will always be cleared at the beginning of the test.
- `before=False`: if the temporary dir already existed, any existi... | 31_29_4 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#temporary-files-and-directories | .md | - `after=True`: the temporary dir will always be deleted at the end of the test.
- `after=False`: the temporary dir will always be left intact at the end of the test.
<Tip>
In order to run the equivalent of `rm -r` safely, only subdirs of the project repository checkout are allowed if
an explicit `tmp_dir` is used,... | 31_29_5 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#temporary-files-and-directories | .md | get nuked. i.e. please always pass paths that start with `./`.
</Tip>
<Tip>
Each test can register multiple temporary directories and they all will get auto-removed, unless requested
otherwise.
</Tip> | 31_29_6 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#temporary-syspath-override | .md | 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... | 31_30_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#skipping-tests | .md | 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... | 31_31_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#skipping-tests | .md | running the test altogether. Common examples are skipping windows-only tests on non-windows platforms, or skipping
tests that depend on an external resource which is not available at the moment (for example a database).
- A **xfail** means that you expect a test to fail for some reason. A common example is a test fo... | 31_31_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#skipping-tests | .md | implemented, or a bug not yet fixed. When a test passes despite being expected to fail (marked with
pytest.mark.xfail), it’s an xpass and will be reported in the test summary.
One of the important differences between the two is that `skip` doesn't run the test, and `xfail` does. So if the
code that's buggy causes som... | 31_31_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#implementation | .md | - 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... | 31_32_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#implementation | .md | ```python
def test_feature_x():
if not has_something():
pytest.skip("unsupported configuration")
```
or the whole module:
```python
import pytest | 31_32_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#implementation | .md | if not pytest.config.getoption("--custom-flag"):
pytest.skip("--custom-flag is missing, skipping tests", allow_module_level=True)
```
or the `xfail` way:
```python
def test_feature_x():
pytest.xfail("expected to fail until bug XYZ is fixed")
```
- Here is how to skip all tests in a module if some import is missin... | 31_32_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#implementation | .md | docutils = pytest.importorskip("docutils", minversion="0.3")
```
- Skip a test based on a condition:
```python no-style
@pytest.mark.skipif(sys.version_info < (3,6), reason="requires python3.6 or higher")
def test_feature_x():
```
or:
```python no-style
@unittest.skipIf(torch_device == "cpu", "Can't do half pr... | 31_32_3 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#implementation | .md | ```python no-style
@pytest.mark.skipif(sys.platform == 'win32', reason="does not run on windows")
class TestClass():
def test_feature_x(self):
```
More details, example and ways are [here](https://docs.pytest.org/en/latest/skipping.html). | 31_32_4 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#slow-tests | .md | 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... | 31_33_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#slow-tests | .md | Once a test is marked as `@slow`, to run such tests set `RUN_SLOW=1` env var, e.g.:
```bash
RUN_SLOW=1 pytest tests
```
Some decorators like `@parameterized` rewrite test names, therefore `@slow` and the rest of the skip decorators
`@require_*` have to be listed last for them to work correctly. Here is an example o... | 31_33_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#slow-tests | .md | ```python no-style
@parameterized.expand(...)
@slow
def test_integration_foo():
```
As explained at the beginning of this document, slow tests get to run on a scheduled basis, rather than in PRs CI
checks. So it's possible that some problems will be missed during a PR submission and get merged. Such problems will
get... | 31_33_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#slow-tests | .md | machine before submitting the PR.
Here is a rough decision making mechanism for choosing which tests should be marked as slow:
If the test is focused on one of the library's internal components (e.g., modeling files, tokenization files,
pipelines), then we should run that test in the non-slow test suite. If it's fo... | 31_33_3 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#slow-tests | .md | such as the documentation or the examples, then we should run these tests in the slow test suite. And then, to refine
this approach we should have exceptions:
- All tests that need to download a heavy set of weights or a dataset that is larger than ~50MB (e.g., model or
tokenizer integration tests, pipeline integrati... | 31_33_4 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#slow-tests | .md | should create and upload to the hub a tiny version of it (with random weights) for integration tests. This is
discussed in the following paragraphs.
- All tests that need to do a training not specifically optimized to be fast should be set to slow.
- We can introduce exceptions if some of these should-be-non-slow tests... | 31_33_5 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#slow-tests | .md | `@slow`. Auto-modeling tests, which save and load large files to disk, are a good example of tests that are marked
as `@slow`.
- If a test completes under 1 second on CI (including downloads if any) then it should be a normal test regardless.
Collectively, all the non-slow tests need to cover entirely the different i... | 31_33_6 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#slow-tests | .md | a significant coverage can be achieved by testing with specially created tiny models with random weights. Such models
have the very minimal number of layers (e.g., 2), vocab size (e.g., 1000), etc. Then the `@slow` tests can use large
slow models to do qualitative testing. To see the use of these simply look for *tiny*... | 31_33_7 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#slow-tests | .md | ```bash
grep tiny tests examples
```
Here is an example of a [script](https://github.com/huggingface/transformers/tree/main/scripts/fsmt/fsmt-make-tiny-model.py) that created the tiny model
[stas/tiny-wmt19-en-de](https://huggingface.co/stas/tiny-wmt19-en-de). You can easily adjust it to your specific
model's archite... | 31_33_8 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#slow-tests | .md | It's easy to measure the run-time incorrectly if for example there is an overheard of downloading a huge model, but if
you test it locally the downloaded files would be cached and thus the download time not measured. Hence check the
execution speed report in CI logs instead (the output of `pytest --durations=0 tests`).... | 31_33_9 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#slow-tests | .md | That report is also useful to find slow outliers that aren't marked as such, or which need to be re-written to be fast.
If you notice that the test suite starts getting slow on CI, the top listing of this report will show the slowest
tests. | 31_33_10 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#testing-the-stdoutstderr-output | .md | 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... | 31_34_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#testing-the-stdoutstderr-output | .md | def test_result_and_stdout(capsys):
msg = "Hello"
print_to_stdout(msg)
print_to_stderr(msg)
out, err = capsys.readouterr() # consume the captured output streams
# optional: if you want to replay the consumed streams:
sys.stdout.write(out)
sys.stderr.write(err)
# test:
assert msg in out
assert msg in err
```
And, of ... | 31_34_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/testing.md | https://huggingface.co/docs/transformers/en/testing/#testing-the-stdoutstderr-output | .md | def test_something_exception():
msg = "Not a good value"
error = ""
try:
raise_exception(msg)
except Exception as e:
error = str(e)
assert msg in error, f"{msg} is in the exception:\n{error}"
```
Another approach to capturing stdout is via `contextlib.redirect_stdout`:
```python
from io import StringIO
from context... | 31_34_2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.