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 |
|---|---|---|---|---|---|
<Tip>
Creating an inference engine is a complex topic, and the "best" solution
will most likely depend on your problem space. Are you on CPU or GPU? Do
you want the lowest latency, the highest throughput, support for
many models, or just highly optimize 1 specific model?
There are many ways to tackle this topic, so wha... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/pipeline_webserver.md | https://huggingface.co/docs/transformers/en/pipeline_webserver/#using-pipelines-for-a-webserver | #using-pipelines-for-a-webserver | .md | 39_1 |
There's a lot that can go wrong in production: out of memory, out of space,
loading the model might fail, the query might be wrong, the query might be
correct but still fail to run because of a model misconfiguration, and so on.
Generally, it's good if the server outputs the errors to the user, so
adding a lot of `tr... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/pipeline_webserver.md | https://huggingface.co/docs/transformers/en/pipeline_webserver/#error-checking | #error-checking | .md | 39_2 |
Webservers usually look better when they do circuit breaking. It means they
return proper errors when they're overloaded instead of just waiting for the query indefinitely. Return a 503 error instead of waiting for a super long time or a 504 after a long time.
This is relatively easy to implement in the proposed code... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/pipeline_webserver.md | https://huggingface.co/docs/transformers/en/pipeline_webserver/#circuit-breaking | #circuit-breaking | .md | 39_3 |
Currently PyTorch is not async aware, and computation will block the main
thread while running. That means it would be better if PyTorch was forced to run
on its own thread/process. This wasn't done here because the code is a lot more
complex (mostly because threads and async and queues don't play nice together).
But u... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/pipeline_webserver.md | https://huggingface.co/docs/transformers/en/pipeline_webserver/#blocking-the-main-thread | #blocking-the-main-thread | .md | 39_4 |
In general, batching is not necessarily an improvement over passing 1 item at
a time (see [batching details](./main_classes/pipelines#pipeline-batching) for more information). But it can be very effective
when used in the correct setting. In the API, there is no dynamic
batching by default (too much opportunity for a s... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/pipeline_webserver.md | https://huggingface.co/docs/transformers/en/pipeline_webserver/#dynamic-batching | #dynamic-batching | .md | 39_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/tokenizer_summary.md | https://huggingface.co/docs/transformers/en/tokenizer_summary/ | .md | 40_0 | |
[[open-in-colab]]
On this page, we will have a closer look at tokenization.
<Youtube id="VFp38yj8h3A"/>
As we saw in [the preprocessing tutorial](preprocessing), tokenizing a text is splitting it into words or
subwords, which then are converted to ids through a look-up table. Converting words or subwords to ids i... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tokenizer_summary.md | https://huggingface.co/docs/transformers/en/tokenizer_summary/#summary-of-the-tokenizers | #summary-of-the-tokenizers | .md | 40_1 |
Splitting a text into smaller chunks is a task that is harder than it looks, and there are multiple ways of doing so.
For instance, let's look at the sentence `"Don't you love 🤗 Transformers? We sure do."`
<Youtube id="nhJxYji1aho"/>
A simple way of tokenizing this text is to split it by spaces, which would give: ... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tokenizer_summary.md | https://huggingface.co/docs/transformers/en/tokenizer_summary/#introduction | #introduction | .md | 40_2 |
<Youtube id="zHvTiHr506c"/>
Subword tokenization algorithms rely on the principle that frequently used words should not be split into smaller
subwords, but rare words should be decomposed into meaningful subwords. For instance `"annoyingly"` might be
considered a rare word and could be decomposed into `"annoying"` an... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tokenizer_summary.md | https://huggingface.co/docs/transformers/en/tokenizer_summary/#subword-tokenization | #subword-tokenization | .md | 40_3 |
Byte-Pair Encoding (BPE) was introduced in [Neural Machine Translation of Rare Words with Subword Units (Sennrich et
al., 2015)](https://arxiv.org/abs/1508.07909). BPE relies on a pre-tokenizer that splits the training data into
words. Pretokenization can be as simple as space tokenization, e.g. [GPT-2](model_doc/gpt2)... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tokenizer_summary.md | https://huggingface.co/docs/transformers/en/tokenizer_summary/#byte-pair-encoding-bpe | #byte-pair-encoding-bpe | .md | 40_4 |
A base vocabulary that includes all possible base characters can be quite large if *e.g.* all unicode characters are
considered as base characters. To have a better base vocabulary, [GPT-2](https://cdn.openai.com/better-language-models/language_models_are_unsupervised_multitask_learners.pdf) uses bytes
as the base voca... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tokenizer_summary.md | https://huggingface.co/docs/transformers/en/tokenizer_summary/#byte-level-bpe | #byte-level-bpe | .md | 40_5 |
WordPiece is the subword tokenization algorithm used for [BERT](model_doc/bert), [DistilBERT](model_doc/distilbert), and [Electra](model_doc/electra). The algorithm was outlined in [Japanese and Korean
Voice Search (Schuster et al., 2012)](https://static.googleusercontent.com/media/research.google.com/ja//pubs/archive/... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tokenizer_summary.md | https://huggingface.co/docs/transformers/en/tokenizer_summary/#wordpiece | #wordpiece | .md | 40_6 |
Unigram is a subword tokenization algorithm introduced in [Subword Regularization: Improving Neural Network Translation
Models with Multiple Subword Candidates (Kudo, 2018)](https://arxiv.org/pdf/1804.10959.pdf). In contrast to BPE or
WordPiece, Unigram initializes its base vocabulary to a large number of symbols and p... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tokenizer_summary.md | https://huggingface.co/docs/transformers/en/tokenizer_summary/#unigram | #unigram | .md | 40_7 |
All tokenization algorithms described so far have the same problem: It is assumed that the input text uses spaces to
separate words. However, not all languages use spaces to separate words. One possible solution is to use language
specific pre-tokenizers, *e.g.* [XLM](model_doc/xlm) uses a specific Chinese, Japanese, a... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/tokenizer_summary.md | https://huggingface.co/docs/transformers/en/tokenizer_summary/#sentencepiece | #sentencepiece | .md | 40_8 |
<!--Copyright 2024 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/deepspeed.md | https://huggingface.co/docs/transformers/en/deepspeed/ | .md | 41_0 | |
[DeepSpeed](https://www.deepspeed.ai/) is a PyTorch optimization library that makes distributed training memory-efficient and fast. At its core is the [Zero Redundancy Optimizer (ZeRO)](https://hf.co/papers/1910.02054) which enables training large models at scale. ZeRO works in several stages:
* ZeRO-1, optimizer sta... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/deepspeed.md | https://huggingface.co/docs/transformers/en/deepspeed/#deepspeed | #deepspeed | .md | 41_1 |
DeepSpeed is available to install from PyPI or Transformers (for more detailed installation options, take a look at the DeepSpeed [installation details](https://www.deepspeed.ai/tutorials/advanced-install/) or the GitHub [README](https://github.com/microsoft/deepspeed#installation)).
<Tip>
If you're having difficul... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/deepspeed.md | https://huggingface.co/docs/transformers/en/deepspeed/#installation | #installation | .md | 41_2 |
Before you begin, it is a good idea to check whether you have enough GPU and CPU memory to fit your model. DeepSpeed provides a tool for estimating the required CPU/GPU memory. For example, to estimate the memory requirements for the [bigscience/T0_3B](bigscience/T0_3B) model on a single GPU:
```bash
$ python -c 'fro... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/deepspeed.md | https://huggingface.co/docs/transformers/en/deepspeed/#memory-requirements | #memory-requirements | .md | 41_3 |
After you've installed DeepSpeed and have a better idea of your memory requirements, the next step is selecting a ZeRO stage to use. In order of fastest and most memory-efficient:
| Fastest | Memory efficient |
|------------------|------------------|
| ZeRO-1 | ZeRO-3 + offload |
| ZeRO-2 ... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/deepspeed.md | https://huggingface.co/docs/transformers/en/deepspeed/#select-a-zero-stage | #select-a-zero-stage | .md | 41_4 |
DeepSpeed works with the [`Trainer`] class by way of a config file containing all the parameters for configuring how you want setup your training run. When you execute your training script, DeepSpeed logs the configuration it received from [`Trainer`] to the console so you can see exactly what configuration was used. ... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/deepspeed.md | https://huggingface.co/docs/transformers/en/deepspeed/#deepspeed-configuration-file | #deepspeed-configuration-file | .md | 41_5 |
There are three types of configuration parameters:
1. Some of the configuration parameters are shared by [`Trainer`] and DeepSpeed, and it can be difficult to identify errors when there are conflicting definitions. To make it easier, these shared configuration parameters are configured from the [`Trainer`] command li... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/deepspeed.md | https://huggingface.co/docs/transformers/en/deepspeed/#deepspeed-and-trainer-parameters | #deepspeed-and-trainer-parameters | .md | 41_6 |
There are three configurations, each corresponding to a different ZeRO stage. Stage 1 is not as interesting for scalability, and this guide focuses on stages 2 and 3. The `zero_optimization` configuration contains all the options for what to enable and how to configure them. For a more detailed explanation of each para... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/deepspeed.md | https://huggingface.co/docs/transformers/en/deepspeed/#zero-configuration | #zero-configuration | .md | 41_7 |
[ZeRO-Infinity](https://hf.co/papers/2104.07857) allows offloading model states to the CPU and/or NVMe to save even more memory. Smart partitioning and tiling algorithms allow each GPU to send and receive very small amounts of data during offloading such that a modern NVMe can fit an even larger total memory pool than ... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/deepspeed.md | https://huggingface.co/docs/transformers/en/deepspeed/#nvme-configuration | #nvme-configuration | .md | 41_8 |
There are a number of important parameters to specify in the DeepSpeed configuration file which are briefly described in this section. | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/deepspeed.md | https://huggingface.co/docs/transformers/en/deepspeed/#deepspeed-features | #deepspeed-features | .md | 41_9 |
Activation and gradient checkpointing trades speed for more GPU memory which allows you to overcome scenarios where your GPU is out of memory or to increase your batch size for better performance. To enable this feature:
1. For a Hugging Face model, set `model.gradient_checkpointing_enable()` or `--gradient_checkpoin... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/deepspeed.md | https://huggingface.co/docs/transformers/en/deepspeed/#activationgradient-checkpointing | #activationgradient-checkpointing | .md | 41_10 |
DeepSpeed and Transformers optimizer and scheduler can be mixed and matched as long as you don't enable `offload_optimizer`. When `offload_optimizer` is enabled, you could use a non-DeepSpeed optimizer (except for LAMB) as long as it has both a CPU and GPU implementation.
<Tip warning={true}>
The optimizer and sche... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/deepspeed.md | https://huggingface.co/docs/transformers/en/deepspeed/#optimizer-and-scheduler | #optimizer-and-scheduler | .md | 41_11 |
Deepspeed supports fp32, fp16, and bf16 mixed precision.
<hfoptions id="precision">
<hfoption id="fp32">
If your model doesn't work well with mixed precision, for example if it wasn't pretrained in mixed precision, you may encounter overflow or underflow issues which can cause NaN loss. For these cases, you should ... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/deepspeed.md | https://huggingface.co/docs/transformers/en/deepspeed/#precision | #precision | .md | 41_12 |
The batch size can be auto-configured or explicitly set. If you choose to use the `"auto"` option, [`Trainer`] sets `train_micro_batch_size_per_gpu` to the value of args.`per_device_train_batch_size` and `train_batch_size` to `args.world_size * args.per_device_train_batch_size * args.gradient_accumulation_steps`.
```... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/deepspeed.md | https://huggingface.co/docs/transformers/en/deepspeed/#batch-size | #batch-size | .md | 41_13 |
Gradient accumulation can be auto-configured or explicitly set. If you choose to use the `"auto"` option, [`Trainer`] sets it to the value of `args.gradient_accumulation_steps`.
```yaml
{
"gradient_accumulation_steps": "auto"
}
``` | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/deepspeed.md | https://huggingface.co/docs/transformers/en/deepspeed/#gradient-accumulation | #gradient-accumulation | .md | 41_14 |
Gradient clipping can be auto-configured or explicitly set. If you choose to use the `"auto"` option, [`Trainer`] sets it to the value of `args.max_grad_norm`.
```yaml
{
"gradient_clipping": "auto"
}
``` | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/deepspeed.md | https://huggingface.co/docs/transformers/en/deepspeed/#gradient-clipping | #gradient-clipping | .md | 41_15 |
For communication collectives like reduction, gathering and scattering operations, a separate data type is used.
All gather and scatter operations are performed in the same data type the data is in. For example, if you're training with bf16, the data is also gathered in bf16 because gathering is a non-lossy operation... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/deepspeed.md | https://huggingface.co/docs/transformers/en/deepspeed/#communication-data-type | #communication-data-type | .md | 41_16 |
[Universal Checkpointing](https://www.deepspeed.ai/tutorials/universal-checkpointing) is an efficient and flexible feature for saving and loading model checkpoints. It enables seamless model training continuation and fine-tuning across different model architectures, parallelism techniques, and training configurations. ... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/deepspeed.md | https://huggingface.co/docs/transformers/en/deepspeed/#universal-checkpointing | #universal-checkpointing | .md | 41_17 |
DeepSpeed can be deployed by different launchers such as [torchrun](https://pytorch.org/docs/stable/elastic/run.html), the `deepspeed` launcher, or [Accelerate](https://huggingface.co/docs/accelerate/basic_tutorials/launch#using-accelerate-launch). To deploy, add `--deepspeed ds_config.json` to the [`Trainer`] command ... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/deepspeed.md | https://huggingface.co/docs/transformers/en/deepspeed/#deployment | #deployment | .md | 41_18 |
A node is one or more GPUs for running a workload. A more powerful setup is a multi-node setup which can be launched with the `deepspeed` launcher. For this guide, let's assume there are two nodes with 8 GPUs each. The first node can be accessed `ssh hostname1` and the second node with `ssh hostname2`. Both nodes must ... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/deepspeed.md | https://huggingface.co/docs/transformers/en/deepspeed/#multi-node-deployment | #multi-node-deployment | .md | 41_19 |
In a SLURM environment, you'll need to adapt your SLURM script to your specific SLURM environment. An example SLURM script may look like:
```bash
#SBATCH --job-name=test-nodes # name
#SBATCH --nodes=2 # nodes
#SBATCH --ntasks-per-node=1 # crucial - only 1 task per dist per node!
#SB... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/deepspeed.md | https://huggingface.co/docs/transformers/en/deepspeed/#slurm | #slurm | .md | 41_20 |
The `deepspeed` launcher doesn't support deployment from a notebook so you'll need to emulate the distributed environment. However, this only works for 1 GPU. If you want to use more than 1 GPU, you must use a multi-process environment for DeepSpeed to work. This means you have to use the `deepspeed` launcher which can... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/deepspeed.md | https://huggingface.co/docs/transformers/en/deepspeed/#notebook | #notebook | .md | 41_21 |
DeepSpeed stores the main full precision fp32 weights in custom checkpoint optimizer files (the glob pattern looks like `global_step*/*optim_states.pt`) and are saved under the normal checkpoint.
<hfoptions id="save">
<hfoption id="fp16">
A model trained with ZeRO-2 saves the pytorch_model.bin weights in fp16. To s... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/deepspeed.md | https://huggingface.co/docs/transformers/en/deepspeed/#save-model-weights | #save-model-weights | .md | 41_22 |
You must have saved at least one checkpoint to load the latest checkpoint as shown in the following:
```py
from transformers.trainer_utils import get_last_checkpoint
from deepspeed.utils.zero_to_fp32 import load_state_dict_from_zero_checkpoint
checkpoint_dir = get_last_checkpoint(trainer.args.output_dir)
fp32_model ... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/deepspeed.md | https://huggingface.co/docs/transformers/en/deepspeed/#online | #online | .md | 41_23 |
DeepSpeed provides a zero_to_fp32.py script at the top-level of the checkpoint folder for extracting weights at any point. This is a standalone script and you don't need a configuration file or [`Trainer`].
For example, if your checkpoint folder looked like this:
```bash
$ ls -l output_dir/checkpoint-1/
-rw-rw-r-- ... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/deepspeed.md | https://huggingface.co/docs/transformers/en/deepspeed/#offline | #offline | .md | 41_24 |
[ZeRO Inference](https://www.deepspeed.ai/2022/09/09/zero-inference.html) places the model weights in CPU or NVMe memory to avoid burdening the GPU which makes it possible to run inference with huge models on a GPU. Inference doesn't require any large additional amounts of memory for the optimizer states and gradients ... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/deepspeed.md | https://huggingface.co/docs/transformers/en/deepspeed/#zero-inference | #zero-inference | .md | 41_25 |
DeepSpeed also works with Transformers without the [`Trainer`] class. This is handled by the [`HfDeepSpeedConfig`] which only takes care of gathering ZeRO-3 parameters and splitting a model across multiple GPUs when you call [`~PreTrainedModel.from_pretrained`].
<Tip>
If you want everything automatically taken care... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/deepspeed.md | https://huggingface.co/docs/transformers/en/deepspeed/#non-trainer-deepspeed-integration | #non-trainer-deepspeed-integration | .md | 41_26 |
To run ZeRO Inference without the [`Trainer`] in cases where you can’t fit a model onto a single GPU, try using additional GPUs or/and offloading to CPU memory. The important nuance to understand here is that the way ZeRO is designed, you can process different inputs on different GPUs in parallel.
Make sure to:
* d... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/deepspeed.md | https://huggingface.co/docs/transformers/en/deepspeed/#non-trainer-zero-inference | #non-trainer-zero-inference | .md | 41_27 |
Using multiple GPUs with ZeRO-3 for generation requires synchronizing the GPUs by setting `synced_gpus=True` in the [`~GenerationMixin.generate`] method. Otherwise, if one GPU is finished generating before another one, the whole system hangs because the remaining GPUs haven't received the weight shard from the GPU that... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/deepspeed.md | https://huggingface.co/docs/transformers/en/deepspeed/#generate | #generate | .md | 41_28 |
When you encounter an issue, you should consider whether DeepSpeed is the cause of the problem because often it isn't (unless it's super obviously and you can see DeepSpeed modules in the exception)! The first step should be to retry your setup without DeepSpeed, and if the problem persists, then you can report the iss... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/deepspeed.md | https://huggingface.co/docs/transformers/en/deepspeed/#troubleshoot | #troubleshoot | .md | 41_29 |
When the DeepSpeed process is killed during launch without a traceback, that usually means the program tried to allocate more CPU memory than your system has or your process tried to allocate more CPU memory than allowed leading the OS kernel to terminate the process. In this case, check whether your configuration file... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/deepspeed.md | https://huggingface.co/docs/transformers/en/deepspeed/#deepspeed-process-killed-at-startup | #deepspeed-process-killed-at-startup | .md | 41_30 |
NaN loss often occurs when a model is pretrained in bf16 and then you try to use it with fp16 (especially relevant for TPU trained models). To resolve this, use fp32 or bf16 if your hardware supports it (TPU, Ampere GPUs or newer).
The other issue may be related to using fp16. For example, if this is your fp16 config... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/deepspeed.md | https://huggingface.co/docs/transformers/en/deepspeed/#nan-loss | #nan-loss | .md | 41_31 |
DeepSpeed ZeRO is a powerful technology for training and loading very large models for inference with limited GPU resources, making it more accessible to everyone. To learn more about DeepSpeed, feel free to read the [blog posts](https://www.microsoft.com/en-us/research/search/?q=deepspeed), [documentation](https://www... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/deepspeed.md | https://huggingface.co/docs/transformers/en/deepspeed/#resources | #resources | .md | 41_32 |
<!--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/index.md | https://huggingface.co/docs/transformers/en/index/ | .md | 42_0 | |
State-of-the-art Machine Learning for [PyTorch](https://pytorch.org/), [TensorFlow](https://www.tensorflow.org/), and [JAX](https://jax.readthedocs.io/en/latest/).
🤗 Transformers provides APIs and tools to easily download and train state-of-the-art pretrained models. Using pretrained models can reduce your compute c... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/index.md | https://huggingface.co/docs/transformers/en/index/#-transformers | #-transformers | .md | 42_1 |
<a target="_blank" href="https://huggingface.co/support">
<img alt="HuggingFace Expert Acceleration Program" src="https://cdn-media.huggingface.co/marketing/transformers/new-support-improved.png" style="width: 100%; max-width: 600px; border: 1px solid #eee; border-radius: 4px; box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/index.md | https://huggingface.co/docs/transformers/en/index/#if-you-are-looking-for-custom-support-from-the-hugging-face-team | #if-you-are-looking-for-custom-support-from-the-hugging-face-team | .md | 42_2 |
The documentation is organized into five sections:
- **GET STARTED** provides a quick tour of the library and installation instructions to get up and running.
- **TUTORIALS** are a great place to start if you're a beginner. This section will help you gain the basic skills you need to start using the library.
- **HOW-... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/index.md | https://huggingface.co/docs/transformers/en/index/#contents | #contents | .md | 42_3 |
The table below represents the current support in the library for each of those models, whether they have a Python
tokenizer (called "slow"). A "fast" tokenizer backed by the 🤗 Tokenizers library, whether they have support in Jax (via
Flax), PyTorch, and/or TensorFlow.
<!--This table is updated automatically from th... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/index.md | https://huggingface.co/docs/transformers/en/index/#supported-models-and-frameworks | #supported-models-and-frameworks | .md | 42_4 |
<!--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 agreed to... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/llm_tutorial_optimization.md | https://huggingface.co/docs/transformers/en/llm_tutorial_optimization/ | .md | 43_0 | |
[[open-in-colab]]
Large Language Models (LLMs) such as GPT3/4, [Falcon](https://huggingface.co/tiiuae/falcon-40b), and [Llama](https://huggingface.co/meta-llama/Llama-2-70b-hf) are rapidly advancing in their ability to tackle human-centric tasks, establishing themselves as essential tools in modern knowledge-based in... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/llm_tutorial_optimization.md | https://huggingface.co/docs/transformers/en/llm_tutorial_optimization/#optimizing-llms-for-speed-and-memory | #optimizing-llms-for-speed-and-memory | .md | 43_1 |
Memory requirements of LLMs can be best understood by seeing the LLM as a set of weight matrices and vectors and the text inputs as a sequence of vectors. In the following, the definition *weights* will be used to signify all model weight matrices and vectors.
At the time of writing this guide, LLMs consist of at lea... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/llm_tutorial_optimization.md | https://huggingface.co/docs/transformers/en/llm_tutorial_optimization/#1-lower-precision | #1-lower-precision | .md | 43_2 |
Today's top-performing LLMs share more or less the same fundamental architecture that consists of feed-forward layers, activation layers, layer normalization layers, and most crucially, self-attention layers.
Self-attention layers are central to Large Language Models (LLMs) in that they enable the model to understand... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/llm_tutorial_optimization.md | https://huggingface.co/docs/transformers/en/llm_tutorial_optimization/#2-flash-attention | #2-flash-attention | .md | 43_3 |
So far we have looked into improving computational and memory efficiency by:
- Casting the weights to a lower precision format
- Replacing the self-attention algorithm with a more memory- and compute efficient version
Let's now look into how we can change the architecture of an LLM so that it is most effective ... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/llm_tutorial_optimization.md | https://huggingface.co/docs/transformers/en/llm_tutorial_optimization/#3-architectural-innovations | #3-architectural-innovations | .md | 43_4 |
Self-attention puts each token in relation to each other's tokens.
As an example, the \\( \text{Softmax}(\mathbf{QK}^T) \\) matrix of the text input sequence *"Hello", "I", "love", "you"* could look as follows:

Each word token is given a probability mass at wh... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/llm_tutorial_optimization.md | https://huggingface.co/docs/transformers/en/llm_tutorial_optimization/#31-improving-positional-embeddings-of-llms | #31-improving-positional-embeddings-of-llms | .md | 43_5 |
Auto-regressive text generation with LLMs works by iteratively putting in an input sequence, sampling the next token, appending the next token to the input sequence, and continuing to do so until the LLM produces a token that signifies that the generation has finished.
Please have a look at [Transformer's Generate Te... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/llm_tutorial_optimization.md | https://huggingface.co/docs/transformers/en/llm_tutorial_optimization/#32-the-key-value-cache | #32-the-key-value-cache | .md | 43_6 |
The key-value cache is especially useful for applications such as chat where multiple passes of auto-regressive decoding are required. Let's look at an example.
```
User: How many people live in France?
Assistant: Roughly 75 million people live in France
User: And how many are in Germany?
Assistant: Germany has ca. 8... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/llm_tutorial_optimization.md | https://huggingface.co/docs/transformers/en/llm_tutorial_optimization/#321-multi-round-conversation | #321-multi-round-conversation | .md | 43_7 |
[Multi-Query-Attention](https://arxiv.org/abs/1911.02150) was proposed in Noam Shazeer's *Fast Transformer Decoding: One Write-Head is All You Need* paper. As the title says, Noam found out that instead of using `n_head` key-value projections weights, one can use a single head-value projection weight pair that is share... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/llm_tutorial_optimization.md | https://huggingface.co/docs/transformers/en/llm_tutorial_optimization/#322-multi-query-attention-mqa | #322-multi-query-attention-mqa | .md | 43_8 |
[Grouped-Query-Attention](https://arxiv.org/abs/2305.13245), as proposed by Ainslie et al. from Google, found that using MQA can often lead to quality degradation compared to using vanilla multi-key-value head projections. The paper argues that more model performance can be kept by less drastically reducing the number ... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/llm_tutorial_optimization.md | https://huggingface.co/docs/transformers/en/llm_tutorial_optimization/#323-grouped-query-attention-gqa | #323-grouped-query-attention-gqa | .md | 43_9 |
The research community is constantly coming up with new, nifty ways to speed up inference time for ever-larger LLMs. As an example, one such promising research direction is [speculative decoding](https://arxiv.org/abs/2211.17192) where "easy tokens" are generated by smaller, faster language models and only "hard tokens... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/llm_tutorial_optimization.md | https://huggingface.co/docs/transformers/en/llm_tutorial_optimization/#conclusion | #conclusion | .md | 43_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 a... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/contributing.md | https://huggingface.co/docs/transformers/en/contributing/ | .md | 44_0 | |
Everyone is welcome to contribute, and we value everybody's contribution. Code
contributions are not the only way to help the community. Answering questions, helping
others, and improving the documentation are also immensely valuable.
It also helps us if you spread the word! Reference the library in blog posts
about ... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/contributing.md | https://huggingface.co/docs/transformers/en/contributing/#contribute-to--transformers | #contribute-to--transformers | .md | 44_1 |
There are several ways you can contribute to 🤗 Transformers:
* Fix outstanding issues with the existing code.
* Submit issues related to bugs or desired new features.
* Implement new models.
* Contribute to the examples or to the documentation.
If you don't know where to start, there is a special [Good First
Issue... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/contributing.md | https://huggingface.co/docs/transformers/en/contributing/#ways-to-contribute | #ways-to-contribute | .md | 44_2 |
If you notice an issue with the existing code and have a fix in mind, feel free to [start contributing](#create-a-pull-request) and open a Pull Request! | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/contributing.md | https://huggingface.co/docs/transformers/en/contributing/#fixing-outstanding-issues | #fixing-outstanding-issues | .md | 44_3 |
Do your best to follow these guidelines when submitting a bug-related issue or a feature
request. It will make it easier for us to come back to you quickly and with good
feedback. | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/contributing.md | https://huggingface.co/docs/transformers/en/contributing/#submitting-a-bug-related-issue-or-feature-request | #submitting-a-bug-related-issue-or-feature-request | .md | 44_4 |
The 🤗 Transformers library is robust and reliable thanks to users who report the problems they encounter.
Before you report an issue, we would really appreciate it if you could **make sure the bug was not
already reported** (use the search bar on GitHub under Issues). Your issue should also be related to bugs in the... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/contributing.md | https://huggingface.co/docs/transformers/en/contributing/#did-you-find-a-bug | #did-you-find-a-bug | .md | 44_5 |
If there is a new feature you'd like to see in 🤗 Transformers, please open an issue and describe:
1. What is the *motivation* behind this feature? Is it related to a problem or frustration with the library? Is it a feature related to something you need for a project? Is it something you worked on and think it could ... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/contributing.md | https://huggingface.co/docs/transformers/en/contributing/#do-you-want-a-new-feature | #do-you-want-a-new-feature | .md | 44_6 |
New models are constantly released and if you want to implement a new model, please provide the following information:
* A short description of the model and a link to the paper.
* Link to the implementation if it is open-sourced.
* Link to the model weights if they are available.
If you are willing to contribute t... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/contributing.md | https://huggingface.co/docs/transformers/en/contributing/#do-you-want-to-implement-a-new-model | #do-you-want-to-implement-a-new-model | .md | 44_7 |
We're always looking for improvements to the documentation that make it more clear and accurate. Please let us know how the documentation can be improved such as typos and any content that is missing, unclear or inaccurate. We'll be happy to make the changes or help you make a contribution if you're interested!
For m... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/contributing.md | https://huggingface.co/docs/transformers/en/contributing/#do-you-want-to-add-documentation | #do-you-want-to-add-documentation | .md | 44_8 |
Before writing any code, we strongly advise you to search through the existing PRs or
issues to make sure nobody is already working on the same thing. If you are
unsure, it is always a good idea to open an issue to get some feedback.
You will need basic `git` proficiency to contribute to
🤗 Transformers. While `git` ... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/contributing.md | https://huggingface.co/docs/transformers/en/contributing/#create-a-pull-request | #create-a-pull-request | .md | 44_9 |
☐ The pull request title should summarize your contribution.<br>
☐ If your pull request addresses an issue, please mention the issue number in the pull
request description to make sure they are linked (and people viewing the issue know you
are working on it).<br>
☐ To indicate a work in progress please prefix the title... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/contributing.md | https://huggingface.co/docs/transformers/en/contributing/#pull-request-checklist | #pull-request-checklist | .md | 44_10 |
An extensive test suite is included to test the library behavior and several examples. Library tests can be found in
the [tests](https://github.com/huggingface/transformers/tree/main/tests) folder and examples tests in the
[examples](https://github.com/huggingface/transformers/tree/main/examples) folder.
We like `pyt... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/contributing.md | https://huggingface.co/docs/transformers/en/contributing/#tests | #tests | .md | 44_11 |
For documentation strings, 🤗 Transformers follows the [Google Python Style Guide](https://google.github.io/styleguide/pyguide.html).
Check our [documentation writing guide](https://github.com/huggingface/transformers/tree/main/docs#writing-documentation---specification)
for more information. | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/contributing.md | https://huggingface.co/docs/transformers/en/contributing/#style-guide | #style-guide | .md | 44_12 |
On Windows (unless you're working in [Windows Subsystem for Linux](https://learn.microsoft.com/en-us/windows/wsl/) or WSL), you need to configure git to transform Windows `CRLF` line endings to Linux `LF` line endings:
```bash
git config core.autocrlf input
```
One way to run the `make` command on Windows is with M... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/contributing.md | https://huggingface.co/docs/transformers/en/contributing/#develop-on-windows | #develop-on-windows | .md | 44_13 |
When updating the main branch of a forked repository, please follow these steps to avoid pinging the upstream repository which adds reference notes to each upstream PR, and sends unnecessary notifications to the developers involved in these PRs.
1. When possible, avoid syncing with the upstream using a branch and PR ... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/contributing.md | https://huggingface.co/docs/transformers/en/contributing/#sync-a-forked-repository-with-upstream-main-the-hugging-face-repository | #sync-a-forked-repository-with-upstream-main-the-hugging-face-repository | .md | 44_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/pipeline_tutorial.md | https://huggingface.co/docs/transformers/en/pipeline_tutorial/ | .md | 45_0 | |
The [`pipeline`] makes it simple to use any model from the [Hub](https://huggingface.co/models) for inference on any language, computer vision, speech, and multimodal tasks. Even if you don't have experience with a specific modality or aren't familiar with the underlying code behind the models, you can still use them f... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/pipeline_tutorial.md | https://huggingface.co/docs/transformers/en/pipeline_tutorial/#pipelines-for-inference | #pipelines-for-inference | .md | 45_1 |
While each task has an associated [`pipeline`], it is simpler to use the general [`pipeline`] abstraction which contains
all the task-specific pipelines. The [`pipeline`] automatically loads a default model and a preprocessing class capable
of inference for your task. Let's take the example of using the [`pipeline`] fo... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/pipeline_tutorial.md | https://huggingface.co/docs/transformers/en/pipeline_tutorial/#pipeline-usage | #pipeline-usage | .md | 45_2 |
[`pipeline`] supports many parameters; some are task specific, and some are general to all pipelines.
In general, you can specify parameters anywhere you want:
```py
transcriber = pipeline(model="openai/whisper-large-v2", my_parameter=1)
out = transcriber(...) # This will use `my_parameter=1`.
out = transcriber(...... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/pipeline_tutorial.md | https://huggingface.co/docs/transformers/en/pipeline_tutorial/#parameters | #parameters | .md | 45_3 |
If you use `device=n`, the pipeline automatically puts the model on the specified device.
This will work regardless of whether you are using PyTorch or Tensorflow.
```py
transcriber = pipeline(model="openai/whisper-large-v2", device=0)
```
If the model is too large for a single GPU and you are using PyTorch, you ca... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/pipeline_tutorial.md | https://huggingface.co/docs/transformers/en/pipeline_tutorial/#device | #device | .md | 45_4 |
By default, pipelines will not batch inference for reasons explained in detail [here](https://huggingface.co/docs/transformers/main_classes/pipelines#pipeline-batching). The reason is that batching is not necessarily faster, and can actually be quite slower in some cases.
But if it works in your use case, you can use... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/pipeline_tutorial.md | https://huggingface.co/docs/transformers/en/pipeline_tutorial/#batch-size | #batch-size | .md | 45_5 |
All tasks provide task specific parameters which allow for additional flexibility and options to help you get your job done.
For instance, the [`transformers.AutomaticSpeechRecognitionPipeline.__call__`] method has a `return_timestamps` parameter which sounds promising for subtitling videos:
```py
>>> transcriber = p... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/pipeline_tutorial.md | https://huggingface.co/docs/transformers/en/pipeline_tutorial/#task-specific-parameters | #task-specific-parameters | .md | 45_6 |
The pipeline can also run inference on a large dataset. The easiest way we recommend doing this is by using an iterator:
```py
def data():
for i in range(1000):
yield f"My example {i}"
pipe = pipeline(model="openai-community/gpt2", device=0)
generated_characters = 0
for out in pipe(data()):
generated_characters += ... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/pipeline_tutorial.md | https://huggingface.co/docs/transformers/en/pipeline_tutorial/#using-pipelines-on-a-dataset | #using-pipelines-on-a-dataset | .md | 45_7 |
<Tip>
Creating an inference engine is a complex topic which deserves it's own
page.
</Tip>
[Link](./pipeline_webserver) | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/pipeline_tutorial.md | https://huggingface.co/docs/transformers/en/pipeline_tutorial/#using-pipelines-for-a-webserver | #using-pipelines-for-a-webserver | .md | 45_8 |
Using a [`pipeline`] for vision tasks is practically identical.
Specify your task and pass your image to the classifier. The image can be a link, a local path or a base64-encoded image. For example, what species of cat is shown below?

>>> class... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/pipeline_tutorial.md | https://huggingface.co/docs/transformers/en/pipeline_tutorial/#text-pipeline | #text-pipeline | .md | 45_10 |
The [`pipeline`] supports more than one modality. For example, a visual question answering (VQA) task combines text and image. Feel free to use any image link you like and a question you want to ask about the image. The image can be a URL or a local path to the image.
For example, if you use this [invoice image](http... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/pipeline_tutorial.md | https://huggingface.co/docs/transformers/en/pipeline_tutorial/#multimodal-pipeline | #multimodal-pipeline | .md | 45_11 |
You can easily run `pipeline` on large models using 🤗 `accelerate`! First make sure you have installed `accelerate` with `pip install accelerate`.
First load your model using `device_map="auto"`! We will use `facebook/opt-1.3b` for our example.
```py
# pip install accelerate
import torch
from transformers import p... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/pipeline_tutorial.md | https://huggingface.co/docs/transformers/en/pipeline_tutorial/#using-pipeline-on-large-models-with--accelerate | #using-pipeline-on-large-models-with--accelerate | .md | 45_12 |
Pipelines are automatically supported in [Gradio](https://github.com/gradio-app/gradio/), a library that makes creating beautiful and user-friendly machine learning apps on the web a breeze. First, make sure you have Gradio installed:
```
pip install gradio
```
Then, you can create a web demo around an image classi... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/pipeline_tutorial.md | https://huggingface.co/docs/transformers/en/pipeline_tutorial/#creating-web-demos-from-pipelines-with-gradio | #creating-web-demos-from-pipelines-with-gradio | .md | 45_13 |
<!--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 agr... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/fsdp.md | https://huggingface.co/docs/transformers/en/fsdp/ | .md | 46_0 | |
[Fully Sharded Data Parallel (FSDP)](https://pytorch.org/blog/introducing-pytorch-fully-sharded-data-parallel-api/) is a data parallel method that shards a model's parameters, gradients and optimizer states across the number of available GPUs (also called workers or *rank*). Unlike [DistributedDataParallel (DDP)](https... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/fsdp.md | https://huggingface.co/docs/transformers/en/fsdp/#fully-sharded-data-parallel | #fully-sharded-data-parallel | .md | 46_1 |
To start, run the [`accelerate config`](https://huggingface.co/docs/accelerate/package_reference/cli#accelerate-config) command to create a configuration file for your training environment. Accelerate uses this configuration file to automatically setup the correct training environment based on your selected training op... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/fsdp.md | https://huggingface.co/docs/transformers/en/fsdp/#fsdp-configuration | #fsdp-configuration | .md | 46_2 |
FSDP offers a number of sharding strategies to select from:
* `FULL_SHARD` - shards model parameters, gradients and optimizer states across workers; select `1` for this option
* `SHARD_GRAD_OP`- shard gradients and optimizer states across workers; select `2` for this option
* `NO_SHARD` - don't shard anything (this i... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/fsdp.md | https://huggingface.co/docs/transformers/en/fsdp/#sharding-strategy | #sharding-strategy | .md | 46_3 |
You could also offload parameters and gradients when they are not in use to the CPU to save even more GPU memory and help you fit large models where even FSDP may not be sufficient. This is enabled by setting `fsdp_offload_params: true` when running `accelerate config`. | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/fsdp.md | https://huggingface.co/docs/transformers/en/fsdp/#cpu-offload | #cpu-offload | .md | 46_4 |
FSDP is applied by wrapping each layer in the network. The wrapping is usually applied in a nested way where the full weights are discarded after each forward pass to save memory for use in the next layer. The *auto wrapping* policy is the simplest way to implement this and you don't need to change any code. You should... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/fsdp.md | https://huggingface.co/docs/transformers/en/fsdp/#wrapping-policy | #wrapping-policy | .md | 46_5 |
Intermediate checkpoints should be saved with `fsdp_state_dict_type: SHARDED_STATE_DICT` because saving the full state dict with CPU offloading on rank 0 takes a lot of time and often results in `NCCL Timeout` errors due to indefinite hanging during broadcasting. You can resume training with the sharded state dicts wit... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/fsdp.md | https://huggingface.co/docs/transformers/en/fsdp/#checkpointing | #checkpointing | .md | 46_6 |
[PyTorch XLA](https://pytorch.org/xla/release/2.1/index.html) supports FSDP training for TPUs and it can be enabled by modifying the FSDP configuration file generated by `accelerate config`. In addition to the sharding strategies and wrapping options specified above, you can add the parameters shown below to the file. ... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/fsdp.md | https://huggingface.co/docs/transformers/en/fsdp/#tpu | #tpu | .md | 46_7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.