# embedding_metadata

key: _node_content
string_value:
{"id_": "4e892dc1-6f80-440e-b629-d1b982778b5e", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "3d4a5be0-96a4-4cae-bb80-ec65cee94a22", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "bb1f2b699b61342ca13b75611df36eb9e3379ec4485edf0807dfbeb683246cf4", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "17b258bf-820c-47fe-a6b9-1f60fdea0a48", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "8ff82756446e934344f8c369afa75167858611f14496a80b6b90afb23121a0eb", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "72e72914-2272-4d9f-8e9e-3d3417fa3d6c", "node_type": "1", "metadata": {}, "hash": "c832afa7bcef6ea2ae20d8655703169ec0723f3edd6dab0de438c5a0c675a7a9", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 40705, "end_char_idx": 44120, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
The length of the key-value cache on the other hand is increased by one at every decoding step.

> Making use of the key-value cache means that the \\( \mathbf{QK}^T \\) is essentially reduced to \\( \mathbf{q}_c\mathbf{K}^T \\) with \\( \mathbf{q}_c \\) being the query projection of the currently passed input token which is *always* just a single vector.

Using the key-value cache has two advantages:
-   Significant increase in computational efficiency as less computations are performed compared to computing the full \\( \mathbf{QK}^T \\) matrix. This leads to an increase in inference speed
-   The maximum required memory is not increased quadratically with the number of generated tokens, but only increases linearly.

> One should *always* make use of the key-value cache as it leads to identical results and a significant speed-up for longer input sequences. Transformers has the key-value cache enabled by default when making use of the text pipeline or the [`generate` method](https://huggingface.co/docs/transformers/main_classes/text_generation).

<Tip warning={true}>

Note that, despite our advice to use key-value caches, your LLM output may be slightly different when you use them. This is a property of the matrix multiplication kernels themselves -- you can read more about it [here](https://github.com/huggingface/transformers/issues/25420#issuecomment-1775317535).

</Tip>

#### 3.2.1 Multi-round conversation

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. 81 million inhabitants
```

In this chat, the LLM runs auto-regressive decoding twice:
  1. The first time, the key-value cache is empty and the input prompt is `"User: How many people live in France?"` and the model auto-regressively generates the text `"Roughly 75 million people live in France"` while increasing the key-value cache at every decoding step.
  2. The second time the input prompt is `"User: How many people live in France? \n Assistant: Roughly 75 million people live in France \n User: And how many in Germany?"`. Thanks to the cache, all key-value vectors for the first two sentences are already computed. Therefore the input prompt only consists of `"User: And how many in Germany?"`. While processing the shortened input prompt, its computed key-value vectors are concatenated to the key-value cache of the first decoding. The second Assistant's answer `"Germany has ca. 81 million inhabitants"` is then auto-regressively generated with the key-value cache consisting of encoded key-value vectors of `"User: How many people live in France? \n Assistant: Roughly 75 million people live in France \n User: And how many are in Germany?"`.

Two things should be noted here:
  1. Keeping all the context is crucial for LLMs deployed in chat so that the LLM understands all the previous context of the conversation. E.g. for the example above the LLM needs to understand that the user refers to the population when asking `"And how many are in Germany"`.
  2. The key-value cache is extremely useful for chat as it allows us to continuously grow the encoded chat history instead of having to re-encode the chat history again from scratch (as e.g.


key: _node_content
string_value:
{"id_": "72e72914-2272-4d9f-8e9e-3d3417fa3d6c", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "3d4a5be0-96a4-4cae-bb80-ec65cee94a22", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "bb1f2b699b61342ca13b75611df36eb9e3379ec4485edf0807dfbeb683246cf4", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "4e892dc1-6f80-440e-b629-d1b982778b5e", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "8c9a8999caaeca3a1567cab8d7d0b9f1920bb677fa357b0b1c0b626a04de010f", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "ac613e7e-f1c8-40e1-a601-600b2b493e5a", "node_type": "1", "metadata": {}, "hash": "e6a25a528f08e3d1fa9da16f79acd34fba42d3e739ac537ec1924e877d695fd9", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 42431, "end_char_idx": 45856, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Assistant: Germany has ca. 81 million inhabitants
```

In this chat, the LLM runs auto-regressive decoding twice:
  1. The first time, the key-value cache is empty and the input prompt is `"User: How many people live in France?"` and the model auto-regressively generates the text `"Roughly 75 million people live in France"` while increasing the key-value cache at every decoding step.
  2. The second time the input prompt is `"User: How many people live in France? \n Assistant: Roughly 75 million people live in France \n User: And how many in Germany?"`. Thanks to the cache, all key-value vectors for the first two sentences are already computed. Therefore the input prompt only consists of `"User: And how many in Germany?"`. While processing the shortened input prompt, its computed key-value vectors are concatenated to the key-value cache of the first decoding. The second Assistant's answer `"Germany has ca. 81 million inhabitants"` is then auto-regressively generated with the key-value cache consisting of encoded key-value vectors of `"User: How many people live in France? \n Assistant: Roughly 75 million people live in France \n User: And how many are in Germany?"`.

Two things should be noted here:
  1. Keeping all the context is crucial for LLMs deployed in chat so that the LLM understands all the previous context of the conversation. E.g. for the example above the LLM needs to understand that the user refers to the population when asking `"And how many are in Germany"`.
  2. The key-value cache is extremely useful for chat as it allows us to continuously grow the encoded chat history instead of having to re-encode the chat history again from scratch (as e.g. would be the case when using an encoder-decoder architecture).

In `transformers`, a `generate` call will return `past_key_values` when `return_dict_in_generate=True` is passed, in addition to the default `use_cache=True`. Note that it is not yet available through the `pipeline` interface.

```python
# Generation as usual
prompt = system_prompt + "Question: Please write a function in Python that transforms bytes to Giga bytes.\n\nAnswer: Here"
model_inputs = tokenizer(prompt, return_tensors='pt')
generation_output = model.generate(**model_inputs, max_new_tokens=60, return_dict_in_generate=True)
decoded_output = tokenizer.batch_decode(generation_output.sequences)[0]

# Piping the returned `past_key_values` to speed up the next conversation round
prompt = decoded_output + "\nQuestion: How can I modify the function above to return Mega bytes instead?\n\nAnswer: Here"
model_inputs = tokenizer(prompt, return_tensors='pt')
generation_output = model.generate(
  **model_inputs,
  past_key_values=generation_output.past_key_values,
  max_new_tokens=60,
  return_dict_in_generate=True
)
tokenizer.batch_decode(generation_output.sequences)[0][len(prompt):]
```

**Output**:
```
 is a modified version of the function that returns Mega bytes instead.

def bytes_to_megabytes(bytes):
   return bytes / 1024 / 1024

Answer: The function takes a number of bytes as input and returns the number of
```

Great, no additional time is spent recomputing the same key and values for the attention layer! There is however one catch. While the required peak memory for the \\( \mathbf{QK}^T \\) matrix is significantly reduced, holding the key-value cache in memory can become very memory expensive for long input sequences or multi-turn chat.


key: _node_content
string_value:
{"id_": "ac613e7e-f1c8-40e1-a601-600b2b493e5a", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "3d4a5be0-96a4-4cae-bb80-ec65cee94a22", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "bb1f2b699b61342ca13b75611df36eb9e3379ec4485edf0807dfbeb683246cf4", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "72e72914-2272-4d9f-8e9e-3d3417fa3d6c", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "af7fe762ab2d1d788a352dcae8d67faae696c12653c1c469d1646b379dbc93d3", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "a1885591-e8d5-4a91-964d-62ab4155ece6", "node_type": "1", "metadata": {}, "hash": "524d0e520cea28535feab9b2014e35857168fe5d735eca875ea09c947aa6f6bb", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 44121, "end_char_idx": 47413, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
would be the case when using an encoder-decoder architecture).

In `transformers`, a `generate` call will return `past_key_values` when `return_dict_in_generate=True` is passed, in addition to the default `use_cache=True`. Note that it is not yet available through the `pipeline` interface.

```python
# Generation as usual
prompt = system_prompt + "Question: Please write a function in Python that transforms bytes to Giga bytes.\n\nAnswer: Here"
model_inputs = tokenizer(prompt, return_tensors='pt')
generation_output = model.generate(**model_inputs, max_new_tokens=60, return_dict_in_generate=True)
decoded_output = tokenizer.batch_decode(generation_output.sequences)[0]

# Piping the returned `past_key_values` to speed up the next conversation round
prompt = decoded_output + "\nQuestion: How can I modify the function above to return Mega bytes instead?\n\nAnswer: Here"
model_inputs = tokenizer(prompt, return_tensors='pt')
generation_output = model.generate(
  **model_inputs,
  past_key_values=generation_output.past_key_values,
  max_new_tokens=60,
  return_dict_in_generate=True
)
tokenizer.batch_decode(generation_output.sequences)[0][len(prompt):]
```

**Output**:
```
 is a modified version of the function that returns Mega bytes instead.

def bytes_to_megabytes(bytes):
   return bytes / 1024 / 1024

Answer: The function takes a number of bytes as input and returns the number of
```

Great, no additional time is spent recomputing the same key and values for the attention layer! There is however one catch. While the required peak memory for the \\( \mathbf{QK}^T \\) matrix is significantly reduced, holding the key-value cache in memory can become very memory expensive for long input sequences or multi-turn chat. Remember that the key-value cache needs to store the key-value vectors for all previous input vectors \\( \mathbf{x}_i \text{, for } i \in \{1, \ldots, c - 1\} \\) for all self-attention layers and for all attention heads.

Let's compute the number of float values that need to be stored in the key-value cache for the LLM `bigcode/octocoder` that we used before.
The number of float values amounts to two times the sequence length times the number of attention heads times the attention head dimension and times the number of layers.
Computing this for our LLM at a hypothetical input sequence length of 16000 gives:

```python
config = model.config
2 * 16_000 * config.n_layer * config.n_head * config.n_embd // config.n_head
```

**Output**:
```
7864320000
```

Roughly 8 billion float values! Storing 8 billion float values in `float16` precision requires around 15 GB of RAM which is circa half as much as the model weights themselves!
Researchers have proposed two methods that allow to significantly reduce the memory cost of storing the key-value cache, which are explored in the next subsections.

#### 3.2.2 Multi-Query-Attention (MQA)

[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 shared across all attention heads without that the model's performance significantly degrades.


key: _node_content
string_value:
{"id_": "a1885591-e8d5-4a91-964d-62ab4155ece6", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "3d4a5be0-96a4-4cae-bb80-ec65cee94a22", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "bb1f2b699b61342ca13b75611df36eb9e3379ec4485edf0807dfbeb683246cf4", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "ac613e7e-f1c8-40e1-a601-600b2b493e5a", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "082abd1d6d8c9875ceaab67e38f08cc0924f043ff666c9ce3b7e1cc860d81116", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "34ba7d81-b813-49f3-9b34-8fac8267a8ab", "node_type": "1", "metadata": {}, "hash": "2f9aef044376b19a83561c3b824f0b12907f2a65f86634c6467705a331caf24c", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 45857, "end_char_idx": 49033, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Remember that the key-value cache needs to store the key-value vectors for all previous input vectors \\( \mathbf{x}_i \text{, for } i \in \{1, \ldots, c - 1\} \\) for all self-attention layers and for all attention heads.

Let's compute the number of float values that need to be stored in the key-value cache for the LLM `bigcode/octocoder` that we used before.
The number of float values amounts to two times the sequence length times the number of attention heads times the attention head dimension and times the number of layers.
Computing this for our LLM at a hypothetical input sequence length of 16000 gives:

```python
config = model.config
2 * 16_000 * config.n_layer * config.n_head * config.n_embd // config.n_head
```

**Output**:
```
7864320000
```

Roughly 8 billion float values! Storing 8 billion float values in `float16` precision requires around 15 GB of RAM which is circa half as much as the model weights themselves!
Researchers have proposed two methods that allow to significantly reduce the memory cost of storing the key-value cache, which are explored in the next subsections.

#### 3.2.2 Multi-Query-Attention (MQA)

[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 shared across all attention heads without that the model's performance significantly degrades.

> By using a single head-value projection weight pair, the key value vectors \\( \mathbf{k}_i, \mathbf{v}_i \\) have to be identical across all attention heads which in turn means that we only need to store 1 key-value projection pair in the cache instead of `n_head` ones.

As most LLMs use between 20 and 100 attention heads, MQA significantly reduces the memory consumption of the key-value cache. For the LLM used in this notebook we could therefore reduce the required memory consumption from 15 GB to less than 400 MB at an input sequence length of 16000.

In addition to memory savings, MQA also leads to improved computational efficiency as explained in the following.
In auto-regressive decoding, large key-value vectors need to be reloaded, concatenated with the current key-value vector pair to be then fed into the \\( \mathbf{q}_c\mathbf{K}^T \\) computation at every step. For auto-regressive decoding, the required memory bandwidth for the constant reloading can become a serious time bottleneck. By reducing the size of the key-value vectors less memory needs to be accessed, thus reducing the memory bandwidth bottleneck. For more detail, please have a look at [Noam's paper](https://arxiv.org/abs/1911.02150).

The important part to understand here is that reducing the number of key-value attention heads to 1 only makes sense if a key-value cache is used. The peak memory consumption of the model for a single forward pass without key-value cache stays unchanged as every attention head still has a unique query vector so that each attention head still has a different \\( \mathbf{QK}^T \\) matrix.


key: _node_content
string_value:
{"id_": "34ba7d81-b813-49f3-9b34-8fac8267a8ab", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "3d4a5be0-96a4-4cae-bb80-ec65cee94a22", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "bb1f2b699b61342ca13b75611df36eb9e3379ec4485edf0807dfbeb683246cf4", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "a1885591-e8d5-4a91-964d-62ab4155ece6", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "a7ba4463be8a9e8144506008bd4f51057f1c8c4ed497910b5898f6e965fbf885", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "4d04a4c8-5a86-4de3-b42d-a00ff764cc8a", "node_type": "1", "metadata": {}, "hash": "4d0c12a767cc74b6f797ad5b803029e6b60621621d01de4b0e5e8c187795d1d1", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 47415, "end_char_idx": 50613, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
> By using a single head-value projection weight pair, the key value vectors \\( \mathbf{k}_i, \mathbf{v}_i \\) have to be identical across all attention heads which in turn means that we only need to store 1 key-value projection pair in the cache instead of `n_head` ones.

As most LLMs use between 20 and 100 attention heads, MQA significantly reduces the memory consumption of the key-value cache. For the LLM used in this notebook we could therefore reduce the required memory consumption from 15 GB to less than 400 MB at an input sequence length of 16000.

In addition to memory savings, MQA also leads to improved computational efficiency as explained in the following.
In auto-regressive decoding, large key-value vectors need to be reloaded, concatenated with the current key-value vector pair to be then fed into the \\( \mathbf{q}_c\mathbf{K}^T \\) computation at every step. For auto-regressive decoding, the required memory bandwidth for the constant reloading can become a serious time bottleneck. By reducing the size of the key-value vectors less memory needs to be accessed, thus reducing the memory bandwidth bottleneck. For more detail, please have a look at [Noam's paper](https://arxiv.org/abs/1911.02150).

The important part to understand here is that reducing the number of key-value attention heads to 1 only makes sense if a key-value cache is used. The peak memory consumption of the model for a single forward pass without key-value cache stays unchanged as every attention head still has a unique query vector so that each attention head still has a different \\( \mathbf{QK}^T \\) matrix.

MQA has seen wide adoption by the community and is now used by many of the most popular LLMs:

-   [**Falcon**](https://huggingface.co/tiiuae/falcon-40b)
-   [**PaLM**](https://arxiv.org/abs/2204.02311)
-   [**MPT**](https://huggingface.co/mosaicml/mpt-30b)
-   [**BLOOM**](https://huggingface.co/bigscience/bloom)

Also, the checkpoint used in this notebook - `bigcode/octocoder` - makes use of MQA.

#### 3.2.3 Grouped-Query-Attention (GQA)

[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 of query head projection weights. Instead of using just a single key-value projection weight, `n < n_head` key-value projection weights should be used. By choosing `n` to a significantly smaller value than `n_head`, such as 2,4 or 8 almost all of the memory and speed gains from MQA can be kept while sacrificing less model capacity and thus arguably less performance.

Moreover, the authors of GQA found out that existing model checkpoints can be *uptrained* to have a GQA architecture with as little as 5% of the original pre-training compute. While 5% of the original pre-training compute can still be a massive amount, GQA *uptraining* allows existing checkpoints to be useful for longer input sequences.

GQA was only recently proposed which is why there is less adoption at the time of writing this notebook.


key: _node_content
string_value:
{"id_": "4d04a4c8-5a86-4de3-b42d-a00ff764cc8a", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "3d4a5be0-96a4-4cae-bb80-ec65cee94a22", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "bb1f2b699b61342ca13b75611df36eb9e3379ec4485edf0807dfbeb683246cf4", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "34ba7d81-b813-49f3-9b34-8fac8267a8ab", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/llm_tutorial_optimization", "title": "Optimizing LLMs for Speed and Memory", "tokens": 12767, "retrieve_doc": false, "source": "transformers"}, "hash": "047ee3ed3362d8f7782526a3533928ba32db8119546628ffc11db6adbcd4cb92", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 49035, "end_char_idx": 51979, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
MQA has seen wide adoption by the community and is now used by many of the most popular LLMs:

-   [**Falcon**](https://huggingface.co/tiiuae/falcon-40b)
-   [**PaLM**](https://arxiv.org/abs/2204.02311)
-   [**MPT**](https://huggingface.co/mosaicml/mpt-30b)
-   [**BLOOM**](https://huggingface.co/bigscience/bloom)

Also, the checkpoint used in this notebook - `bigcode/octocoder` - makes use of MQA.

#### 3.2.3 Grouped-Query-Attention (GQA)

[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 of query head projection weights. Instead of using just a single key-value projection weight, `n < n_head` key-value projection weights should be used. By choosing `n` to a significantly smaller value than `n_head`, such as 2,4 or 8 almost all of the memory and speed gains from MQA can be kept while sacrificing less model capacity and thus arguably less performance.

Moreover, the authors of GQA found out that existing model checkpoints can be *uptrained* to have a GQA architecture with as little as 5% of the original pre-training compute. While 5% of the original pre-training compute can still be a massive amount, GQA *uptraining* allows existing checkpoints to be useful for longer input sequences.

GQA was only recently proposed which is why there is less adoption at the time of writing this notebook.
The most notable application of GQA is [Llama-v2](https://huggingface.co/meta-llama/Llama-2-70b-hf).

> As a conclusion, it is strongly recommended to make use of either GQA or MQA if the LLM is deployed with auto-regressive decoding and is required to handle large input sequences as is the case for example for chat.


## Conclusion

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" are generated by the LLM itself. Going into more detail is out of the scope of this notebook, but can be read upon in this [nice blog post](https://huggingface.co/blog/assisted-generation).

The reason massive LLMs such as GPT3/4, Llama-2-70b, Claude, PaLM can run so quickly in chat-interfaces such as [Hugging Face Chat](https://huggingface.co/chat/) or ChatGPT is to a big part thanks to the above-mentioned improvements in precision, algorithms, and architecture.
Going forward, accelerators such as GPUs, TPUs, etc... will only get faster and allow for more memory, but one should nevertheless always make sure to use the best available algorithms and architectures to get the most bang for your buck 🤗


key: _node_content
string_value:
{"id_": "6e830ee2-45d7-4f42-a525-ae6d227a7a2c", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "title": "Pipelines for inference", "tokens": 4098, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "df04425c-3160-4924-84ae-3cad2eeea3a4", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "title": "Pipelines for inference", "tokens": 4098, "retrieve_doc": true, "source": "transformers"}, "hash": "ae7a9817190d68adf284158e10204a65f5200468b94ed3ad1fe61941b821c65d", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "adcf4d47-ab0f-4778-b748-0de94b9b1c0f", "node_type": "1", "metadata": {}, "hash": "1dd704adb7cbb386befb315b98420340a3f40715eaa79926dfda42f89f20dffc", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 3081, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# Pipelines for inference

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 for inference with the [`pipeline`]! This tutorial will teach you to:

* Use a [`pipeline`] for inference.
* Use a specific tokenizer or model.
* Use a [`pipeline`] for audio, vision, and multimodal tasks.

<Tip>

Take a look at the [`pipeline`] documentation for a complete list of supported tasks and available parameters.

</Tip>

## Pipeline usage

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`] for automatic speech recognition (ASR), or
speech-to-text.


1. Start by creating a [`pipeline`] and specify the inference task:

```py
>>> from transformers import pipeline

>>> transcriber = pipeline(task="automatic-speech-recognition")
```

2. Pass your input to the [`pipeline`]. In the case of speech recognition, this is an audio input file:

```py
>>> transcriber("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac")
{'text': 'I HAVE A DREAM BUT ONE DAY THIS NATION WILL RISE UP LIVE UP THE TRUE MEANING OF ITS TREES'}
```

Not the result you had in mind? Check out some of the [most downloaded automatic speech recognition models](https://huggingface.co/models?pipeline_tag=automatic-speech-recognition&sort=trending) 
on the Hub to see if you can get a better transcription.

Let's try the [Whisper large-v2](https://huggingface.co/openai/whisper-large-v2) model from OpenAI. Whisper was released 
2 years later than Wav2Vec2, and was trained on close to 10x more data. As such, it beats Wav2Vec2 on most downstream 
benchmarks. It also has the added benefit of predicting punctuation and casing, neither of which are possible with  
Wav2Vec2.

Let's give it a try here to see how it performs:

```py
>>> transcriber = pipeline(model="openai/whisper-large-v2")
>>> transcriber("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac")
{'text': ' I have a dream that one day this nation will rise up and live out the true meaning of its creed.'}
```

Now this result looks more accurate! For a deep-dive comparison on Wav2Vec2 vs Whisper, refer to the [Audio Transformers Course](https://huggingface.co/learn/audio-course/chapter5/asr_models).
We really encourage you to check out the Hub for models in different languages, models specialized in your field, and more.
You can check out and compare model results directly from your browser on the Hub to see if it fits or 
handles corner cases better than other ones.
And if you don't find a model for your use case, you can always start [training](training) your own!


key: _node_content
string_value:
{"id_": "adcf4d47-ab0f-4778-b748-0de94b9b1c0f", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "title": "Pipelines for inference", "tokens": 4098, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "df04425c-3160-4924-84ae-3cad2eeea3a4", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "title": "Pipelines for inference", "tokens": 4098, "retrieve_doc": true, "source": "transformers"}, "hash": "ae7a9817190d68adf284158e10204a65f5200468b94ed3ad1fe61941b821c65d", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "6e830ee2-45d7-4f42-a525-ae6d227a7a2c", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "title": "Pipelines for inference", "tokens": 4098, "retrieve_doc": true, "source": "transformers"}, "hash": "4ec6f3d7098825a81da7be16293d164eb2817b4eace54d47eed284f784f9603d", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "37d9ec9d-a8ab-46ff-89d2-bbd7a5887342", "node_type": "1", "metadata": {}, "hash": "35006ca7c198b75ee86aa5ac99db349e52adabda3fb962b33bd29f1e7792996d", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 1603, "end_char_idx": 4779, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Check out some of the [most downloaded automatic speech recognition models](https://huggingface.co/models?pipeline_tag=automatic-speech-recognition&sort=trending) 
on the Hub to see if you can get a better transcription.

Let's try the [Whisper large-v2](https://huggingface.co/openai/whisper-large-v2) model from OpenAI. Whisper was released 
2 years later than Wav2Vec2, and was trained on close to 10x more data. As such, it beats Wav2Vec2 on most downstream 
benchmarks. It also has the added benefit of predicting punctuation and casing, neither of which are possible with  
Wav2Vec2.

Let's give it a try here to see how it performs:

```py
>>> transcriber = pipeline(model="openai/whisper-large-v2")
>>> transcriber("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac")
{'text': ' I have a dream that one day this nation will rise up and live out the true meaning of its creed.'}
```

Now this result looks more accurate! For a deep-dive comparison on Wav2Vec2 vs Whisper, refer to the [Audio Transformers Course](https://huggingface.co/learn/audio-course/chapter5/asr_models).
We really encourage you to check out the Hub for models in different languages, models specialized in your field, and more.
You can check out and compare model results directly from your browser on the Hub to see if it fits or 
handles corner cases better than other ones.
And if you don't find a model for your use case, you can always start [training](training) your own!

If you have several inputs, you can pass your input as a list:

```py
transcriber(
    [
        "https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac",
        "https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/1.flac",
    ]
)
```

Pipelines are great for experimentation as switching from one model to another is trivial; however, there are some ways to optimize them for larger workloads than experimentation. See the following guides that dive into iterating over whole datasets or using pipelines in a webserver:
of the docs:
* [Using pipelines on a dataset](#using-pipelines-on-a-dataset)
* [Using pipelines for a webserver](./pipeline_webserver)

## Parameters

[`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(..., my_parameter=2)  # This will override and use `my_parameter=2`.
out = transcriber(...)  # This will go back to using `my_parameter=1`.
```

Let's check out 3 important ones:

### Device

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 can set `torch_dtype='float16'` to enable FP16 precision inference. Usually this would not cause significant performance drops but make sure you evaluate it on your models!


key: _node_content
string_value:
{"id_": "37d9ec9d-a8ab-46ff-89d2-bbd7a5887342", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "title": "Pipelines for inference", "tokens": 4098, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "df04425c-3160-4924-84ae-3cad2eeea3a4", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "title": "Pipelines for inference", "tokens": 4098, "retrieve_doc": true, "source": "transformers"}, "hash": "ae7a9817190d68adf284158e10204a65f5200468b94ed3ad1fe61941b821c65d", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "adcf4d47-ab0f-4778-b748-0de94b9b1c0f", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "title": "Pipelines for inference", "tokens": 4098, "retrieve_doc": true, "source": "transformers"}, "hash": "c73b8751cf83108b607ed8d46f6ca45323903abd11f23d46bc6f5d8e7901ece3", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "01b0d65a-34b8-4a64-8592-d984d346b49d", "node_type": "1", "metadata": {}, "hash": "f5a60559e3778ed0ebe7c7c7bc00cf888d81660b2dbc26f23d14217a76e8e30d", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 3527, "end_char_idx": 6805, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
See the following guides that dive into iterating over whole datasets or using pipelines in a webserver:
of the docs:
* [Using pipelines on a dataset](#using-pipelines-on-a-dataset)
* [Using pipelines for a webserver](./pipeline_webserver)

## Parameters

[`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(..., my_parameter=2)  # This will override and use `my_parameter=2`.
out = transcriber(...)  # This will go back to using `my_parameter=1`.
```

Let's check out 3 important ones:

### Device

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 can set `torch_dtype='float16'` to enable FP16 precision inference. Usually this would not cause significant performance drops but make sure you evaluate it on your models!

Alternatively, you can set `device_map="auto"` to automatically 
determine how to load and store the model weights. Using the `device_map` argument requires the 🤗 [Accelerate](https://huggingface.co/docs/accelerate)
package:

```bash
pip install --upgrade accelerate
```

The following code automatically loads and stores model weights across devices:

```py
transcriber = pipeline(model="openai/whisper-large-v2", device_map="auto")
```

Note that if  `device_map="auto"` is passed, there is no need to add the argument `device=device` when instantiating your `pipeline` as you may encounter some unexpected behavior!

### Batch size

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:

```py
transcriber = pipeline(model="openai/whisper-large-v2", device=0, batch_size=2)
audio_filenames = [f"https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/{i}.flac" for i in range(1, 5)]
texts = transcriber(audio_filenames)
```

This runs the pipeline on the 4 provided audio files, but it will pass them in batches of 2
to the model (which is on a GPU, where batching is more likely to help) without requiring any further code from you. 
The output should always match what you would have received without batching. It is only meant as a way to help you get more speed out of a pipeline.

Pipelines can also alleviate some of the complexities of batching because, for some pipelines, a single item (like a long audio file) needs to be chunked into multiple parts to be processed by a model. The pipeline performs this [*chunk batching*](./main_classes/pipelines#pipeline-chunk-batching) for you.

### Task specific parameters

All tasks provide task specific parameters which allow for additional flexibility and options to help you get your job done.


key: _node_content
string_value:
{"id_": "01b0d65a-34b8-4a64-8592-d984d346b49d", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "title": "Pipelines for inference", "tokens": 4098, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "df04425c-3160-4924-84ae-3cad2eeea3a4", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "title": "Pipelines for inference", "tokens": 4098, "retrieve_doc": true, "source": "transformers"}, "hash": "ae7a9817190d68adf284158e10204a65f5200468b94ed3ad1fe61941b821c65d", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "37d9ec9d-a8ab-46ff-89d2-bbd7a5887342", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "title": "Pipelines for inference", "tokens": 4098, "retrieve_doc": true, "source": "transformers"}, "hash": "e779da1fe50b0f6f63e23a78889fdf63e5f3863577cd23a64a96f4270d5ffd05", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "fb028a24-75d7-4389-9e29-b7d07e855cf9", "node_type": "1", "metadata": {}, "hash": "906238569b9c1ee944b4c069e3d73b3a9ef5c120b52bc819d609487d93d9aef4", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 5401, "end_char_idx": 6973, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
### Batch size

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:

```py
transcriber = pipeline(model="openai/whisper-large-v2", device=0, batch_size=2)
audio_filenames = [f"https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/{i}.flac" for i in range(1, 5)]
texts = transcriber(audio_filenames)
```

This runs the pipeline on the 4 provided audio files, but it will pass them in batches of 2
to the model (which is on a GPU, where batching is more likely to help) without requiring any further code from you. 
The output should always match what you would have received without batching. It is only meant as a way to help you get more speed out of a pipeline.

Pipelines can also alleviate some of the complexities of batching because, for some pipelines, a single item (like a long audio file) needs to be chunked into multiple parts to be processed by a model. The pipeline performs this [*chunk batching*](./main_classes/pipelines#pipeline-chunk-batching) for you.

### Task specific parameters

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:


key: _node_content
string_value:
{"id_": "fb028a24-75d7-4389-9e29-b7d07e855cf9", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "title": "Pipelines for inference", "tokens": 4098, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "df04425c-3160-4924-84ae-3cad2eeea3a4", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "title": "Pipelines for inference", "tokens": 4098, "retrieve_doc": true, "source": "transformers"}, "hash": "ae7a9817190d68adf284158e10204a65f5200468b94ed3ad1fe61941b821c65d", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "01b0d65a-34b8-4a64-8592-d984d346b49d", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "title": "Pipelines for inference", "tokens": 4098, "retrieve_doc": true, "source": "transformers"}, "hash": "b847fd1974b7b86f20b7e9957ba8c31a8125764f56381398b384b5b71c451696", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "f37fcd01-45fe-4f8e-9c9d-a9484a435c72", "node_type": "1", "metadata": {}, "hash": "53974a720c7e1847322692775b013696d472f1ba6408014dd1f948dc0f5fc0d3", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 5401, "end_char_idx": 9283, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
### Batch size

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:

```py
transcriber = pipeline(model="openai/whisper-large-v2", device=0, batch_size=2)
audio_filenames = [f"https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/{i}.flac" for i in range(1, 5)]
texts = transcriber(audio_filenames)
```

This runs the pipeline on the 4 provided audio files, but it will pass them in batches of 2
to the model (which is on a GPU, where batching is more likely to help) without requiring any further code from you. 
The output should always match what you would have received without batching. It is only meant as a way to help you get more speed out of a pipeline.

Pipelines can also alleviate some of the complexities of batching because, for some pipelines, a single item (like a long audio file) needs to be chunked into multiple parts to be processed by a model. The pipeline performs this [*chunk batching*](./main_classes/pipelines#pipeline-chunk-batching) for you.

### Task specific parameters

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 = pipeline(model="openai/whisper-large-v2", return_timestamps=True)
>>> transcriber("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/mlk.flac")
{'text': ' I have a dream that one day this nation will rise up and live out the true meaning of its creed.', 'chunks': [{'timestamp': (0.0, 11.88), 'text': ' I have a dream that one day this nation will rise up and live out the true meaning of its'}, {'timestamp': (11.88, 12.38), 'text': ' creed.'}]}
```

As you can see, the model inferred the text and also outputted **when** the various sentences were pronounced.

There are many parameters available for each task, so check out each task's API reference to see what you can tinker with!
For instance, the [`~transformers.AutomaticSpeechRecognitionPipeline`] has a `chunk_length_s` parameter which is helpful 
for working on really long audio files (for example, subtitling entire movies or hour-long videos) that a model typically 
cannot handle on its own:

```python
>>> transcriber = pipeline(model="openai/whisper-large-v2", chunk_length_s=30)
>>> transcriber("https://huggingface.co/datasets/reach-vb/random-audios/resolve/main/ted_60.wav")
{'text': " So in college, I was a government major, which means I had to write a lot of papers. Now, when a normal student writes a paper, they might spread the work out a little like this. So, you know. You get started maybe a little slowly, but you get enough done in the first week that with some heavier days later on, everything gets done and things stay civil. And I would want to do that like that. That would be the plan. I would have it all ready to go, but then actually the paper would come along, and then I would kind of do this. And that would happen every single paper. But then came my 90-page senior thesis, a paper you're supposed to spend a year on. I knew for a paper like that, my normal workflow was not an option, it was way too big a project. So I planned things out and I decided I kind of had to go something like this. This is how the year would go. So I'd start off light and I'd bump it up"}
```

If you can't find a parameter that would really help you out, feel free to [request it](https://github.com/huggingface/transformers/issues/new?assignees=&labels=feature&template=feature-request.yml)!


key: _node_content
string_value:
{"id_": "f37fcd01-45fe-4f8e-9c9d-a9484a435c72", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "title": "Pipelines for inference", "tokens": 4098, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "df04425c-3160-4924-84ae-3cad2eeea3a4", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "title": "Pipelines for inference", "tokens": 4098, "retrieve_doc": true, "source": "transformers"}, "hash": "ae7a9817190d68adf284158e10204a65f5200468b94ed3ad1fe61941b821c65d", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "fb028a24-75d7-4389-9e29-b7d07e855cf9", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "title": "Pipelines for inference", "tokens": 4098, "retrieve_doc": true, "source": "transformers"}, "hash": "489f43c116f47636b3619312b2958e4ce344e6625cc0af8db69e19eb7dfbc9d5", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "fb901ee4-d4bf-47c0-b242-7f9995c142f4", "node_type": "1", "metadata": {}, "hash": "7cea01c2cb59d29bbddfcdf52061bcc88fc4723b90da085025312abfda05619c", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 9286, "end_char_idx": 12398, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
## Using pipelines on a dataset

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 += len(out[0]["generated_text"])
```

The iterator `data()` yields each result, and the pipeline automatically
recognizes the input is iterable and will start fetching the data while
it continues to process it on the GPU (this uses [DataLoader](https://pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader) under the hood).
This is important because you don't have to allocate memory for the whole dataset
and you can feed the GPU as fast as possible.

Since batching could speed things up, it may be useful to try tuning the `batch_size` parameter here.

The simplest way to iterate over a dataset is to just load one from 🤗 [Datasets](https://github.com/huggingface/datasets/):

```py
# KeyDataset is a util that will just output the item we're interested in.
from transformers.pipelines.pt_utils import KeyDataset
from datasets import load_dataset

pipe = pipeline(model="hf-internal-testing/tiny-random-wav2vec2", device=0)
dataset = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation[:10]")

for out in pipe(KeyDataset(dataset, "audio")):
    print(out)
```


## Using pipelines for a webserver

<Tip>
Creating an inference engine is a complex topic which deserves it's own
page.
</Tip>

[Link](./pipeline_webserver)

## Vision pipeline

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?

![pipeline-cat-chonk](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg)

```py
>>> from transformers import pipeline

>>> vision_classifier = pipeline(model="google/vit-base-patch16-224")
>>> preds = vision_classifier(
...     images="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"
... )
>>> preds = [{"score": round(pred["score"], 4), "label": pred["label"]} for pred in preds]
>>> preds
[{'score': 0.4335, 'label': 'lynx, catamount'}, {'score': 0.0348, 'label': 'cougar, puma, catamount, mountain lion, painter, panther, Felis concolor'}, {'score': 0.0324, 'label': 'snow leopard, ounce, Panthera uncia'}, {'score': 0.0239, 'label': 'Egyptian cat'}, {'score': 0.0229, 'label': 'tiger cat'}]
```

## Text pipeline

Using a [`pipeline`] for NLP tasks is practically identical.

```py
>>> from transformers import pipeline

>>> # This model is a `zero-shot-classification` model.
>>> # It will classify text, except you are free to choose any label you might imagine
>>> classifier = pipeline(model="facebook/bart-large-mnli")
>>> classifier(
...     "I have a problem with my iphone that needs to be resolved asap!!


key: _node_content
string_value:
{"id_": "fb901ee4-d4bf-47c0-b242-7f9995c142f4", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "title": "Pipelines for inference", "tokens": 4098, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "df04425c-3160-4924-84ae-3cad2eeea3a4", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "title": "Pipelines for inference", "tokens": 4098, "retrieve_doc": true, "source": "transformers"}, "hash": "ae7a9817190d68adf284158e10204a65f5200468b94ed3ad1fe61941b821c65d", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "f37fcd01-45fe-4f8e-9c9d-a9484a435c72", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "title": "Pipelines for inference", "tokens": 4098, "retrieve_doc": true, "source": "transformers"}, "hash": "4e73b9cfcf105c7b96eb66f6d9a49e40ba1c96e9622538e90d32322556328b84", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "40959296-4a0b-4ce6-a994-af977a56d2a6", "node_type": "1", "metadata": {}, "hash": "8b5f8f5377006f5476f9ae07e945daedd608f1482e0a1386ebb00526aac605a6", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 10879, "end_char_idx": 13426, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
</Tip>

[Link](./pipeline_webserver)

## Vision pipeline

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?

![pipeline-cat-chonk](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg)

```py
>>> from transformers import pipeline

>>> vision_classifier = pipeline(model="google/vit-base-patch16-224")
>>> preds = vision_classifier(
...     images="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"
... )
>>> preds = [{"score": round(pred["score"], 4), "label": pred["label"]} for pred in preds]
>>> preds
[{'score': 0.4335, 'label': 'lynx, catamount'}, {'score': 0.0348, 'label': 'cougar, puma, catamount, mountain lion, painter, panther, Felis concolor'}, {'score': 0.0324, 'label': 'snow leopard, ounce, Panthera uncia'}, {'score': 0.0239, 'label': 'Egyptian cat'}, {'score': 0.0229, 'label': 'tiger cat'}]
```

## Text pipeline

Using a [`pipeline`] for NLP tasks is practically identical.

```py
>>> from transformers import pipeline

>>> # This model is a `zero-shot-classification` model.
>>> # It will classify text, except you are free to choose any label you might imagine
>>> classifier = pipeline(model="facebook/bart-large-mnli")
>>> classifier(
...     "I have a problem with my iphone that needs to be resolved asap!!",
...     candidate_labels=["urgent", "not urgent", "phone", "tablet", "computer"],
... )
{'sequence': 'I have a problem with my iphone that needs to be resolved asap!!', 'labels': ['urgent', 'phone', 'computer', 'not urgent', 'tablet'], 'scores': [0.504, 0.479, 0.013, 0.003, 0.002]}
```

## Multimodal pipeline

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](https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png):

```py
>>> from transformers import pipeline

>>> vqa = pipeline(model="impira/layoutlm-document-qa")
>>> output = vqa(
...     image="https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png",
...     question="What is the invoice number?


key: _node_content
string_value:
{"id_": "40959296-4a0b-4ce6-a994-af977a56d2a6", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "title": "Pipelines for inference", "tokens": 4098, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "df04425c-3160-4924-84ae-3cad2eeea3a4", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "title": "Pipelines for inference", "tokens": 4098, "retrieve_doc": true, "source": "transformers"}, "hash": "ae7a9817190d68adf284158e10204a65f5200468b94ed3ad1fe61941b821c65d", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "fb901ee4-d4bf-47c0-b242-7f9995c142f4", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "title": "Pipelines for inference", "tokens": 4098, "retrieve_doc": true, "source": "transformers"}, "hash": "5f8e122a41e5994baee64ff7cd134ff134ccd8a08156b1625d28ebaf46c71008", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "2b5b4165-e434-4cf7-a535-b1428fea3121", "node_type": "1", "metadata": {}, "hash": "8a5e444a0d80a927a08f127c9e5887e33bb56c2284b9d07af673c14ca0ee40d2", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 12061, "end_char_idx": 14835, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```py
>>> from transformers import pipeline

>>> # This model is a `zero-shot-classification` model.
>>> # It will classify text, except you are free to choose any label you might imagine
>>> classifier = pipeline(model="facebook/bart-large-mnli")
>>> classifier(
...     "I have a problem with my iphone that needs to be resolved asap!!",
...     candidate_labels=["urgent", "not urgent", "phone", "tablet", "computer"],
... )
{'sequence': 'I have a problem with my iphone that needs to be resolved asap!!', 'labels': ['urgent', 'phone', 'computer', 'not urgent', 'tablet'], 'scores': [0.504, 0.479, 0.013, 0.003, 0.002]}
```

## Multimodal pipeline

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](https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png):

```py
>>> from transformers import pipeline

>>> vqa = pipeline(model="impira/layoutlm-document-qa")
>>> output = vqa(
...     image="https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png",
...     question="What is the invoice number?",
... )
>>> output[0]["score"] = round(output[0]["score"], 3)
>>> output
[{'score': 0.425, 'answer': 'us-001', 'start': 16, 'end': 16}]
```

<Tip>

To run the example above you need to have [`pytesseract`](https://pypi.org/project/pytesseract/) installed in addition to 🤗 Transformers:

```bash
sudo apt install -y tesseract-ocr
pip install pytesseract
```

</Tip>

## Using `pipeline` on large models with 🤗 `accelerate`:

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 pipeline

pipe = pipeline(model="facebook/opt-1.3b", torch_dtype=torch.bfloat16, device_map="auto")
output = pipe("This is a cool example!", do_sample=True, top_p=0.95)
```

You can also pass 8-bit loaded models if you install `bitsandbytes` and add the argument `load_in_8bit=True`

```py
# pip install accelerate bitsandbytes
import torch
from transformers import pipeline

pipe = pipeline(model="facebook/opt-1.3b", device_map="auto", model_kwargs={"load_in_8bit": True})
output = pipe("This is a cool example!", do_sample=True, top_p=0.95)
```

Note that you can replace the checkpoint with any Hugging Face model that supports large model loading, such as BLOOM.


key: _node_content
string_value:
{"id_": "2b5b4165-e434-4cf7-a535-b1428fea3121", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "title": "Pipelines for inference", "tokens": 4098, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "df04425c-3160-4924-84ae-3cad2eeea3a4", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "title": "Pipelines for inference", "tokens": 4098, "retrieve_doc": true, "source": "transformers"}, "hash": "ae7a9817190d68adf284158e10204a65f5200468b94ed3ad1fe61941b821c65d", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "40959296-4a0b-4ce6-a994-af977a56d2a6", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/pipeline_tutorial", "title": "Pipelines for inference", "tokens": 4098, "retrieve_doc": true, "source": "transformers"}, "hash": "a7d798c9ad0a2d66a34a485cd92855e860df282a1057440de9b9c60447215c2d", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 13426, "end_char_idx": 16068, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
",
... )
>>> output[0]["score"] = round(output[0]["score"], 3)
>>> output
[{'score': 0.425, 'answer': 'us-001', 'start': 16, 'end': 16}]
```

<Tip>

To run the example above you need to have [`pytesseract`](https://pypi.org/project/pytesseract/) installed in addition to 🤗 Transformers:

```bash
sudo apt install -y tesseract-ocr
pip install pytesseract
```

</Tip>

## Using `pipeline` on large models with 🤗 `accelerate`:

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 pipeline

pipe = pipeline(model="facebook/opt-1.3b", torch_dtype=torch.bfloat16, device_map="auto")
output = pipe("This is a cool example!", do_sample=True, top_p=0.95)
```

You can also pass 8-bit loaded models if you install `bitsandbytes` and add the argument `load_in_8bit=True`

```py
# pip install accelerate bitsandbytes
import torch
from transformers import pipeline

pipe = pipeline(model="facebook/opt-1.3b", device_map="auto", model_kwargs={"load_in_8bit": True})
output = pipe("This is a cool example!", do_sample=True, top_p=0.95)
```

Note that you can replace the checkpoint with any Hugging Face model that supports large model loading, such as BLOOM.

## Creating web demos from pipelines with `gradio`

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 classification pipeline (or any other pipeline) in a single line of code by calling Gradio's [`Interface.from_pipeline`](https://www.gradio.app/docs/interface#interface-from-pipeline) function to launch the pipeline. This creates an intuitive drag-and-drop interface in your browser:

```py
from transformers import pipeline
import gradio as gr

pipe = pipeline("image-classification", model="google/vit-base-patch16-224")

gr.Interface.from_pipeline(pipe).launch()
```


![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/panda-classification.png)

By default, the web demo runs on a local server. If you'd like to share it with others, you can generate a temporary public
link by setting `share=True` in `launch()`. You can also host your demo on [Hugging Face Spaces](https://huggingface.co/spaces) for a permanent link.


key: _node_content
string_value:
{"id_": "6e8eb2a1-22b3-455a-9b16-e62bd19f8c25", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/fsdp", "title": "Fully Sharded Data Parallel", "tokens": 1846, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "d6254beb-d9ba-4eae-bcf3-cf88000fa790", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/fsdp", "title": "Fully Sharded Data Parallel", "tokens": 1846, "retrieve_doc": true, "source": "transformers"}, "hash": "cb2207a9ae7a79718ccb6b00018b0acb9220d93bf7ed5ab0e1aa3e37b3035d8c", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "50eb465f-3887-4e3e-b2b4-5427992a29c3", "node_type": "1", "metadata": {}, "hash": "b94c674cd476a3b4515be786a34ddac8e3d7086a8eb69d870d387871ae81e59d", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 3391, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# Fully Sharded Data Parallel

[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://pytorch.org/docs/stable/generated/torch.nn.parallel.DistributedDataParallel.html), FSDP reduces memory-usage because a model is replicated on each GPU. This improves GPU memory-efficiency and allows you to train much larger models on fewer GPUs. FSDP is integrated with the Accelerate, a library for easily managing training in distributed environments, which means it is available for use from the [`Trainer`] class.

Before you start, make sure Accelerate is installed and at least PyTorch 2.1.0 or newer.

```bash
pip install accelerate
```

## FSDP configuration

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 options in `accelerate config`.

```bash
accelerate config
```

When you run `accelerate config`, you'll be prompted with a series of options to configure your training environment. This section covers some of the most important FSDP options. To learn more about the other available FSDP options, take a look at the [fsdp_config](https://huggingface.co/docs/transformers/main_classes/trainer#transformers.TrainingArguments.fsdp_config) parameters.

### Sharding strategy

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 is equivalent to DDP); select `3` for this option
* `HYBRID_SHARD` - shard model parameters, gradients and optimizer states within each worker where each worker also has a full copy; select `4` for this option
* `HYBRID_SHARD_ZERO2` - shard gradients and optimizer states within each worker where each worker also has a full copy; select `5` for this option

This is enabled by the `fsdp_sharding_strategy` flag.

### CPU offload

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`.

### Wrapping policy

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 select `fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP` to wrap a Transformer layer and `fsdp_transformer_layer_cls_to_wrap` to specify which layer to wrap (for example `BertLayer`).

Otherwise, you can choose a size-based wrapping policy where FSDP is applied to a layer if it exceeds a certain number of parameters.


key: _node_content
string_value:
{"id_": "50eb465f-3887-4e3e-b2b4-5427992a29c3", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/fsdp", "title": "Fully Sharded Data Parallel", "tokens": 1846, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "d6254beb-d9ba-4eae-bcf3-cf88000fa790", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/fsdp", "title": "Fully Sharded Data Parallel", "tokens": 1846, "retrieve_doc": true, "source": "transformers"}, "hash": "cb2207a9ae7a79718ccb6b00018b0acb9220d93bf7ed5ab0e1aa3e37b3035d8c", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "6e8eb2a1-22b3-455a-9b16-e62bd19f8c25", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/fsdp", "title": "Fully Sharded Data Parallel", "tokens": 1846, "retrieve_doc": true, "source": "transformers"}, "hash": "5358aa4846b4e4f0f88e61228f619d9194e5e6079802685015e8613be6da0a1a", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "34f2f2e5-8d60-44d2-97b6-4e44a489e4b0", "node_type": "1", "metadata": {}, "hash": "995373af9bd5278874c2cbff77d98dbef8eac496d636076b8e576e48d19c86f6", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 1689, "end_char_idx": 4594, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
### Sharding strategy

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 is equivalent to DDP); select `3` for this option
* `HYBRID_SHARD` - shard model parameters, gradients and optimizer states within each worker where each worker also has a full copy; select `4` for this option
* `HYBRID_SHARD_ZERO2` - shard gradients and optimizer states within each worker where each worker also has a full copy; select `5` for this option

This is enabled by the `fsdp_sharding_strategy` flag.

### CPU offload

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`.

### Wrapping policy

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 select `fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP` to wrap a Transformer layer and `fsdp_transformer_layer_cls_to_wrap` to specify which layer to wrap (for example `BertLayer`).

Otherwise, you can choose a size-based wrapping policy where FSDP is applied to a layer if it exceeds a certain number of parameters. This is enabled by setting `fsdp_wrap_policy: SIZE_BASED_WRAP` and `min_num_param` to the desired size threshold.

### Checkpointing

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 with the [`~accelerate.Accelerator.load_state`]` method.

```py
# directory containing checkpoints
accelerator.load_state("ckpt")
```

However, when training ends, you want to save the full state dict because sharded state dict is only compatible with FSDP.

```py
if trainer.is_fsdp_enabled:
    trainer.accelerator.state.fsdp_plugin.set_state_dict_type("FULL_STATE_DICT")

trainer.save_model(script_args.output_dir)
```

### TPU

[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.


key: _node_content
string_value:
{"id_": "34f2f2e5-8d60-44d2-97b6-4e44a489e4b0", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/fsdp", "title": "Fully Sharded Data Parallel", "tokens": 1846, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "d6254beb-d9ba-4eae-bcf3-cf88000fa790", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/fsdp", "title": "Fully Sharded Data Parallel", "tokens": 1846, "retrieve_doc": true, "source": "transformers"}, "hash": "cb2207a9ae7a79718ccb6b00018b0acb9220d93bf7ed5ab0e1aa3e37b3035d8c", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "50eb465f-3887-4e3e-b2b4-5427992a29c3", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/fsdp", "title": "Fully Sharded Data Parallel", "tokens": 1846, "retrieve_doc": true, "source": "transformers"}, "hash": "f9c8bbf0169d5cc7e26d0d9378e0ebbf493768ea27f094ae17b33802b3ab0200", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "8623e95f-2902-4b67-8643-1ce99bb98438", "node_type": "1", "metadata": {}, "hash": "68326477b8403a364c97ff227645ebda0035518ed2e529d191a0c2506fe097c7", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 2960, "end_char_idx": 6014, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
The *auto wrapping* policy is the simplest way to implement this and you don't need to change any code. You should select `fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP` to wrap a Transformer layer and `fsdp_transformer_layer_cls_to_wrap` to specify which layer to wrap (for example `BertLayer`).

Otherwise, you can choose a size-based wrapping policy where FSDP is applied to a layer if it exceeds a certain number of parameters. This is enabled by setting `fsdp_wrap_policy: SIZE_BASED_WRAP` and `min_num_param` to the desired size threshold.

### Checkpointing

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 with the [`~accelerate.Accelerator.load_state`]` method.

```py
# directory containing checkpoints
accelerator.load_state("ckpt")
```

However, when training ends, you want to save the full state dict because sharded state dict is only compatible with FSDP.

```py
if trainer.is_fsdp_enabled:
    trainer.accelerator.state.fsdp_plugin.set_state_dict_type("FULL_STATE_DICT")

trainer.save_model(script_args.output_dir)
```

### TPU

[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.

```yaml
xla: True # must be set to True to enable PyTorch/XLA
xla_fsdp_settings: # XLA-specific FSDP parameters
xla_fsdp_grad_ckpt: True # use gradient checkpointing
```

The [`xla_fsdp_settings`](https://github.com/pytorch/xla/blob/2e6e183e0724818f137c8135b34ef273dea33318/torch_xla/distributed/fsdp/xla_fully_sharded_data_parallel.py#L128) allow you to configure additional XLA-specific parameters for FSDP.

## Launch training

An example FSDP configuration file may look like:

```yaml
compute_environment: LOCAL_MACHINE
debug: false
distributed_type: FSDP
downcast_bf16: 'no'
fsdp_config:
  fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP
  fsdp_backward_prefetch_policy: BACKWARD_PRE
  fsdp_cpu_ram_efficient_loading: true
  fsdp_forward_prefetch: false
  fsdp_offload_params: true
  fsdp_sharding_strategy: 1
  fsdp_state_dict_type: SHARDED_STATE_DICT
  fsdp_sync_module_states: true
  fsdp_transformer_layer_cls_to_wrap: BertLayer
  fsdp_use_orig_params: true
machine_rank: 0
main_training_function: main
mixed_precision: bf16
num_machines: 1
num_processes: 2
rdzv_backend: static
same_network: true
tpu_env: []
tpu_use_cluster: false
tpu_use_sudo: false
use_cpu: false
```

To launch training, run the [`accelerate launch`](https://huggingface.co/docs/accelerate/package_reference/cli#accelerate-launch) command and it'll automatically use the configuration file you previously created with `accelerate config`.


key: _node_content
string_value:
{"id_": "8623e95f-2902-4b67-8643-1ce99bb98438", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/fsdp", "title": "Fully Sharded Data Parallel", "tokens": 1846, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "d6254beb-d9ba-4eae-bcf3-cf88000fa790", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/fsdp", "title": "Fully Sharded Data Parallel", "tokens": 1846, "retrieve_doc": true, "source": "transformers"}, "hash": "cb2207a9ae7a79718ccb6b00018b0acb9220d93bf7ed5ab0e1aa3e37b3035d8c", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "34f2f2e5-8d60-44d2-97b6-4e44a489e4b0", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/fsdp", "title": "Fully Sharded Data Parallel", "tokens": 1846, "retrieve_doc": true, "source": "transformers"}, "hash": "7e9bf19819b85d80811b833a295f4992d78fa07b70d92c374253c1bc0aa23f70", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 5007, "end_char_idx": 6981, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
## Launch training

An example FSDP configuration file may look like:

```yaml
compute_environment: LOCAL_MACHINE
debug: false
distributed_type: FSDP
downcast_bf16: 'no'
fsdp_config:
  fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP
  fsdp_backward_prefetch_policy: BACKWARD_PRE
  fsdp_cpu_ram_efficient_loading: true
  fsdp_forward_prefetch: false
  fsdp_offload_params: true
  fsdp_sharding_strategy: 1
  fsdp_state_dict_type: SHARDED_STATE_DICT
  fsdp_sync_module_states: true
  fsdp_transformer_layer_cls_to_wrap: BertLayer
  fsdp_use_orig_params: true
machine_rank: 0
main_training_function: main
mixed_precision: bf16
num_machines: 1
num_processes: 2
rdzv_backend: static
same_network: true
tpu_env: []
tpu_use_cluster: false
tpu_use_sudo: false
use_cpu: false
```

To launch training, run the [`accelerate launch`](https://huggingface.co/docs/accelerate/package_reference/cli#accelerate-launch) command and it'll automatically use the configuration file you previously created with `accelerate config`.

```bash
accelerate launch my-trainer-script.py
```

```bash
accelerate launch --fsdp="full shard" --fsdp_config="path/to/fsdp_config/ my-trainer-script.py
```

## Next steps

FSDP can be a powerful tool for training really large models and you have access to more than one GPU or TPU. By sharding the model parameters, optimizer and gradient states, and even offloading them to the CPU when they're inactive, FSDP can reduce the high cost of large-scale training. If you're interested in learning more, the following may be helpful:

* Follow along with the more in-depth Accelerate guide for [FSDP](https://huggingface.co/docs/accelerate/usage_guides/fsdp).
* Read the [Introducing PyTorch Fully Sharded Data Parallel (FSDP) API](https://pytorch.org/blog/introducing-pytorch-fully-sharded-data-parallel-api/) blog post.
* Read the [Scaling PyTorch models on Cloud TPUs with FSDP](https://pytorch.org/blog/scaling-pytorch-models-on-cloud-tpus-with-fsdp/) blog post.


key: _node_content
string_value:
{"id_": "6d25324e-8dc1-48c0-a553-73b2a65f6dc0", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/model_summary", "title": "The Transformer model family", "tokens": 4019, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "fd6ed4d3-f1ca-498d-9c74-7a5d84385e19", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/model_summary", "title": "The Transformer model family", "tokens": 4019, "retrieve_doc": true, "source": "transformers"}, "hash": "8cead54d1f52c4d818c9192529c1a4c2c648d344c5ad270063818d92463dd149", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "212cc8f8-8054-486a-a6fe-7465fe4fc367", "node_type": "1", "metadata": {}, "hash": "510d17991dbb4867cfe0febee037598b0c6759fe2ee5bbfef62f54d206f7d9f2", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 3129, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# The Transformer model family

Since its introduction in 2017, the [original Transformer](https://arxiv.org/abs/1706.03762) model (see the [Annotated Transformer](http://nlp.seas.harvard.edu/2018/04/03/attention.html) blog post for a gentle technical introduction) has inspired many new and exciting models that extend beyond natural language processing (NLP) tasks. There are models for [predicting the folded structure of proteins](https://huggingface.co/blog/deep-learning-with-proteins), [training a cheetah to run](https://huggingface.co/blog/train-decision-transformers), and [time series forecasting](https://huggingface.co/blog/time-series-transformers). With so many Transformer variants available, it can be easy to miss the bigger picture. What all these models have in common is they're based on the original Transformer architecture. Some models only use the encoder or decoder, while others use both. This provides a useful taxonomy to categorize and examine the high-level differences within models in the Transformer family, and it'll help you understand Transformers you haven't encountered before.

If you aren't familiar with the original Transformer model or need a refresher, check out the [How do Transformers work](https://huggingface.co/course/chapter1/4?fw=pt) chapter from the Hugging Face course.

<div align="center">
    <iframe width="560" height="315" src="https://www.youtube.com/embed/H39Z_720T5s" title="YouTube video player"
    frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope;
    picture-in-picture" allowfullscreen></iframe>
</div>

## Computer vision

<iframe style="border: 1px solid rgba(0, 0, 0, 0.1);" width="1000" height="450" src="https://www.figma.com/embed?embed_host=share&url=https%3A%2F%2Fwww.figma.com%2Ffile%2FacQBpeFBVvrDUlzFlkejoz%2FModelscape-timeline%3Fnode-id%3D0%253A1%26t%3Dm0zJ7m2BQ9oe0WtO-1" allowfullscreen></iframe> 

### Convolutional network

For a long time, convolutional networks (CNNs) were the dominant paradigm for computer vision tasks until the [Vision Transformer](https://arxiv.org/abs/2010.11929) demonstrated its scalability and efficiency. Even then, some of a CNN's best qualities, like translation invariance, are so powerful (especially for certain tasks) that some Transformers incorporate convolutions in their architecture. [ConvNeXt](model_doc/convnext) flipped this exchange around and incorporated design choices from Transformers to modernize a CNN. For example, ConvNeXt uses non-overlapping sliding windows to patchify an image and a larger kernel to increase its global receptive field. ConvNeXt also makes several layer design choices to be more memory-efficient and improve performance, so it competes favorably with Transformers!

### Encoder[[cv-encoder]]

The [Vision Transformer (ViT)](model_doc/vit) opened the door to computer vision tasks without convolutions. ViT uses a standard Transformer encoder, but its main breakthrough was how it treated an image. It splits an image into fixed-size patches and uses them to create an embedding, just like how a sentence is split into tokens.


key: _node_content
string_value:
{"id_": "212cc8f8-8054-486a-a6fe-7465fe4fc367", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/model_summary", "title": "The Transformer model family", "tokens": 4019, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "fd6ed4d3-f1ca-498d-9c74-7a5d84385e19", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/model_summary", "title": "The Transformer model family", "tokens": 4019, "retrieve_doc": true, "source": "transformers"}, "hash": "8cead54d1f52c4d818c9192529c1a4c2c648d344c5ad270063818d92463dd149", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "6d25324e-8dc1-48c0-a553-73b2a65f6dc0", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/model_summary", "title": "The Transformer model family", "tokens": 4019, "retrieve_doc": true, "source": "transformers"}, "hash": "0e5d6f759cdb5d41cda3b0f2cf9742049a1c02704908bb7610bfb75a42c6d29c", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "81c63364-e285-4150-80bc-8e628f013687", "node_type": "1", "metadata": {}, "hash": "f9123e30781ced80dc6cd7e0a629ed3208b2e25e111da26e24d04c0c51a76d8e", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 2163, "end_char_idx": 5725, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Even then, some of a CNN's best qualities, like translation invariance, are so powerful (especially for certain tasks) that some Transformers incorporate convolutions in their architecture. [ConvNeXt](model_doc/convnext) flipped this exchange around and incorporated design choices from Transformers to modernize a CNN. For example, ConvNeXt uses non-overlapping sliding windows to patchify an image and a larger kernel to increase its global receptive field. ConvNeXt also makes several layer design choices to be more memory-efficient and improve performance, so it competes favorably with Transformers!

### Encoder[[cv-encoder]]

The [Vision Transformer (ViT)](model_doc/vit) opened the door to computer vision tasks without convolutions. ViT uses a standard Transformer encoder, but its main breakthrough was how it treated an image. It splits an image into fixed-size patches and uses them to create an embedding, just like how a sentence is split into tokens. ViT capitalized on the Transformers' efficient architecture to demonstrate competitive results with the CNNs at the time while requiring fewer resources to train. ViT was soon followed by other vision models that could also handle dense vision tasks like segmentation as well as detection.

One of these models is the [Swin](model_doc/swin) Transformer. It builds hierarchical feature maps (like a CNN 👀 and unlike ViT) from smaller-sized patches and merges them with neighboring patches in deeper layers. Attention is only computed within a local window, and the window is shifted between attention layers to create connections to help the model learn better. Since the Swin Transformer can produce hierarchical feature maps, it is a good candidate for dense prediction tasks like segmentation and detection. The [SegFormer](model_doc/segformer) also uses a Transformer encoder to build hierarchical feature maps, but it adds a simple multilayer perceptron (MLP) decoder on top to combine all the feature maps and make a prediction.

Other vision models, like BeIT and ViTMAE, drew inspiration from BERT's pretraining objective. [BeIT](model_doc/beit) is pretrained by *masked image modeling (MIM)*; the image patches are randomly masked, and the image is also tokenized into visual tokens. BeIT is trained to predict the visual tokens corresponding to the masked patches. [ViTMAE](model_doc/vitmae) has a similar pretraining objective, except it must predict the pixels instead of visual tokens. What's unusual is 75% of the image patches are masked! The decoder reconstructs the pixels from the masked tokens and encoded patches. After pretraining, the decoder is thrown away, and the encoder is ready to be used in downstream tasks.

### Decoder[[cv-decoder]]

Decoder-only vision models are rare because most vision models rely on an encoder to learn an image representation. But for use cases like image generation, the decoder is a natural fit, as we've seen from text generation models like GPT-2. [ImageGPT](model_doc/imagegpt) uses the same architecture as GPT-2, but instead of predicting the next token in a sequence, it predicts the next pixel in an image. In addition to image generation, ImageGPT could also be finetuned for image classification.

### Encoder-decoder[[cv-encoder-decoder]]

Vision models commonly use an encoder (also known as a backbone) to extract important image features before passing them to a Transformer decoder. [DETR](model_doc/detr) has a pretrained backbone, but it also uses the complete Transformer encoder-decoder architecture for object detection.


key: _node_content
string_value:
{"id_": "81c63364-e285-4150-80bc-8e628f013687", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/model_summary", "title": "The Transformer model family", "tokens": 4019, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "fd6ed4d3-f1ca-498d-9c74-7a5d84385e19", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/model_summary", "title": "The Transformer model family", "tokens": 4019, "retrieve_doc": true, "source": "transformers"}, "hash": "8cead54d1f52c4d818c9192529c1a4c2c648d344c5ad270063818d92463dd149", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "212cc8f8-8054-486a-a6fe-7465fe4fc367", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/model_summary", "title": "The Transformer model family", "tokens": 4019, "retrieve_doc": true, "source": "transformers"}, "hash": "b8dee52ed3e3ec41bf06b70405e356a2078f575120edf086cced6e79aa508a02", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "274244d5-1b30-4700-b341-92e1259f1a0a", "node_type": "1", "metadata": {}, "hash": "8512f7945e4e45e353158f4d39346f978e6ee029df678571246aac19e2f64bf4", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 4165, "end_char_idx": 7305, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Other vision models, like BeIT and ViTMAE, drew inspiration from BERT's pretraining objective. [BeIT](model_doc/beit) is pretrained by *masked image modeling (MIM)*; the image patches are randomly masked, and the image is also tokenized into visual tokens. BeIT is trained to predict the visual tokens corresponding to the masked patches. [ViTMAE](model_doc/vitmae) has a similar pretraining objective, except it must predict the pixels instead of visual tokens. What's unusual is 75% of the image patches are masked! The decoder reconstructs the pixels from the masked tokens and encoded patches. After pretraining, the decoder is thrown away, and the encoder is ready to be used in downstream tasks.

### Decoder[[cv-decoder]]

Decoder-only vision models are rare because most vision models rely on an encoder to learn an image representation. But for use cases like image generation, the decoder is a natural fit, as we've seen from text generation models like GPT-2. [ImageGPT](model_doc/imagegpt) uses the same architecture as GPT-2, but instead of predicting the next token in a sequence, it predicts the next pixel in an image. In addition to image generation, ImageGPT could also be finetuned for image classification.

### Encoder-decoder[[cv-encoder-decoder]]

Vision models commonly use an encoder (also known as a backbone) to extract important image features before passing them to a Transformer decoder. [DETR](model_doc/detr) has a pretrained backbone, but it also uses the complete Transformer encoder-decoder architecture for object detection. The encoder learns image representations and combines them with object queries (each object query is a learned embedding that focuses on a region or object in an image) in the decoder. DETR predicts the bounding box coordinates and class label for each object query.

## Natural language processing

<iframe style="border: 1px solid rgba(0, 0, 0, 0.1);" width="1000" height="450" src="https://www.figma.com/embed?embed_host=share&url=https%3A%2F%2Fwww.figma.com%2Ffile%2FUhbQAZDlpYW5XEpdFy6GoG%2Fnlp-model-timeline%3Fnode-id%3D0%253A1%26t%3D4mZMr4r1vDEYGJ50-1" allowfullscreen></iframe>

### Encoder[[nlp-encoder]]

[BERT](model_doc/bert) is an encoder-only Transformer that randomly masks certain tokens in the input to avoid seeing other tokens, which would allow it to "cheat". The pretraining objective is to predict the masked token based on the context. This allows BERT to fully use the left and right contexts to help it learn a deeper and richer representation of the inputs. However, there was still room for improvement in BERT's pretraining strategy. [RoBERTa](model_doc/roberta) improved upon this by introducing a new pretraining recipe that includes training for longer and on larger batches, randomly masking tokens at each epoch instead of just once during preprocessing, and removing the next-sentence prediction objective. 

The dominant strategy to improve performance is to increase the model size. But training large models is computationally expensive. One way to reduce computational costs is using a smaller model like [DistilBERT](model_doc/distilbert).


key: _node_content
string_value:
{"id_": "274244d5-1b30-4700-b341-92e1259f1a0a", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/model_summary", "title": "The Transformer model family", "tokens": 4019, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "fd6ed4d3-f1ca-498d-9c74-7a5d84385e19", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/model_summary", "title": "The Transformer model family", "tokens": 4019, "retrieve_doc": true, "source": "transformers"}, "hash": "8cead54d1f52c4d818c9192529c1a4c2c648d344c5ad270063818d92463dd149", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "81c63364-e285-4150-80bc-8e628f013687", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/model_summary", "title": "The Transformer model family", "tokens": 4019, "retrieve_doc": true, "source": "transformers"}, "hash": "ab735995d323c697e5672fb632249e1c5223f364933c32628fd2f291ccc27802", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "262865c1-c6bb-4168-b7f5-bbc7d422e62c", "node_type": "1", "metadata": {}, "hash": "0cf213ec57003fb8c06fbbaffd4409237761532a45b660940005affc1a7a6a23", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 5726, "end_char_idx": 9017, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
The encoder learns image representations and combines them with object queries (each object query is a learned embedding that focuses on a region or object in an image) in the decoder. DETR predicts the bounding box coordinates and class label for each object query.

## Natural language processing

<iframe style="border: 1px solid rgba(0, 0, 0, 0.1);" width="1000" height="450" src="https://www.figma.com/embed?embed_host=share&url=https%3A%2F%2Fwww.figma.com%2Ffile%2FUhbQAZDlpYW5XEpdFy6GoG%2Fnlp-model-timeline%3Fnode-id%3D0%253A1%26t%3D4mZMr4r1vDEYGJ50-1" allowfullscreen></iframe>

### Encoder[[nlp-encoder]]

[BERT](model_doc/bert) is an encoder-only Transformer that randomly masks certain tokens in the input to avoid seeing other tokens, which would allow it to "cheat". The pretraining objective is to predict the masked token based on the context. This allows BERT to fully use the left and right contexts to help it learn a deeper and richer representation of the inputs. However, there was still room for improvement in BERT's pretraining strategy. [RoBERTa](model_doc/roberta) improved upon this by introducing a new pretraining recipe that includes training for longer and on larger batches, randomly masking tokens at each epoch instead of just once during preprocessing, and removing the next-sentence prediction objective. 

The dominant strategy to improve performance is to increase the model size. But training large models is computationally expensive. One way to reduce computational costs is using a smaller model like [DistilBERT](model_doc/distilbert). DistilBERT uses [knowledge distillation](https://arxiv.org/abs/1503.02531) - a compression technique - to create a smaller version of BERT while keeping nearly all of its language understanding capabilities. 

However, most Transformer models continued to trend towards more parameters, leading to new models focused on improving training efficiency. [ALBERT](model_doc/albert) reduces memory consumption by lowering the number of parameters in two ways: separating the larger vocabulary embedding into two smaller matrices and allowing layers to share parameters. [DeBERTa](model_doc/deberta) added a disentangled attention mechanism where the word and its position are separately encoded in two vectors. The attention is computed from these separate vectors instead of a single vector containing the word and position embeddings. [Longformer](model_doc/longformer) also focused on making attention more efficient, especially for processing documents with longer sequence lengths. It uses a combination of local windowed attention (attention only calculated from fixed window size around each token) and global attention (only for specific task tokens like `[CLS]` for classification) to create a sparse attention matrix instead of a full attention matrix.

### Decoder[[nlp-decoder]]

[GPT-2](model_doc/gpt2) is a decoder-only Transformer that predicts the next word in the sequence. It masks tokens to the right so the model can't "cheat" by looking ahead. By pretraining on a massive body of text, GPT-2 became really good at generating text, even if the text is only sometimes accurate or true. But GPT-2 lacked the bidirectional context from BERT's pretraining, which made it unsuitable for certain tasks.


key: _node_content
string_value:
{"id_": "262865c1-c6bb-4168-b7f5-bbc7d422e62c", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/model_summary", "title": "The Transformer model family", "tokens": 4019, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "fd6ed4d3-f1ca-498d-9c74-7a5d84385e19", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/model_summary", "title": "The Transformer model family", "tokens": 4019, "retrieve_doc": true, "source": "transformers"}, "hash": "8cead54d1f52c4d818c9192529c1a4c2c648d344c5ad270063818d92463dd149", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "274244d5-1b30-4700-b341-92e1259f1a0a", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/model_summary", "title": "The Transformer model family", "tokens": 4019, "retrieve_doc": true, "source": "transformers"}, "hash": "b3b068642bf42be0a7f344b4fd8a1de96c7e1d960a1237a30eab9916c1226ea7", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "3183ce95-d2af-4515-9058-db07e6e677f2", "node_type": "1", "metadata": {}, "hash": "ddc653538932ca46bf8cc1f16c62fec654434af80223eb7dda3b9e2db715350b", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 7146, "end_char_idx": 10667, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
But training large models is computationally expensive. One way to reduce computational costs is using a smaller model like [DistilBERT](model_doc/distilbert). DistilBERT uses [knowledge distillation](https://arxiv.org/abs/1503.02531) - a compression technique - to create a smaller version of BERT while keeping nearly all of its language understanding capabilities. 

However, most Transformer models continued to trend towards more parameters, leading to new models focused on improving training efficiency. [ALBERT](model_doc/albert) reduces memory consumption by lowering the number of parameters in two ways: separating the larger vocabulary embedding into two smaller matrices and allowing layers to share parameters. [DeBERTa](model_doc/deberta) added a disentangled attention mechanism where the word and its position are separately encoded in two vectors. The attention is computed from these separate vectors instead of a single vector containing the word and position embeddings. [Longformer](model_doc/longformer) also focused on making attention more efficient, especially for processing documents with longer sequence lengths. It uses a combination of local windowed attention (attention only calculated from fixed window size around each token) and global attention (only for specific task tokens like `[CLS]` for classification) to create a sparse attention matrix instead of a full attention matrix.

### Decoder[[nlp-decoder]]

[GPT-2](model_doc/gpt2) is a decoder-only Transformer that predicts the next word in the sequence. It masks tokens to the right so the model can't "cheat" by looking ahead. By pretraining on a massive body of text, GPT-2 became really good at generating text, even if the text is only sometimes accurate or true. But GPT-2 lacked the bidirectional context from BERT's pretraining, which made it unsuitable for certain tasks. [XLNET](model_doc/xlnet) combines the best of both BERT and GPT-2's pretraining objectives by using a permutation language modeling objective (PLM) that allows it to learn bidirectionally.

After GPT-2, language models grew even bigger and are now known as *large language models (LLMs)*. LLMs demonstrate few- or even zero-shot learning if pretrained on a large enough dataset. [GPT-J](model_doc/gptj) is an LLM with 6B parameters and trained on 400B tokens. GPT-J was followed by [OPT](model_doc/opt), a family of decoder-only models, the largest of which is 175B and trained on 180B tokens. [BLOOM](model_doc/bloom) was released around the same time, and the largest model in the family has 176B parameters and is trained on 366B tokens in 46 languages and 13 programming languages.

### Encoder-decoder[[nlp-encoder-decoder]]

[BART](model_doc/bart) keeps the original Transformer architecture, but it modifies the pretraining objective with *text infilling* corruption, where some text spans are replaced with a single `mask` token. The decoder predicts the uncorrupted tokens (future tokens are masked) and uses the encoder's hidden states to help it. [Pegasus](model_doc/pegasus) is similar to BART, but Pegasus masks entire sentences instead of text spans. In addition to masked language modeling, Pegasus is pretrained by gap sentence generation (GSG). The GSG objective masks whole sentences important to a document, replacing them with a `mask` token. The decoder must generate the output from the remaining sentences. [T5](model_doc/t5) is a more unique model that casts all NLP tasks into a text-to-text problem using specific prefixes.


key: _node_content
string_value:
{"id_": "3183ce95-d2af-4515-9058-db07e6e677f2", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/model_summary", "title": "The Transformer model family", "tokens": 4019, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "fd6ed4d3-f1ca-498d-9c74-7a5d84385e19", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/model_summary", "title": "The Transformer model family", "tokens": 4019, "retrieve_doc": true, "source": "transformers"}, "hash": "8cead54d1f52c4d818c9192529c1a4c2c648d344c5ad270063818d92463dd149", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "262865c1-c6bb-4168-b7f5-bbc7d422e62c", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/model_summary", "title": "The Transformer model family", "tokens": 4019, "retrieve_doc": true, "source": "transformers"}, "hash": "c0cce0cce87b96069189fba20bfdf7a0a0a3b158989ba883922efe9231b879d3", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "d937da67-2c92-437f-bbe8-f65939cfcb2e", "node_type": "1", "metadata": {}, "hash": "f719a4cf576fe33f48ab4b7bfda7364116c1b23a66d7bd24715e3751f0c590b0", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 9018, "end_char_idx": 12070, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
[XLNET](model_doc/xlnet) combines the best of both BERT and GPT-2's pretraining objectives by using a permutation language modeling objective (PLM) that allows it to learn bidirectionally.

After GPT-2, language models grew even bigger and are now known as *large language models (LLMs)*. LLMs demonstrate few- or even zero-shot learning if pretrained on a large enough dataset. [GPT-J](model_doc/gptj) is an LLM with 6B parameters and trained on 400B tokens. GPT-J was followed by [OPT](model_doc/opt), a family of decoder-only models, the largest of which is 175B and trained on 180B tokens. [BLOOM](model_doc/bloom) was released around the same time, and the largest model in the family has 176B parameters and is trained on 366B tokens in 46 languages and 13 programming languages.

### Encoder-decoder[[nlp-encoder-decoder]]

[BART](model_doc/bart) keeps the original Transformer architecture, but it modifies the pretraining objective with *text infilling* corruption, where some text spans are replaced with a single `mask` token. The decoder predicts the uncorrupted tokens (future tokens are masked) and uses the encoder's hidden states to help it. [Pegasus](model_doc/pegasus) is similar to BART, but Pegasus masks entire sentences instead of text spans. In addition to masked language modeling, Pegasus is pretrained by gap sentence generation (GSG). The GSG objective masks whole sentences important to a document, replacing them with a `mask` token. The decoder must generate the output from the remaining sentences. [T5](model_doc/t5) is a more unique model that casts all NLP tasks into a text-to-text problem using specific prefixes. For example, the prefix `Summarize:` indicates a summarization task. T5 is pretrained by supervised (GLUE and SuperGLUE) training and self-supervised training (randomly sample and drop out 15% of tokens).

## Audio

<iframe style="border: 1px solid rgba(0, 0, 0, 0.1);" width="1000" height="450" src="https://www.figma.com/embed?embed_host=share&url=https%3A%2F%2Fwww.figma.com%2Ffile%2Fvrchl8jDV9YwNVPWu2W0kK%2Fspeech-and-audio-model-timeline%3Fnode-id%3D0%253A1%26t%3DmM4H8pPMuK23rClL-1" allowfullscreen></iframe>

### Encoder[[audio-encoder]]

[Wav2Vec2](model_doc/wav2vec2) uses a Transformer encoder to learn speech representations directly from raw audio waveforms. It is pretrained with a contrastive task to determine the true speech representation from a set of false ones. [HuBERT](model_doc/hubert) is similar to Wav2Vec2 but has a different training process. Target labels are created by a clustering step in which segments of similar audio are assigned to a cluster which becomes a hidden unit. The hidden unit is mapped to an embedding to make a prediction.

### Encoder-decoder[[audio-encoder-decoder]]

[Speech2Text](model_doc/speech_to_text) is a speech model designed for automatic speech recognition (ASR) and speech translation. The model accepts log mel-filter bank features extracted from the audio waveform and pretrained autoregressively to generate a transcript or translation.


key: _node_content
string_value:
{"id_": "d937da67-2c92-437f-bbe8-f65939cfcb2e", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/model_summary", "title": "The Transformer model family", "tokens": 4019, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "fd6ed4d3-f1ca-498d-9c74-7a5d84385e19", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/model_summary", "title": "The Transformer model family", "tokens": 4019, "retrieve_doc": true, "source": "transformers"}, "hash": "8cead54d1f52c4d818c9192529c1a4c2c648d344c5ad270063818d92463dd149", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "3183ce95-d2af-4515-9058-db07e6e677f2", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/model_summary", "title": "The Transformer model family", "tokens": 4019, "retrieve_doc": true, "source": "transformers"}, "hash": "a31a3c0a39c724e2981998c1a7a780fb2dfd53e9e15193fabb94c4963863658b", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "205c83f6-11bd-4b67-b231-dc27dc9f6eba", "node_type": "1", "metadata": {}, "hash": "d5ebde93d67712f3bfdeb34e1d16fdedea36108cffd66feb9f6274c797da4022", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 10668, "end_char_idx": 13583, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
For example, the prefix `Summarize:` indicates a summarization task. T5 is pretrained by supervised (GLUE and SuperGLUE) training and self-supervised training (randomly sample and drop out 15% of tokens).

## Audio

<iframe style="border: 1px solid rgba(0, 0, 0, 0.1);" width="1000" height="450" src="https://www.figma.com/embed?embed_host=share&url=https%3A%2F%2Fwww.figma.com%2Ffile%2Fvrchl8jDV9YwNVPWu2W0kK%2Fspeech-and-audio-model-timeline%3Fnode-id%3D0%253A1%26t%3DmM4H8pPMuK23rClL-1" allowfullscreen></iframe>

### Encoder[[audio-encoder]]

[Wav2Vec2](model_doc/wav2vec2) uses a Transformer encoder to learn speech representations directly from raw audio waveforms. It is pretrained with a contrastive task to determine the true speech representation from a set of false ones. [HuBERT](model_doc/hubert) is similar to Wav2Vec2 but has a different training process. Target labels are created by a clustering step in which segments of similar audio are assigned to a cluster which becomes a hidden unit. The hidden unit is mapped to an embedding to make a prediction.

### Encoder-decoder[[audio-encoder-decoder]]

[Speech2Text](model_doc/speech_to_text) is a speech model designed for automatic speech recognition (ASR) and speech translation. The model accepts log mel-filter bank features extracted from the audio waveform and pretrained autoregressively to generate a transcript or translation. [Whisper](model_doc/whisper) is also an ASR model, but unlike many other speech models, it is pretrained on a massive amount of ✨ labeled ✨ audio transcription data for zero-shot performance. A large chunk of the dataset also contains non-English languages, meaning Whisper can also be used for low-resource languages. Structurally, Whisper is similar to Speech2Text. The audio signal is converted to a log-mel spectrogram encoded by the encoder. The decoder generates the transcript autoregressively from the encoder's hidden states and the previous tokens.

## Multimodal

<iframe style="border: 1px solid rgba(0, 0, 0, 0.1);" width="1000" height="450" src="https://www.figma.com/embed?embed_host=share&url=https%3A%2F%2Fwww.figma.com%2Ffile%2FcX125FQHXJS2gxeICiY93p%2Fmultimodal%3Fnode-id%3D0%253A1%26t%3DhPQwdx3HFPWJWnVf-1" allowfullscreen></iframe>

### Encoder[[mm-encoder]]

[VisualBERT](model_doc/visual_bert) is a multimodal model for vision-language tasks released shortly after BERT. It combines BERT and a pretrained object detection system to extract image features into visual embeddings, passed alongside text embeddings to BERT. VisualBERT predicts the masked text based on the unmasked text and the visual embeddings, and it also has to predict whether the text is aligned with the image. When ViT was released, [ViLT](model_doc/vilt) adopted ViT in its architecture because it was easier to get the image embeddings this way. The image embeddings are jointly processed with the text embeddings.


key: _node_content
string_value:
{"id_": "205c83f6-11bd-4b67-b231-dc27dc9f6eba", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/model_summary", "title": "The Transformer model family", "tokens": 4019, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "fd6ed4d3-f1ca-498d-9c74-7a5d84385e19", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/model_summary", "title": "The Transformer model family", "tokens": 4019, "retrieve_doc": true, "source": "transformers"}, "hash": "8cead54d1f52c4d818c9192529c1a4c2c648d344c5ad270063818d92463dd149", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "d937da67-2c92-437f-bbe8-f65939cfcb2e", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/model_summary", "title": "The Transformer model family", "tokens": 4019, "retrieve_doc": true, "source": "transformers"}, "hash": "fa6c702bf46bc45dbfd23db38fdade0b4aa487138c200805be43e560071c626d", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "f843c63c-3867-4062-a01f-88e185a3463e", "node_type": "1", "metadata": {}, "hash": "55d7f6021f5b22795320384716981b088bd8b5ea976418e4c23e88a80e15cad1", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 12071, "end_char_idx": 15267, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
[Whisper](model_doc/whisper) is also an ASR model, but unlike many other speech models, it is pretrained on a massive amount of ✨ labeled ✨ audio transcription data for zero-shot performance. A large chunk of the dataset also contains non-English languages, meaning Whisper can also be used for low-resource languages. Structurally, Whisper is similar to Speech2Text. The audio signal is converted to a log-mel spectrogram encoded by the encoder. The decoder generates the transcript autoregressively from the encoder's hidden states and the previous tokens.

## Multimodal

<iframe style="border: 1px solid rgba(0, 0, 0, 0.1);" width="1000" height="450" src="https://www.figma.com/embed?embed_host=share&url=https%3A%2F%2Fwww.figma.com%2Ffile%2FcX125FQHXJS2gxeICiY93p%2Fmultimodal%3Fnode-id%3D0%253A1%26t%3DhPQwdx3HFPWJWnVf-1" allowfullscreen></iframe>

### Encoder[[mm-encoder]]

[VisualBERT](model_doc/visual_bert) is a multimodal model for vision-language tasks released shortly after BERT. It combines BERT and a pretrained object detection system to extract image features into visual embeddings, passed alongside text embeddings to BERT. VisualBERT predicts the masked text based on the unmasked text and the visual embeddings, and it also has to predict whether the text is aligned with the image. When ViT was released, [ViLT](model_doc/vilt) adopted ViT in its architecture because it was easier to get the image embeddings this way. The image embeddings are jointly processed with the text embeddings. From there, ViLT is pretrained by image text matching, masked language modeling, and whole word masking.

[CLIP](model_doc/clip) takes a different approach and makes a pair prediction of (`image`, `text`) . An image encoder (ViT) and a text encoder (Transformer) are jointly trained on a 400 million (`image`, `text`) pair dataset to maximize the similarity between the image and text embeddings of the (`image`, `text`) pairs. After pretraining, you can use natural language to instruct CLIP to predict the text given an image or vice versa. [OWL-ViT](model_doc/owlvit) builds on top of CLIP by using it as its backbone for zero-shot object detection. After pretraining, an object detection head is added to make a set prediction over the (`class`, `bounding box`) pairs.

### Encoder-decoder[[mm-encoder-decoder]]

Optical character recognition (OCR) is a long-standing text recognition task that typically involves several components to understand the image and generate the text. [TrOCR](model_doc/trocr) simplifies the process using an end-to-end Transformer. The encoder is a ViT-style model for image understanding and processes the image as fixed-size patches. The decoder accepts the encoder's hidden states and autoregressively generates text. [Donut](model_doc/donut) is a more general visual document understanding model that doesn't rely on OCR-based approaches. It uses a Swin Transformer as the encoder and multilingual BART as the decoder. Donut is pretrained to read text by predicting the next word based on the image and text annotations. The decoder generates a token sequence given a prompt. The prompt is represented by a special token for each downstream task.


key: _node_content
string_value:
{"id_": "f843c63c-3867-4062-a01f-88e185a3463e", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/model_summary", "title": "The Transformer model family", "tokens": 4019, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "fd6ed4d3-f1ca-498d-9c74-7a5d84385e19", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/model_summary", "title": "The Transformer model family", "tokens": 4019, "retrieve_doc": true, "source": "transformers"}, "hash": "8cead54d1f52c4d818c9192529c1a4c2c648d344c5ad270063818d92463dd149", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "205c83f6-11bd-4b67-b231-dc27dc9f6eba", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/model_summary", "title": "The Transformer model family", "tokens": 4019, "retrieve_doc": true, "source": "transformers"}, "hash": "74299f09fc5979aeab98d5bd804c6b4941c61ba12ac7b274e64037863ff1c96a", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 13515, "end_char_idx": 16524, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
The image embeddings are jointly processed with the text embeddings. From there, ViLT is pretrained by image text matching, masked language modeling, and whole word masking.

[CLIP](model_doc/clip) takes a different approach and makes a pair prediction of (`image`, `text`) . An image encoder (ViT) and a text encoder (Transformer) are jointly trained on a 400 million (`image`, `text`) pair dataset to maximize the similarity between the image and text embeddings of the (`image`, `text`) pairs. After pretraining, you can use natural language to instruct CLIP to predict the text given an image or vice versa. [OWL-ViT](model_doc/owlvit) builds on top of CLIP by using it as its backbone for zero-shot object detection. After pretraining, an object detection head is added to make a set prediction over the (`class`, `bounding box`) pairs.

### Encoder-decoder[[mm-encoder-decoder]]

Optical character recognition (OCR) is a long-standing text recognition task that typically involves several components to understand the image and generate the text. [TrOCR](model_doc/trocr) simplifies the process using an end-to-end Transformer. The encoder is a ViT-style model for image understanding and processes the image as fixed-size patches. The decoder accepts the encoder's hidden states and autoregressively generates text. [Donut](model_doc/donut) is a more general visual document understanding model that doesn't rely on OCR-based approaches. It uses a Swin Transformer as the encoder and multilingual BART as the decoder. Donut is pretrained to read text by predicting the next word based on the image and text annotations. The decoder generates a token sequence given a prompt. The prompt is represented by a special token for each downstream task. For example, document parsing has a special `parsing` token that is combined with the encoder hidden states to parse the document into a structured output format (JSON).

## Reinforcement learning

<iframe style="border: 1px solid rgba(0, 0, 0, 0.1);" width="1000" height="450" src="https://www.figma.com/embed?embed_host=share&url=https%3A%2F%2Fwww.figma.com%2Ffile%2FiB3Y6RvWYki7ZuKO6tNgZq%2Freinforcement-learning%3Fnode-id%3D0%253A1%26t%3DhPQwdx3HFPWJWnVf-1" allowfullscreen></iframe>

### Decoder[[rl-decoder]]

The Decision and Trajectory Transformer casts the state, action, and reward as a sequence modeling problem. The [Decision Transformer](model_doc/decision_transformer) generates a series of actions that lead to a future desired return based on returns-to-go, past states, and actions. For the last *K* timesteps, each of the three modalities are converted into token embeddings and processed by a GPT-like model to predict a future action token. [Trajectory Transformer](model_doc/trajectory_transformer) also tokenizes the states, actions, and rewards and processes them with a GPT architecture. Unlike the Decision Transformer, which is focused on reward conditioning, the Trajectory Transformer generates future actions with beam search.


key: _node_content
string_value:
{"id_": "60aa5821-1a7e-4082-9674-200629fd36f2", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/perf_hardware", "title": "Custom hardware for training", "tokens": 1941, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "ce45066f-bb84-4136-8a15-25e2b289e1db", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/perf_hardware", "title": "Custom hardware for training", "tokens": 1941, "retrieve_doc": true, "source": "transformers"}, "hash": "e8838a6c78427147c4993990011b8914b4ed1ea4b07c2b4cb49c8e0365b689de", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "41d03d1e-1ecb-49f1-b37e-a05e9aa19211", "node_type": "1", "metadata": {}, "hash": "34cee575c4a8d6656ad5e45edec6ab7cced2b101a667d59d84188a5a540f992c", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 3286, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
<!---
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 agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
rendered properly in your Markdown viewer.

-->


# Custom hardware for training

The hardware you use to run model training and inference can have a big effect on performance. For a deep dive into GPUs make sure to check out Tim Dettmer's excellent [blog post](https://timdettmers.com/2020/09/07/which-gpu-for-deep-learning/).

Let's have a look at some practical advice for GPU setups.

## GPU
When you train bigger models you have essentially three options:

- bigger GPUs
- more GPUs
- more CPU and NVMe (offloaded to by [DeepSpeed-Infinity](main_classes/deepspeed#nvme-support))

Let's start at the case where you have a single GPU.

### Power and Cooling

If you bought an expensive high end GPU make sure you give it the correct power and sufficient cooling.

**Power**:

Some high end consumer GPU cards have 2 and sometimes 3 PCI-E 8-Pin power sockets. Make sure you have as many independent 12V PCI-E 8-Pin cables plugged into the card as there are sockets. Do not use the 2 splits at one end of the same cable (also known as pigtail cable). That is if you have 2 sockets on the GPU, you want 2 PCI-E 8-Pin cables going from your PSU to the card and not one that has 2 PCI-E 8-Pin connectors at the end! You won't get the full performance out of your card otherwise.

Each PCI-E 8-Pin power cable needs to be plugged into a 12V rail on the PSU side and can supply up to 150W of power.

Some other cards may use a PCI-E 12-Pin connectors, and these can deliver up to 500-600W of power.

Low end cards may use 6-Pin connectors, which supply up to 75W of power.

Additionally you want the high-end PSU that has stable voltage. Some lower quality ones may not give the card the stable voltage it needs to function at its peak.

And of course the PSU needs to have enough unused Watts to power the card.

**Cooling**:

When a GPU gets overheated it will start throttling down and will not deliver full performance and it can even shutdown if it gets too hot.

It's hard to tell the exact best temperature to strive for when a GPU is heavily loaded, but probably anything under +80C is good, but lower is better - perhaps 70-75C is an excellent range to be in. The throttling down is likely to start at around 84-90C. But other than throttling performance a prolonged very high temperature is likely to reduce the lifespan of a GPU.

Next let's have a look at one of the most important aspects when having multiple GPUs: connectivity.

### Multi-GPU Connectivity

If you use multiple GPUs the way cards are inter-connected can have a huge impact on the total training time.


key: _node_content
string_value:
{"id_": "41d03d1e-1ecb-49f1-b37e-a05e9aa19211", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/perf_hardware", "title": "Custom hardware for training", "tokens": 1941, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "ce45066f-bb84-4136-8a15-25e2b289e1db", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/perf_hardware", "title": "Custom hardware for training", "tokens": 1941, "retrieve_doc": true, "source": "transformers"}, "hash": "e8838a6c78427147c4993990011b8914b4ed1ea4b07c2b4cb49c8e0365b689de", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "60aa5821-1a7e-4082-9674-200629fd36f2", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/perf_hardware", "title": "Custom hardware for training", "tokens": 1941, "retrieve_doc": true, "source": "transformers"}, "hash": "fda7bb9e045edb477dbf78dffec491870dc18bee2c6a01730b9c7f4ba793188c", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "bcec998a-b9bf-45a6-ad42-2a67c5f1cf8a", "node_type": "1", "metadata": {}, "hash": "54b4d826cda659e6691a587f07df8481d0d3ed69a982fdf112f8ada872f9d2be", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 1677, "end_char_idx": 4771, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Do not use the 2 splits at one end of the same cable (also known as pigtail cable). That is if you have 2 sockets on the GPU, you want 2 PCI-E 8-Pin cables going from your PSU to the card and not one that has 2 PCI-E 8-Pin connectors at the end! You won't get the full performance out of your card otherwise.

Each PCI-E 8-Pin power cable needs to be plugged into a 12V rail on the PSU side and can supply up to 150W of power.

Some other cards may use a PCI-E 12-Pin connectors, and these can deliver up to 500-600W of power.

Low end cards may use 6-Pin connectors, which supply up to 75W of power.

Additionally you want the high-end PSU that has stable voltage. Some lower quality ones may not give the card the stable voltage it needs to function at its peak.

And of course the PSU needs to have enough unused Watts to power the card.

**Cooling**:

When a GPU gets overheated it will start throttling down and will not deliver full performance and it can even shutdown if it gets too hot.

It's hard to tell the exact best temperature to strive for when a GPU is heavily loaded, but probably anything under +80C is good, but lower is better - perhaps 70-75C is an excellent range to be in. The throttling down is likely to start at around 84-90C. But other than throttling performance a prolonged very high temperature is likely to reduce the lifespan of a GPU.

Next let's have a look at one of the most important aspects when having multiple GPUs: connectivity.

### Multi-GPU Connectivity

If you use multiple GPUs the way cards are inter-connected can have a huge impact on the total training time. If the GPUs are on the same physical node, you can run:

```bash
nvidia-smi topo -m
```

and it will tell you how the GPUs are inter-connected. On a machine with dual-GPU and which are connected with NVLink, you will most likely see something like:

```
        GPU0    GPU1    CPU Affinity    NUMA Affinity
GPU0     X      NV2     0-23            N/A
GPU1    NV2      X      0-23            N/A
```

on a different machine w/o NVLink we may see:
```
        GPU0    GPU1    CPU Affinity    NUMA Affinity
GPU0     X      PHB     0-11            N/A
GPU1    PHB      X      0-11            N/A
```

The report includes this legend:

```
  X    = Self
  SYS  = Connection traversing PCIe as well as the SMP interconnect between NUMA nodes (e.g., QPI/UPI)
  NODE = Connection traversing PCIe as well as the interconnect between PCIe Host Bridges within a NUMA node
  PHB  = Connection traversing PCIe as well as a PCIe Host Bridge (typically the CPU)
  PXB  = Connection traversing multiple PCIe bridges (without traversing the PCIe Host Bridge)
  PIX  = Connection traversing at most a single PCIe bridge
  NV#  = Connection traversing a bonded set of # NVLinks
```

So the first report `NV2` tells us the GPUs are interconnected with 2 NVLinks, and the second report `PHB` we have a typical consumer-level PCIe+Bridge setup.

Check what type of connectivity you have on your setup. Some of these will make the communication between cards faster (e.g. NVLink), others slower (e.g. PHB).


key: _node_content
string_value:
{"id_": "bcec998a-b9bf-45a6-ad42-2a67c5f1cf8a", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/perf_hardware", "title": "Custom hardware for training", "tokens": 1941, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "ce45066f-bb84-4136-8a15-25e2b289e1db", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/perf_hardware", "title": "Custom hardware for training", "tokens": 1941, "retrieve_doc": true, "source": "transformers"}, "hash": "e8838a6c78427147c4993990011b8914b4ed1ea4b07c2b4cb49c8e0365b689de", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "41d03d1e-1ecb-49f1-b37e-a05e9aa19211", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/perf_hardware", "title": "Custom hardware for training", "tokens": 1941, "retrieve_doc": true, "source": "transformers"}, "hash": "28ed93b03afccfae9a9784493935b1c18c80fe17c2bcebfaf61c6dc9ac806cf1", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "d9e243d3-3d0b-4448-be2b-b8edf916985d", "node_type": "1", "metadata": {}, "hash": "892aecf849bcdd19da82ab9ff46d89acb8f7ad231f9549766f70f8555d833814", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 3287, "end_char_idx": 6271, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
If the GPUs are on the same physical node, you can run:

```bash
nvidia-smi topo -m
```

and it will tell you how the GPUs are inter-connected. On a machine with dual-GPU and which are connected with NVLink, you will most likely see something like:

```
        GPU0    GPU1    CPU Affinity    NUMA Affinity
GPU0     X      NV2     0-23            N/A
GPU1    NV2      X      0-23            N/A
```

on a different machine w/o NVLink we may see:
```
        GPU0    GPU1    CPU Affinity    NUMA Affinity
GPU0     X      PHB     0-11            N/A
GPU1    PHB      X      0-11            N/A
```

The report includes this legend:

```
  X    = Self
  SYS  = Connection traversing PCIe as well as the SMP interconnect between NUMA nodes (e.g., QPI/UPI)
  NODE = Connection traversing PCIe as well as the interconnect between PCIe Host Bridges within a NUMA node
  PHB  = Connection traversing PCIe as well as a PCIe Host Bridge (typically the CPU)
  PXB  = Connection traversing multiple PCIe bridges (without traversing the PCIe Host Bridge)
  PIX  = Connection traversing at most a single PCIe bridge
  NV#  = Connection traversing a bonded set of # NVLinks
```

So the first report `NV2` tells us the GPUs are interconnected with 2 NVLinks, and the second report `PHB` we have a typical consumer-level PCIe+Bridge setup.

Check what type of connectivity you have on your setup. Some of these will make the communication between cards faster (e.g. NVLink), others slower (e.g. PHB).

Depending on the type of scalability solution used, the connectivity speed could have a major or a minor impact. If the GPUs need to sync rarely, as in DDP, the impact of a slower connection will be less significant. If the GPUs need to send messages to each other often, as in ZeRO-DP, then faster connectivity becomes super important to achieve faster training.

#### NVlink

[NVLink](https://en.wikipedia.org/wiki/NVLink) is a wire-based serial multi-lane near-range communications link developed by Nvidia.

Each new generation provides a faster bandwidth, e.g. here is a quote from [Nvidia Ampere GA102 GPU Architecture](https://www.nvidia.com/content/dam/en-zz/Solutions/geforce/ampere/pdf/NVIDIA-ampere-GA102-GPU-Architecture-Whitepaper-V1.pdf):

> Third-Generation NVLink®
> GA102 GPUs utilize NVIDIA’s third-generation NVLink interface, which includes four x4 links,
> with each link providing 14.0625 GB/sec bandwidth in each direction between two GPUs. Four
> links provide 56.25 GB/sec bandwidth in each direction, and 112.5 GB/sec total bandwidth
> between two GPUs. Two RTX 3090 GPUs can be connected together for SLI using NVLink.
> (Note that 3-Way and 4-Way SLI configurations are not supported.)

So the higher `X` you get in the report of `NVX` in the output of `nvidia-smi topo -m` the better. The generation will depend on your GPU architecture.

Let's compare the execution of an openai-community/gpt2 language model training over a small sample of wikitext.

The results are:


key: _node_content
string_value:
{"id_": "d9e243d3-3d0b-4448-be2b-b8edf916985d", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/perf_hardware", "title": "Custom hardware for training", "tokens": 1941, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "ce45066f-bb84-4136-8a15-25e2b289e1db", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/perf_hardware", "title": "Custom hardware for training", "tokens": 1941, "retrieve_doc": true, "source": "transformers"}, "hash": "e8838a6c78427147c4993990011b8914b4ed1ea4b07c2b4cb49c8e0365b689de", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "bcec998a-b9bf-45a6-ad42-2a67c5f1cf8a", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/perf_hardware", "title": "Custom hardware for training", "tokens": 1941, "retrieve_doc": true, "source": "transformers"}, "hash": "1cb08c8f7c50b89722f9f03b0f4ea0a9b585ea4412775711d5c65e5329008fe4", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "33cd143c-d735-4ca2-ba2a-e44183513b5d", "node_type": "1", "metadata": {}, "hash": "ded506ad8664380d5638592adb5cd5ec430e6117255272c8ab9dd20070e07e7b", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 4668, "end_char_idx": 6345, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Some of these will make the communication between cards faster (e.g. NVLink), others slower (e.g. PHB).

Depending on the type of scalability solution used, the connectivity speed could have a major or a minor impact. If the GPUs need to sync rarely, as in DDP, the impact of a slower connection will be less significant. If the GPUs need to send messages to each other often, as in ZeRO-DP, then faster connectivity becomes super important to achieve faster training.

#### NVlink

[NVLink](https://en.wikipedia.org/wiki/NVLink) is a wire-based serial multi-lane near-range communications link developed by Nvidia.

Each new generation provides a faster bandwidth, e.g. here is a quote from [Nvidia Ampere GA102 GPU Architecture](https://www.nvidia.com/content/dam/en-zz/Solutions/geforce/ampere/pdf/NVIDIA-ampere-GA102-GPU-Architecture-Whitepaper-V1.pdf):

> Third-Generation NVLink®
> GA102 GPUs utilize NVIDIA’s third-generation NVLink interface, which includes four x4 links,
> with each link providing 14.0625 GB/sec bandwidth in each direction between two GPUs. Four
> links provide 56.25 GB/sec bandwidth in each direction, and 112.5 GB/sec total bandwidth
> between two GPUs. Two RTX 3090 GPUs can be connected together for SLI using NVLink.
> (Note that 3-Way and 4-Way SLI configurations are not supported.)

So the higher `X` you get in the report of `NVX` in the output of `nvidia-smi topo -m` the better. The generation will depend on your GPU architecture.

Let's compare the execution of an openai-community/gpt2 language model training over a small sample of wikitext.

The results are:


| NVlink | Time |
| -----  | ---: |
| Y      | 101s |
| N      | 131s |


key: _node_content
string_value:
{"id_": "33cd143c-d735-4ca2-ba2a-e44183513b5d", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/perf_hardware", "title": "Custom hardware for training", "tokens": 1941, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "ce45066f-bb84-4136-8a15-25e2b289e1db", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/perf_hardware", "title": "Custom hardware for training", "tokens": 1941, "retrieve_doc": true, "source": "transformers"}, "hash": "e8838a6c78427147c4993990011b8914b4ed1ea4b07c2b4cb49c8e0365b689de", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "d9e243d3-3d0b-4448-be2b-b8edf916985d", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/perf_hardware", "title": "Custom hardware for training", "tokens": 1941, "retrieve_doc": true, "source": "transformers"}, "hash": "2d3fb788533fb2dd41baed8ec634ed9319fd32f536da8710adeca7f63b7e9443", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 4773, "end_char_idx": 7566, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Depending on the type of scalability solution used, the connectivity speed could have a major or a minor impact. If the GPUs need to sync rarely, as in DDP, the impact of a slower connection will be less significant. If the GPUs need to send messages to each other often, as in ZeRO-DP, then faster connectivity becomes super important to achieve faster training.

#### NVlink

[NVLink](https://en.wikipedia.org/wiki/NVLink) is a wire-based serial multi-lane near-range communications link developed by Nvidia.

Each new generation provides a faster bandwidth, e.g. here is a quote from [Nvidia Ampere GA102 GPU Architecture](https://www.nvidia.com/content/dam/en-zz/Solutions/geforce/ampere/pdf/NVIDIA-ampere-GA102-GPU-Architecture-Whitepaper-V1.pdf):

> Third-Generation NVLink®
> GA102 GPUs utilize NVIDIA’s third-generation NVLink interface, which includes four x4 links,
> with each link providing 14.0625 GB/sec bandwidth in each direction between two GPUs. Four
> links provide 56.25 GB/sec bandwidth in each direction, and 112.5 GB/sec total bandwidth
> between two GPUs. Two RTX 3090 GPUs can be connected together for SLI using NVLink.
> (Note that 3-Way and 4-Way SLI configurations are not supported.)

So the higher `X` you get in the report of `NVX` in the output of `nvidia-smi topo -m` the better. The generation will depend on your GPU architecture.

Let's compare the execution of an openai-community/gpt2 language model training over a small sample of wikitext.

The results are:


| NVlink | Time |
| -----  | ---: |
| Y      | 101s |
| N      | 131s |


You can see that NVLink completes the training ~23% faster. In the second benchmark we use `NCCL_P2P_DISABLE=1` to tell the GPUs not to use NVLink.

Here is the full benchmark code and outputs:

```bash
# DDP w/ NVLink

rm -r /tmp/test-clm; CUDA_VISIBLE_DEVICES=0,1 torchrun \
--nproc_per_node 2 examples/pytorch/language-modeling/run_clm.py --model_name_or_path openai-community/gpt2 \
--dataset_name wikitext --dataset_config_name wikitext-2-raw-v1 --do_train \
--output_dir /tmp/test-clm --per_device_train_batch_size 4 --max_steps 200

{'train_runtime': 101.9003, 'train_samples_per_second': 1.963, 'epoch': 0.69}

# DDP w/o NVLink

rm -r /tmp/test-clm; CUDA_VISIBLE_DEVICES=0,1 NCCL_P2P_DISABLE=1 torchrun \
--nproc_per_node 2 examples/pytorch/language-modeling/run_clm.py --model_name_or_path openai-community/gpt2 \
--dataset_name wikitext --dataset_config_name wikitext-2-raw-v1 --do_train
--output_dir /tmp/test-clm --per_device_train_batch_size 4 --max_steps 200

{'train_runtime': 131.4367, 'train_samples_per_second': 1.522, 'epoch': 0.69}
```

Hardware: 2x TITAN RTX 24GB each + NVlink with 2 NVLinks (`NV2` in `nvidia-smi topo -m`)
Software: `pytorch-1.8-to-be` + `cuda-11.0` / `transformers==4.3.0.dev0`


key: _node_content
string_value:
{"id_": "0158a30c-859e-47f0-8abf-ddde5d22e068", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/gguf", "title": "GGUF and interaction with Transformers", "tokens": 984, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "63af9d7a-4340-4cbb-9202-513cd71b5282", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/gguf", "title": "GGUF and interaction with Transformers", "tokens": 984, "retrieve_doc": true, "source": "transformers"}, "hash": "1aba5118f2cd3cdbca993da6d6369eb9cb53f690196a24a74b6e9704122221f0", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "aa2831f6-5b84-468a-bce7-e8bd7a8e367e", "node_type": "1", "metadata": {}, "hash": "067c475a9a529ec610dc84b48ff8150b30d8f2a1407c1e4600607487e6f65e24", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 2969, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# GGUF and interaction with Transformers

The GGUF file format is used to store models for inference with [GGML](https://github.com/ggerganov/ggml) and other 
libraries that depend on it, like the very popular [llama.cpp](https://github.com/ggerganov/llama.cpp) or 
[whisper.cpp](https://github.com/ggerganov/whisper.cpp).

It is a file format [supported by the Hugging Face Hub](https://huggingface.co/docs/hub/en/gguf) with features 
allowing for quick inspection of tensors and metadata within the file.

This file format is designed as a "single-file-format" where a single file usually contains both the configuration
attributes, the tokenizer vocabulary and other attributes, as well as all tensors to be loaded in the model. These
files come in different formats according to the quantization type of the file. We briefly go over some of them
[here](https://huggingface.co/docs/hub/en/gguf#quantization-types).

## Support within Transformers

We have added the ability to load `gguf` files within `transformers` in order to offer further training/fine-tuning
capabilities to gguf models, before converting back those models to `gguf` to use within the `ggml` ecosystem. When
loading a model, we first dequantize it to fp32, before loading the weights to be used in PyTorch.

> [!NOTE]
> The support is still very exploratory and we welcome contributions in order to solidify it across quantization types
> and model architectures.

For now, here are the supported model architectures and quantization types:

### Supported quantization types

The initial supported quantization types are decided according to the popular quantized files that have been shared
on the Hub.

- F32
- Q2_K
- Q3_K
- Q4_0
- Q4_K
- Q5_K
- Q6_K
- Q8_0

We take example from the excellent [99991/pygguf](https://github.com/99991/pygguf) Python parser to dequantize the 
weights.

### Supported model architectures

For now the supported model architectures are the architectures that have been very popular on the Hub, namely:

- LLaMa
- Mistral
- Qwen2

## Example usage

In order to load `gguf` files in `transformers`, you should specify the `gguf_file` argument to the `from_pretrained`
methods of both tokenizers and models. Here is how one would load a tokenizer and a model, which can be loaded
from the exact same file:

```py
from transformers import AutoTokenizer, AutoModelForCausalLM

model_id = "TheBloke/TinyLlama-1.1B-Chat-v1.0-GGUF"
filename = "tinyllama-1.1b-chat-v1.0.Q6_K.gguf"

tokenizer = AutoTokenizer.from_pretrained(model_id, gguf_file=filename)
model = AutoModelForCausalLM.from_pretrained(model_id, gguf_file=filename)
```

Now you have access to the full, unquantized version of the model in the PyTorch ecosystem, where you can combine it
with a plethora of other tools.

In order to convert back to a `gguf` file, we recommend using the 
[`convert-hf-to-gguf.py` file](https://github.com/ggerganov/llama.cpp/blob/master/convert-hf-to-gguf.py) from llama.cpp.


key: _node_content
string_value:
{"id_": "aa2831f6-5b84-468a-bce7-e8bd7a8e367e", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/gguf", "title": "GGUF and interaction with Transformers", "tokens": 984, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "63af9d7a-4340-4cbb-9202-513cd71b5282", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/gguf", "title": "GGUF and interaction with Transformers", "tokens": 984, "retrieve_doc": true, "source": "transformers"}, "hash": "1aba5118f2cd3cdbca993da6d6369eb9cb53f690196a24a74b6e9704122221f0", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "0158a30c-859e-47f0-8abf-ddde5d22e068", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/gguf", "title": "GGUF and interaction with Transformers", "tokens": 984, "retrieve_doc": true, "source": "transformers"}, "hash": "08d09dedf6a752d416eb85d376710739eea6970d94f040486bbd0913d0b71202", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 1680, "end_char_idx": 3215, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
- F32
- Q2_K
- Q3_K
- Q4_0
- Q4_K
- Q5_K
- Q6_K
- Q8_0

We take example from the excellent [99991/pygguf](https://github.com/99991/pygguf) Python parser to dequantize the 
weights.

### Supported model architectures

For now the supported model architectures are the architectures that have been very popular on the Hub, namely:

- LLaMa
- Mistral
- Qwen2

## Example usage

In order to load `gguf` files in `transformers`, you should specify the `gguf_file` argument to the `from_pretrained`
methods of both tokenizers and models. Here is how one would load a tokenizer and a model, which can be loaded
from the exact same file:

```py
from transformers import AutoTokenizer, AutoModelForCausalLM

model_id = "TheBloke/TinyLlama-1.1B-Chat-v1.0-GGUF"
filename = "tinyllama-1.1b-chat-v1.0.Q6_K.gguf"

tokenizer = AutoTokenizer.from_pretrained(model_id, gguf_file=filename)
model = AutoModelForCausalLM.from_pretrained(model_id, gguf_file=filename)
```

Now you have access to the full, unquantized version of the model in the PyTorch ecosystem, where you can combine it
with a plethora of other tools.

In order to convert back to a `gguf` file, we recommend using the 
[`convert-hf-to-gguf.py` file](https://github.com/ggerganov/llama.cpp/blob/master/convert-hf-to-gguf.py) from llama.cpp.

Here's how you would complete the script above to save the model and export it back to `gguf`:

```py
tokenizer.save_pretrained('directory')
model.save_pretrained('directory')

!python ${path_to_llama_cpp}/convert-hf-to-gguf.py ${directory}
```


key: _node_content
string_value:
{"id_": "29fa1f44-5f62-4b5c-96d5-dff4f712f6f0", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/attention", "title": "Attention mechanisms", "tokens": 862, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "c0127d63-dfa8-4c4c-9a21-cbe4211252ad", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/attention", "title": "Attention mechanisms", "tokens": 862, "retrieve_doc": true, "source": "transformers"}, "hash": "a2f77a27d88eca3804ec54054d070a99e06e4ac4a4127d03a79079e6d8d8a746", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 2906, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# Attention mechanisms

Most transformer models use full attention in the sense that the attention matrix is square. It can be a big
computational bottleneck when you have long texts. Longformer and reformer are models that try to be more efficient and
use a sparse version of the attention matrix to speed up training.

## LSH attention

[Reformer](model_doc/reformer) uses LSH attention. In the softmax(QK^t), only the biggest elements (in the softmax
dimension) of the matrix QK^t are going to give useful contributions. So for each query q in Q, we can consider only
the keys k in K that are close to q. A hash function is used to determine if q and k are close. The attention mask is
modified to mask the current token (except at the first position), because it will give a query and a key equal (so
very similar to each other). Since the hash can be a bit random, several hash functions are used in practice
(determined by a n_rounds parameter) and then are averaged together.

## Local attention

[Longformer](model_doc/longformer) uses local attention: often, the local context (e.g., what are the two tokens to the
left and right?) is enough to take action for a given token. Also, by stacking attention layers that have a small
window, the last layer will have a receptive field of more than just the tokens in the window, allowing them to build a
representation of the whole sentence.

Some preselected input tokens are also given global attention: for those few tokens, the attention matrix can access
all tokens and this process is symmetric: all other tokens have access to those specific tokens (on top of the ones in
their local window). This is shown in Figure 2d of the paper, see below for a sample attention mask:

<div class="flex justify-center">
    <img scale="50 %" align="center" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/local_attention_mask.png"/>
</div>

Using those attention matrices with less parameters then allows the model to have inputs having a bigger sequence
length.

## Other tricks

### Axial positional encodings

[Reformer](model_doc/reformer) uses axial positional encodings: in traditional transformer models, the positional encoding
E is a matrix of size \\(l\\) by \\(d\\), \\(l\\) being the sequence length and \\(d\\) the dimension of the
hidden state. If you have very long texts, this matrix can be huge and take way too much space on the GPU. To alleviate
that, axial positional encodings consist of factorizing that big matrix E in two smaller matrices E1 and E2, with
dimensions \\(l_{1} \times d_{1}\\) and \\(l_{2} \times d_{2}\\), such that \\(l_{1} \times l_{2} = l\\) and
\\(d_{1} + d_{2} = d\\) (with the product for the lengths, this ends up being way smaller). The embedding for time
step \\(j\\) in E is obtained by concatenating the embeddings for timestep \\(j \% l1\\) in E1 and \\(j // l1\\)
in E2.


key: _node_content
string_value:
{"id_": "267b417b-a993-4662-84bc-14386b5bab1c", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/fast_tokenizers", "title": "Use tokenizers from \ud83e\udd17 Tokenizers", "tokens": 649, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "738c43a2-7a09-4c2a-9d30-d8aee499bf36", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/fast_tokenizers", "title": "Use tokenizers from \ud83e\udd17 Tokenizers", "tokens": 649, "retrieve_doc": true, "source": "transformers"}, "hash": "32073cdb09c332f609d301597e53983bf339a3a0ce0bae9031cabbf2fb868608", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 2125, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# Use tokenizers from 🤗 Tokenizers

The [`PreTrainedTokenizerFast`] depends on the [🤗 Tokenizers](https://huggingface.co/docs/tokenizers) library. The tokenizers obtained from the 🤗 Tokenizers library can be
loaded very simply into 🤗 Transformers.

Before getting in the specifics, let's first start by creating a dummy tokenizer in a few lines:

```python
>>> from tokenizers import Tokenizer
>>> from tokenizers.models import BPE
>>> from tokenizers.trainers import BpeTrainer
>>> from tokenizers.pre_tokenizers import Whitespace

>>> tokenizer = Tokenizer(BPE(unk_token="[UNK]"))
>>> trainer = BpeTrainer(special_tokens=["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]"])

>>> tokenizer.pre_tokenizer = Whitespace()
>>> files = [...]
>>> tokenizer.train(files, trainer)
```

We now have a tokenizer trained on the files we defined. We can either continue using it in that runtime, or save it to
a JSON file for future re-use.

## Loading directly from the tokenizer object

Let's see how to leverage this tokenizer object in the 🤗 Transformers library. The
[`PreTrainedTokenizerFast`] class allows for easy instantiation, by accepting the instantiated
*tokenizer* object as an argument:

```python
>>> from transformers import PreTrainedTokenizerFast

>>> fast_tokenizer = PreTrainedTokenizerFast(tokenizer_object=tokenizer)
```

This object can now be used with all the methods shared by the 🤗 Transformers tokenizers! Head to [the tokenizer
page](main_classes/tokenizer) for more information.

## Loading from a JSON file

In order to load a tokenizer from a JSON file, let's first start by saving our tokenizer:

```python
>>> tokenizer.save("tokenizer.json")
```

The path to which we saved this file can be passed to the [`PreTrainedTokenizerFast`] initialization
method using the `tokenizer_file` parameter:

```python
>>> from transformers import PreTrainedTokenizerFast

>>> fast_tokenizer = PreTrainedTokenizerFast(tokenizer_file="tokenizer.json")
```

This object can now be used with all the methods shared by the 🤗 Transformers tokenizers! Head to [the tokenizer
page](main_classes/tokenizer) for more information.


key: _node_content
string_value:
{"id_": "9264c7e0-6d09-468c-ba43-5af0d9a982f7", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/big_models", "title": "Instantiate a big model", "tokens": 2428, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "10f02487-1864-41f9-b5f6-818aa791bbc8", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/big_models", "title": "Instantiate a big model", "tokens": 2428, "retrieve_doc": true, "source": "transformers"}, "hash": "8d9904392ea855d641436a43c66fad3091c67b2543cf997b03e3beee5894fa31", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "8f745796-10a5-4c79-bcf0-010d59f1b059", "node_type": "1", "metadata": {}, "hash": "307d834a2551189a814cdbd6d717b996c7187fb473ed33c102e3711946e8b00d", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 2956, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# Instantiate a big model

A barrier to accessing very large pretrained models is the amount of memory required. When loading a pretrained PyTorch model, you usually:

1. Create a model with random weights.
2. Load your pretrained weights.
3. Put those pretrained weights in the model.

The first two steps both require a full version of the model in memory and if the model weighs several GBs, you may not have enough memory for two copies of it. This problem is amplified in distributed training environments because each process loads a pretrained model and stores two copies in memory.

> [!TIP]
> The randomly created model is initialized with "empty" tensors, which take space in memory without filling it. The random values are whatever was in this chunk of memory at the time. To improve loading speed, the [`_fast_init`](https://github.com/huggingface/transformers/blob/c9f6e5e35156e068b227dd9b15521767f6afd4d2/src/transformers/modeling_utils.py#L2710) parameter is set to `True` by default to skip the random initialization for all weights that are correctly loaded.

This guide will show you how Transformers can help you load large pretrained models despite their memory requirements.

## Sharded checkpoints

From Transformers v4.18.0, a checkpoint larger than 10GB is automatically sharded by the [`~PreTrainedModel.save_pretrained`] method. It is split into several smaller partial checkpoints and creates an index file that maps parameter names to the files they're stored in.

The maximum shard size is controlled with the `max_shard_size` parameter, but by default it is 5GB, because it is easier to run on free-tier GPU instances without running out of memory.

For example, let's shard [BioMistral/BioMistral-7B](https://hf.co/BioMistral/BioMistral-7B).

```py
>>> with tempfile.TemporaryDirectory() as tmp_dir:
...     model.save_pretrained(tmp_dir, max_shard_size="5GB")
...     print(sorted(os.listdir(tmp_dir)))
['config.json', 'generation_config.json', 'model-00001-of-00006.safetensors', 'model-00002-of-00006.safetensors', 'model-00003-of-00006.safetensors', 'model-00004-of-00006.safetensors', 'model-00005-of-00006.safetensors', 'model-00006-of-00006.safetensors', 'model.safetensors.index.json']
```

The sharded checkpoint is reloaded with the [`~PreTrainedModel.from_pretrained`] method.

```py
>>> with tempfile.TemporaryDirectory() as tmp_dir:
...     model.save_pretrained(tmp_dir, max_shard_size="5GB")
...     new_model = AutoModel.from_pretrained(tmp_dir)
```

The main advantage of sharded checkpoints for big models is that each shard is loaded after the previous one, which caps the memory usage to only the model size and the largest shard size.

You could also directly load a sharded checkpoint inside a model without the [`~PreTrainedModel.from_pretrained`] method (similar to PyTorch's `load_state_dict()` method for a full checkpoint). In this case, use the [`~modeling_utils.load_sharded_checkpoint`] method.


key: _node_content
string_value:
{"id_": "8f745796-10a5-4c79-bcf0-010d59f1b059", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/big_models", "title": "Instantiate a big model", "tokens": 2428, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "10f02487-1864-41f9-b5f6-818aa791bbc8", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/big_models", "title": "Instantiate a big model", "tokens": 2428, "retrieve_doc": true, "source": "transformers"}, "hash": "8d9904392ea855d641436a43c66fad3091c67b2543cf997b03e3beee5894fa31", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "9264c7e0-6d09-468c-ba43-5af0d9a982f7", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/big_models", "title": "Instantiate a big model", "tokens": 2428, "retrieve_doc": true, "source": "transformers"}, "hash": "22a9f5907fc411a57b3d242e019c98a899ac357a8ca84dbd03994cfbfda78096", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "34211feb-17b4-4dee-a867-43f3cbf807e5", "node_type": "1", "metadata": {}, "hash": "3a83534e416ea52104dd70d7214752cef93e554a1527984be51ca4347cdd1d23", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 1494, "end_char_idx": 4410, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
The maximum shard size is controlled with the `max_shard_size` parameter, but by default it is 5GB, because it is easier to run on free-tier GPU instances without running out of memory.

For example, let's shard [BioMistral/BioMistral-7B](https://hf.co/BioMistral/BioMistral-7B).

```py
>>> with tempfile.TemporaryDirectory() as tmp_dir:
...     model.save_pretrained(tmp_dir, max_shard_size="5GB")
...     print(sorted(os.listdir(tmp_dir)))
['config.json', 'generation_config.json', 'model-00001-of-00006.safetensors', 'model-00002-of-00006.safetensors', 'model-00003-of-00006.safetensors', 'model-00004-of-00006.safetensors', 'model-00005-of-00006.safetensors', 'model-00006-of-00006.safetensors', 'model.safetensors.index.json']
```

The sharded checkpoint is reloaded with the [`~PreTrainedModel.from_pretrained`] method.

```py
>>> with tempfile.TemporaryDirectory() as tmp_dir:
...     model.save_pretrained(tmp_dir, max_shard_size="5GB")
...     new_model = AutoModel.from_pretrained(tmp_dir)
```

The main advantage of sharded checkpoints for big models is that each shard is loaded after the previous one, which caps the memory usage to only the model size and the largest shard size.

You could also directly load a sharded checkpoint inside a model without the [`~PreTrainedModel.from_pretrained`] method (similar to PyTorch's `load_state_dict()` method for a full checkpoint). In this case, use the [`~modeling_utils.load_sharded_checkpoint`] method.

```py
>>> from transformers.modeling_utils import load_sharded_checkpoint

>>> with tempfile.TemporaryDirectory() as tmp_dir:
...     model.save_pretrained(tmp_dir, max_shard_size="5GB")
...     load_sharded_checkpoint(model, tmp_dir)
```

### Shard metadata

The index file determines which keys are in the checkpoint and where the corresponding weights are stored. This file is loaded like any other JSON file and you can get a dictionary from it.

```py
>>> import json

>>> with tempfile.TemporaryDirectory() as tmp_dir:
...     model.save_pretrained(tmp_dir, max_shard_size="5GB")
...     with open(os.path.join(tmp_dir, "model.safetensors.index.json"), "r") as f:
...         index = json.load(f)

>>> print(index.keys())
dict_keys(['metadata', 'weight_map'])
```

The `metadata` key provides the total model size.

```py
>>> index["metadata"]
{'total_size': 28966928384}
```

The `weight_map` key maps each parameter name (typically `state_dict` in a PyTorch model) to the shard it's stored in.

```py
>>> index["weight_map"]
{'lm_head.weight': 'model-00006-of-00006.safetensors',
 'model.embed_tokens.weight': 'model-00001-of-00006.safetensors',
 'model.layers.0.input_layernorm.weight': 'model-00001-of-00006.safetensors',
 'model.layers.0.mlp.down_proj.weight': 'model-00001-of-00006.safetensors',
 ...
}
```

## Accelerate's Big Model Inference

> [!TIP]
> Make sure you have Accelerate v0.9.0 or later and PyTorch v1.9.0 or later installed.


key: _node_content
string_value:
{"id_": "34211feb-17b4-4dee-a867-43f3cbf807e5", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/big_models", "title": "Instantiate a big model", "tokens": 2428, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "10f02487-1864-41f9-b5f6-818aa791bbc8", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/big_models", "title": "Instantiate a big model", "tokens": 2428, "retrieve_doc": true, "source": "transformers"}, "hash": "8d9904392ea855d641436a43c66fad3091c67b2543cf997b03e3beee5894fa31", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "8f745796-10a5-4c79-bcf0-010d59f1b059", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/big_models", "title": "Instantiate a big model", "tokens": 2428, "retrieve_doc": true, "source": "transformers"}, "hash": "48589f229627e9e3811a3f518270a0f07aa898a46be83288517016da0e7328ed", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "0a559470-7f75-4483-8eaf-acd5158fa436", "node_type": "1", "metadata": {}, "hash": "33428185ec02dabeda4bcdc84534e35aa8e4d0b97ff1099c0d9b757f8f1890c9", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 2958, "end_char_idx": 5778, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```py
>>> from transformers.modeling_utils import load_sharded_checkpoint

>>> with tempfile.TemporaryDirectory() as tmp_dir:
...     model.save_pretrained(tmp_dir, max_shard_size="5GB")
...     load_sharded_checkpoint(model, tmp_dir)
```

### Shard metadata

The index file determines which keys are in the checkpoint and where the corresponding weights are stored. This file is loaded like any other JSON file and you can get a dictionary from it.

```py
>>> import json

>>> with tempfile.TemporaryDirectory() as tmp_dir:
...     model.save_pretrained(tmp_dir, max_shard_size="5GB")
...     with open(os.path.join(tmp_dir, "model.safetensors.index.json"), "r") as f:
...         index = json.load(f)

>>> print(index.keys())
dict_keys(['metadata', 'weight_map'])
```

The `metadata` key provides the total model size.

```py
>>> index["metadata"]
{'total_size': 28966928384}
```

The `weight_map` key maps each parameter name (typically `state_dict` in a PyTorch model) to the shard it's stored in.

```py
>>> index["weight_map"]
{'lm_head.weight': 'model-00006-of-00006.safetensors',
 'model.embed_tokens.weight': 'model-00001-of-00006.safetensors',
 'model.layers.0.input_layernorm.weight': 'model-00001-of-00006.safetensors',
 'model.layers.0.mlp.down_proj.weight': 'model-00001-of-00006.safetensors',
 ...
}
```

## Accelerate's Big Model Inference

> [!TIP]
> Make sure you have Accelerate v0.9.0 or later and PyTorch v1.9.0 or later installed.

From Transformers v4.20.0, the [`~PreTrainedModel.from_pretrained`] method is supercharged with Accelerate's [Big Model Inference](https://hf.co/docs/accelerate/usage_guides/big_modeling) feature to efficiently handle really big models! Big Model Inference creates a *model skeleton* on PyTorch's [**meta**](https://pytorch.org/docs/main/meta.html) device. The randomly initialized parameters are only created when the pretrained weights are loaded. This way, you aren't keeping two copies of the model in memory at the same time (one for the randomly initialized model and one for the pretrained weights), and the maximum memory consumed is only the full model size.

To enable Big Model Inference in Transformers, set `low_cpu_mem_usage=True` in the [`~PreTrainedModel.from_pretrained`] method.

```py
from transformers import AutoModelForCausalLM

gemma = AutoModelForCausalLM.from_pretrained("google/gemma-7b", low_cpu_mem_usage=True)
```

Accelerate automatically dispatches the model weights across all available devices, starting with the fastest device (GPU) first and then offloading to the slower devices (CPU and even hard drive). This is enabled by setting `device_map="auto"` in the [`~PreTrainedModel.from_pretrained`] method. When you pass the `device_map` parameter, `low_cpu_mem_usage` is automatically set to `True` so you don't need to specify it.


key: _node_content
string_value:
{"id_": "0a559470-7f75-4483-8eaf-acd5158fa436", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/big_models", "title": "Instantiate a big model", "tokens": 2428, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "10f02487-1864-41f9-b5f6-818aa791bbc8", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/big_models", "title": "Instantiate a big model", "tokens": 2428, "retrieve_doc": true, "source": "transformers"}, "hash": "8d9904392ea855d641436a43c66fad3091c67b2543cf997b03e3beee5894fa31", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "34211feb-17b4-4dee-a867-43f3cbf807e5", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/big_models", "title": "Instantiate a big model", "tokens": 2428, "retrieve_doc": true, "source": "transformers"}, "hash": "19eebd188b7e991ad0c0f9d954a9538c01d2e4c821bb475f94653c88f6f05ab9", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "31304479-5185-48d3-8395-d3591f147ff5", "node_type": "1", "metadata": {}, "hash": "5da71eacd2b6a2616650ae373dac289f24dc94f7af3d268e1be91c94d3279eb5", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 4412, "end_char_idx": 6506, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
From Transformers v4.20.0, the [`~PreTrainedModel.from_pretrained`] method is supercharged with Accelerate's [Big Model Inference](https://hf.co/docs/accelerate/usage_guides/big_modeling) feature to efficiently handle really big models! Big Model Inference creates a *model skeleton* on PyTorch's [**meta**](https://pytorch.org/docs/main/meta.html) device. The randomly initialized parameters are only created when the pretrained weights are loaded. This way, you aren't keeping two copies of the model in memory at the same time (one for the randomly initialized model and one for the pretrained weights), and the maximum memory consumed is only the full model size.

To enable Big Model Inference in Transformers, set `low_cpu_mem_usage=True` in the [`~PreTrainedModel.from_pretrained`] method.

```py
from transformers import AutoModelForCausalLM

gemma = AutoModelForCausalLM.from_pretrained("google/gemma-7b", low_cpu_mem_usage=True)
```

Accelerate automatically dispatches the model weights across all available devices, starting with the fastest device (GPU) first and then offloading to the slower devices (CPU and even hard drive). This is enabled by setting `device_map="auto"` in the [`~PreTrainedModel.from_pretrained`] method. When you pass the `device_map` parameter, `low_cpu_mem_usage` is automatically set to `True` so you don't need to specify it.

```py
from transformers import AutoModelForCausalLM

# these loading methods are equivalent
gemma = AutoModelForCausalLM.from_pretrained("google/gemma-7b", device_map="auto")
gemma = AutoModelForCausalLM.from_pretrained("google/gemma-7b", device_map="auto", low_cpu_mem_usage=True)
```

You can also write your own `device_map` by mapping each layer to a device. It should map all model parameters to a device, but you don't have to detail where all the submodules of a layer go if the entire layer is on the same device.

```python
device_map = {"model.layers.1": 0, "model.layers.14": 1, "model.layers.31": "cpu", "lm_head": "disk"}
```

Access `hf_device_map` attribute to see how Accelerate split the model across devices.


key: _node_content
string_value:
{"id_": "31304479-5185-48d3-8395-d3591f147ff5", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/big_models", "title": "Instantiate a big model", "tokens": 2428, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "10f02487-1864-41f9-b5f6-818aa791bbc8", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/big_models", "title": "Instantiate a big model", "tokens": 2428, "retrieve_doc": true, "source": "transformers"}, "hash": "8d9904392ea855d641436a43c66fad3091c67b2543cf997b03e3beee5894fa31", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "0a559470-7f75-4483-8eaf-acd5158fa436", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/big_models", "title": "Instantiate a big model", "tokens": 2428, "retrieve_doc": true, "source": "transformers"}, "hash": "ed2cdd7e290a6aa2ff78e7380cc943772fba81db34d44fbe304944844df3e195", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "17eec031-e2cf-46fb-b62b-60d1de755063", "node_type": "1", "metadata": {}, "hash": "a8288b8681e15a15a19a1909ab7e17ee67ae5d8f12a50bf84afe5d9cb4c21651", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 5081, "end_char_idx": 7740, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
To enable Big Model Inference in Transformers, set `low_cpu_mem_usage=True` in the [`~PreTrainedModel.from_pretrained`] method.

```py
from transformers import AutoModelForCausalLM

gemma = AutoModelForCausalLM.from_pretrained("google/gemma-7b", low_cpu_mem_usage=True)
```

Accelerate automatically dispatches the model weights across all available devices, starting with the fastest device (GPU) first and then offloading to the slower devices (CPU and even hard drive). This is enabled by setting `device_map="auto"` in the [`~PreTrainedModel.from_pretrained`] method. When you pass the `device_map` parameter, `low_cpu_mem_usage` is automatically set to `True` so you don't need to specify it.

```py
from transformers import AutoModelForCausalLM

# these loading methods are equivalent
gemma = AutoModelForCausalLM.from_pretrained("google/gemma-7b", device_map="auto")
gemma = AutoModelForCausalLM.from_pretrained("google/gemma-7b", device_map="auto", low_cpu_mem_usage=True)
```

You can also write your own `device_map` by mapping each layer to a device. It should map all model parameters to a device, but you don't have to detail where all the submodules of a layer go if the entire layer is on the same device.

```python
device_map = {"model.layers.1": 0, "model.layers.14": 1, "model.layers.31": "cpu", "lm_head": "disk"}
```

Access `hf_device_map` attribute to see how Accelerate split the model across devices.

```py
gemma.hf_device_map
```

```python out
{'model.embed_tokens': 0,
 'model.layers.0': 0,
 'model.layers.1': 0,
 'model.layers.2': 0,
 'model.layers.3': 0,
 'model.layers.4': 0,
 'model.layers.5': 0,
 'model.layers.6': 0,
 'model.layers.7': 0,
 'model.layers.8': 0,
 'model.layers.9': 0,
 'model.layers.10': 0,
 'model.layers.11': 0,
 'model.layers.12': 0,
 'model.layers.13': 0,
 'model.layers.14': 'cpu',
 'model.layers.15': 'cpu',
 'model.layers.16': 'cpu',
 'model.layers.17': 'cpu',
 'model.layers.18': 'cpu',
 'model.layers.19': 'cpu',
 'model.layers.20': 'cpu',
 'model.layers.21': 'cpu',
 'model.layers.22': 'cpu',
 'model.layers.23': 'cpu',
 'model.layers.24': 'cpu',
 'model.layers.25': 'cpu',
 'model.layers.26': 'cpu',
 'model.layers.27': 'cpu',
 'model.layers.28': 'cpu',
 'model.layers.29': 'cpu',
 'model.layers.30': 'cpu',
 'model.layers.31': 'cpu',
 'model.norm': 'cpu',
 'lm_head': 'cpu'}
```

## Model data type

PyTorch model weights are normally instantiated as torch.float32 and it can be an issue if you try to load a model as a different data type. For example, you'd need twice as much memory to load the weights in torch.float32 and then again to load them in your desired data type, like torch.float16.


key: _node_content
string_value:
{"id_": "17eec031-e2cf-46fb-b62b-60d1de755063", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/big_models", "title": "Instantiate a big model", "tokens": 2428, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "10f02487-1864-41f9-b5f6-818aa791bbc8", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/big_models", "title": "Instantiate a big model", "tokens": 2428, "retrieve_doc": true, "source": "transformers"}, "hash": "8d9904392ea855d641436a43c66fad3091c67b2543cf997b03e3beee5894fa31", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "31304479-5185-48d3-8395-d3591f147ff5", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/big_models", "title": "Instantiate a big model", "tokens": 2428, "retrieve_doc": true, "source": "transformers"}, "hash": "3d6fdc9576a13e90b25a43491ae4a3337ad2661c76e5844202948b585638c79e", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 6508, "end_char_idx": 8796, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```py
gemma.hf_device_map
```

```python out
{'model.embed_tokens': 0,
 'model.layers.0': 0,
 'model.layers.1': 0,
 'model.layers.2': 0,
 'model.layers.3': 0,
 'model.layers.4': 0,
 'model.layers.5': 0,
 'model.layers.6': 0,
 'model.layers.7': 0,
 'model.layers.8': 0,
 'model.layers.9': 0,
 'model.layers.10': 0,
 'model.layers.11': 0,
 'model.layers.12': 0,
 'model.layers.13': 0,
 'model.layers.14': 'cpu',
 'model.layers.15': 'cpu',
 'model.layers.16': 'cpu',
 'model.layers.17': 'cpu',
 'model.layers.18': 'cpu',
 'model.layers.19': 'cpu',
 'model.layers.20': 'cpu',
 'model.layers.21': 'cpu',
 'model.layers.22': 'cpu',
 'model.layers.23': 'cpu',
 'model.layers.24': 'cpu',
 'model.layers.25': 'cpu',
 'model.layers.26': 'cpu',
 'model.layers.27': 'cpu',
 'model.layers.28': 'cpu',
 'model.layers.29': 'cpu',
 'model.layers.30': 'cpu',
 'model.layers.31': 'cpu',
 'model.norm': 'cpu',
 'lm_head': 'cpu'}
```

## Model data type

PyTorch model weights are normally instantiated as torch.float32 and it can be an issue if you try to load a model as a different data type. For example, you'd need twice as much memory to load the weights in torch.float32 and then again to load them in your desired data type, like torch.float16.

> [!WARNING]
> Due to how PyTorch is designed, the `torch_dtype` parameter only supports floating data types.

To avoid wasting memory like this, explicitly set the `torch_dtype` parameter to the desired data type or set `torch_dtype="auto"` to load the weights with the most optimal memory pattern (the data type is automatically derived from the model weights).

<hfoptions id="dtype">
<hfoption id="specific dtype">

```py
from transformers import AutoModelForCausalLM

gemma = AutoModelForCausalLM.from_pretrained("google/gemma-7b", torch_dtype=torch.float16)
```

</hfoption>
<hfoption id="auto dtype">

```py
from transformers import AutoModelForCausalLM

gemma = AutoModelForCausalLM.from_pretrained("google/gemma-7b", torch_dtype="auto")
```

</hfoption>
</hfoptions>

You can also set the data type to use for models instantiated from scratch.

```python
import torch
from transformers import AutoConfig, AutoModel

my_config = AutoConfig.from_pretrained("google/gemma-2b", torch_dtype=torch.float16)
model = AutoModel.from_config(my_config)
```


key: _node_content
string_value:
{"id_": "61e72a16-0e60-4bc1-9c51-1b566904b648", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/perf_train_cpu", "title": "Efficient Training on CPU", "tokens": 1030, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "83e838eb-4ed0-48c1-8501-ad259f18be43", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/perf_train_cpu", "title": "Efficient Training on CPU", "tokens": 1030, "retrieve_doc": true, "source": "transformers"}, "hash": "9cf35ef5d0afabfdc2fa3de693087687937c1bc83ce588496b4164d3d9eacf44", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "c83e1978-6631-4da0-b37d-0e899232cf60", "node_type": "1", "metadata": {}, "hash": "d7817ae648cddb6ceaf938eb071ecf9a363d0b06bb37ba59678f7b7702b75219", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 2416, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# Efficient Training on CPU

This guide focuses on training large models efficiently on CPU.

## Mixed precision with IPEX
Mixed precision uses single (fp32) and half-precision (bf16/fp16) data types in a model to accelerate training or inference while still preserving much of the single-precision accuracy. Modern CPUs such as 3rd and 4th Gen Intel® Xeon® Scalable processors natively support bf16, so you should get more performance out of the box by enabling mixed precision training with bf16.

To further maximize training performance, you can use Intel® Extension for PyTorch (IPEX), which is a library built on PyTorch and adds additional CPU instruction level architecture (ISA) level support such as Intel® Advanced Vector Extensions 512 Vector Neural Network Instructions (Intel® AVX512-VNNI), and Intel® Advanced Matrix Extensions (Intel® AMX) for an extra performance boost on Intel CPUs. However, CPUs with only AVX2 (e.g., AMD or older Intel CPUs) are not guaranteed to have better performance under IPEX.

Auto Mixed Precision (AMP) for CPU backends has been enabled since PyTorch 1.10. AMP support for bf16 on CPUs and bf16 operator optimization is also supported in IPEX and partially upstreamed to the main PyTorch branch. You can get better performance and user experience with IPEX AMP.

Check more detailed information for [Auto Mixed Precision](https://intel.github.io/intel-extension-for-pytorch/cpu/latest/tutorials/features/amp.html).

### IPEX installation:

IPEX release is following PyTorch, to install via pip:

| PyTorch Version   | IPEX version   |
| :---------------: | :----------:   |
| 2.1.x             |  2.1.100+cpu   |
| 2.0.x             |  2.0.100+cpu   |
| 1.13              |  1.13.0+cpu    |
| 1.12              |  1.12.300+cpu  |

Please run `pip list | grep torch` to get your `pytorch_version`, so you can get the `IPEX version_name`.
```bash
pip install intel_extension_for_pytorch==<version_name> -f https://developer.intel.com/ipex-whl-stable-cpu
```
You can check the latest versions in [ipex-whl-stable-cpu](https://developer.intel.com/ipex-whl-stable-cpu) if needed.

Check more approaches for [IPEX installation](https://intel.github.io/intel-extension-for-pytorch/cpu/latest/tutorials/installation.html).

### Usage in Trainer
To enable auto mixed precision with IPEX in Trainer, users should add `use_ipex`, `bf16` and `no_cuda` in training command arguments.


key: _node_content
string_value:
{"id_": "c83e1978-6631-4da0-b37d-0e899232cf60", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/perf_train_cpu", "title": "Efficient Training on CPU", "tokens": 1030, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "83e838eb-4ed0-48c1-8501-ad259f18be43", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/perf_train_cpu", "title": "Efficient Training on CPU", "tokens": 1030, "retrieve_doc": true, "source": "transformers"}, "hash": "9cf35ef5d0afabfdc2fa3de693087687937c1bc83ce588496b4164d3d9eacf44", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "61e72a16-0e60-4bc1-9c51-1b566904b648", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/perf_train_cpu", "title": "Efficient Training on CPU", "tokens": 1030, "retrieve_doc": true, "source": "transformers"}, "hash": "8aea4a1488679e7f887a1bcf49c8790691cb526bed67f05da813f7f2de6be12e", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 1022, "end_char_idx": 3388, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Auto Mixed Precision (AMP) for CPU backends has been enabled since PyTorch 1.10. AMP support for bf16 on CPUs and bf16 operator optimization is also supported in IPEX and partially upstreamed to the main PyTorch branch. You can get better performance and user experience with IPEX AMP.

Check more detailed information for [Auto Mixed Precision](https://intel.github.io/intel-extension-for-pytorch/cpu/latest/tutorials/features/amp.html).

### IPEX installation:

IPEX release is following PyTorch, to install via pip:

| PyTorch Version   | IPEX version   |
| :---------------: | :----------:   |
| 2.1.x             |  2.1.100+cpu   |
| 2.0.x             |  2.0.100+cpu   |
| 1.13              |  1.13.0+cpu    |
| 1.12              |  1.12.300+cpu  |

Please run `pip list | grep torch` to get your `pytorch_version`, so you can get the `IPEX version_name`.
```bash
pip install intel_extension_for_pytorch==<version_name> -f https://developer.intel.com/ipex-whl-stable-cpu
```
You can check the latest versions in [ipex-whl-stable-cpu](https://developer.intel.com/ipex-whl-stable-cpu) if needed.

Check more approaches for [IPEX installation](https://intel.github.io/intel-extension-for-pytorch/cpu/latest/tutorials/installation.html).

### Usage in Trainer
To enable auto mixed precision with IPEX in Trainer, users should add `use_ipex`, `bf16` and `no_cuda` in training command arguments.

Take an example of the use cases on [Transformers question-answering](https://github.com/huggingface/transformers/tree/main/examples/pytorch/question-answering)

- Training with IPEX using BF16 auto mixed precision on CPU:
<pre> python run_qa.py \
--model_name_or_path google-bert/bert-base-uncased \
--dataset_name squad \
--do_train \
--do_eval \
--per_device_train_batch_size 12 \
--learning_rate 3e-5 \
--num_train_epochs 2 \
--max_seq_length 384 \
--doc_stride 128 \
--output_dir /tmp/debug_squad/ \
<b>--use_ipex</b> \
<b>--bf16</b> \
<b>--use_cpu</b></pre> 

If you want to enable `use_ipex` and `bf16` in your script, add these parameters to `TrainingArguments` like this:
```diff
training_args = TrainingArguments(
    output_dir=args.output_path,
+   bf16=True,
+   use_ipex=True,
+   use_cpu=True,
    **kwargs
)
```

### Practice example

Blog: [Accelerating PyTorch Transformers with Intel Sapphire Rapids](https://huggingface.co/blog/intel-sapphire-rapids)


key: _node_content
string_value:
{"id_": "e91e6d86-7506-4c36-9881-b2e58ae53de6", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/model_memory_anatomy", "title": "Model training anatomy", "tokens": 2516, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "5c302e90-7ccc-4394-ae4b-e45a8a5f2785", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/model_memory_anatomy", "title": "Model training anatomy", "tokens": 2516, "retrieve_doc": true, "source": "transformers"}, "hash": "13c1d1df5bd4f7d976e9a09a204c3ffea3813736bd49565008bda2dd6f1fc03d", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "559c77c7-bef3-4470-bf35-e21753f5b5c4", "node_type": "1", "metadata": {}, "hash": "a845e3149d86d83647d66043ab64e895bc7b5431910b689f480a7f7a2811a68e", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 3120, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
<!---
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 in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->

# Model training anatomy

To understand performance optimization techniques that one can apply to improve efficiency of model training 
speed and memory utilization, it's helpful to get familiar with how GPU is utilized during training, and how compute 
intensity varies depending on an operation performed.

Let's start by exploring a motivating example of GPU utilization and the training run of a model. For the demonstration, 
we'll need to install a few libraries: 

```bash
pip install transformers datasets accelerate nvidia-ml-py3
```

The `nvidia-ml-py3` library allows us to monitor the memory usage of the models from within Python. You might be familiar 
with the `nvidia-smi` command in the terminal - this library allows to access the same information in Python directly.

Then, we create some dummy data: random token IDs between 100 and 30000 and binary labels for a classifier. 
In total, we get 512 sequences each with length 512 and store them in a [`~datasets.Dataset`] with PyTorch format.


```py
>>> import numpy as np
>>> from datasets import Dataset


>>> seq_len, dataset_size = 512, 512
>>> dummy_data = {
...     "input_ids": np.random.randint(100, 30000, (dataset_size, seq_len)),
...     "labels": np.random.randint(0, 1, (dataset_size)),
... }
>>> ds = Dataset.from_dict(dummy_data)
>>> ds.set_format("pt")
```

To print summary statistics for the GPU utilization and the training run with the [`Trainer`] we define two helper functions:

```py
>>> from pynvml import *


>>> def print_gpu_utilization():
...     nvmlInit()
...     handle = nvmlDeviceGetHandleByIndex(0)
...     info = nvmlDeviceGetMemoryInfo(handle)
...     print(f"GPU memory occupied: {info.used//1024**2} MB.")


>>> def print_summary(result):
...     print(f"Time: {result.metrics['train_runtime']:.2f}")
...     print(f"Samples/second: {result.metrics['train_samples_per_second']:.2f}")
...     print_gpu_utilization()
```

Let's verify that we start with a free GPU memory:

```py
>>> print_gpu_utilization()
GPU memory occupied: 0 MB.
```

That looks good: the GPU memory is not occupied as we would expect before we load any models. If that's not the case on 
your machine make sure to stop all processes that are using GPU memory. However, not all free GPU memory can be used by 
the user. When a model is loaded to the GPU the kernels are also loaded, which can take up 1-2GB of memory. To see how 
much it is we load a tiny tensor into the GPU which triggers the kernels to be loaded as well.

```py
>>> import torch


key: _node_content
string_value:
{"id_": "559c77c7-bef3-4470-bf35-e21753f5b5c4", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/model_memory_anatomy", "title": "Model training anatomy", "tokens": 2516, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "5c302e90-7ccc-4394-ae4b-e45a8a5f2785", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/model_memory_anatomy", "title": "Model training anatomy", "tokens": 2516, "retrieve_doc": true, "source": "transformers"}, "hash": "13c1d1df5bd4f7d976e9a09a204c3ffea3813736bd49565008bda2dd6f1fc03d", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "e91e6d86-7506-4c36-9881-b2e58ae53de6", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/model_memory_anatomy", "title": "Model training anatomy", "tokens": 2516, "retrieve_doc": true, "source": "transformers"}, "hash": "70d9b744470facac5683ba1b9c8b619954496285fb913d824bc3401aa314ea8c", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "3acb1b8d-9a71-4ad1-825a-6c0ced816492", "node_type": "1", "metadata": {}, "hash": "23ced0273f9b27cf845b683a4943362524ccd82cc5bd4ee3b70ac79b0905b1f0", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 1607, "end_char_idx": 4120, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```py
>>> import numpy as np
>>> from datasets import Dataset


>>> seq_len, dataset_size = 512, 512
>>> dummy_data = {
...     "input_ids": np.random.randint(100, 30000, (dataset_size, seq_len)),
...     "labels": np.random.randint(0, 1, (dataset_size)),
... }
>>> ds = Dataset.from_dict(dummy_data)
>>> ds.set_format("pt")
```

To print summary statistics for the GPU utilization and the training run with the [`Trainer`] we define two helper functions:

```py
>>> from pynvml import *


>>> def print_gpu_utilization():
...     nvmlInit()
...     handle = nvmlDeviceGetHandleByIndex(0)
...     info = nvmlDeviceGetMemoryInfo(handle)
...     print(f"GPU memory occupied: {info.used//1024**2} MB.")


>>> def print_summary(result):
...     print(f"Time: {result.metrics['train_runtime']:.2f}")
...     print(f"Samples/second: {result.metrics['train_samples_per_second']:.2f}")
...     print_gpu_utilization()
```

Let's verify that we start with a free GPU memory:

```py
>>> print_gpu_utilization()
GPU memory occupied: 0 MB.
```

That looks good: the GPU memory is not occupied as we would expect before we load any models. If that's not the case on 
your machine make sure to stop all processes that are using GPU memory. However, not all free GPU memory can be used by 
the user. When a model is loaded to the GPU the kernels are also loaded, which can take up 1-2GB of memory. To see how 
much it is we load a tiny tensor into the GPU which triggers the kernels to be loaded as well.

```py
>>> import torch


>>> torch.ones((1, 1)).to("cuda")
>>> print_gpu_utilization()
GPU memory occupied: 1343 MB.
```

We see that the kernels alone take up 1.3GB of GPU memory. Now let's see how much space the model uses.

## Load Model

First, we load the `google-bert/bert-large-uncased` model. We load the model weights directly to the GPU so that we can check 
how much space just the weights use.


```py
>>> from transformers import AutoModelForSequenceClassification


>>> model = AutoModelForSequenceClassification.from_pretrained("google-bert/bert-large-uncased").to("cuda")
>>> print_gpu_utilization()
GPU memory occupied: 2631 MB.
```

We can see that the model weights alone take up 1.3 GB of GPU memory. The exact number depends on the specific 
GPU you are using. Note that on newer GPUs a model can sometimes take up more space since the weights are loaded in an 
optimized fashion that speeds up the usage of the model. Now we can also quickly check if we get the same result 
as with `nvidia-smi` CLI:


key: _node_content
string_value:
{"id_": "3acb1b8d-9a71-4ad1-825a-6c0ced816492", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/model_memory_anatomy", "title": "Model training anatomy", "tokens": 2516, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "5c302e90-7ccc-4394-ae4b-e45a8a5f2785", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/model_memory_anatomy", "title": "Model training anatomy", "tokens": 2516, "retrieve_doc": true, "source": "transformers"}, "hash": "13c1d1df5bd4f7d976e9a09a204c3ffea3813736bd49565008bda2dd6f1fc03d", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "559c77c7-bef3-4470-bf35-e21753f5b5c4", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/model_memory_anatomy", "title": "Model training anatomy", "tokens": 2516, "retrieve_doc": true, "source": "transformers"}, "hash": "eb0495ecb28a854c5d1f26501604f3769baea895ce5f629b13fde0b62058607c", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "338acab8-60cd-457d-bc01-185581232dd6", "node_type": "1", "metadata": {}, "hash": "1566cacb2f23c92f1dfe7fbc0bf6ef2aa26ed03b0885c23d2bfbf941e4e279d4", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 3123, "end_char_idx": 6477, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
>>> torch.ones((1, 1)).to("cuda")
>>> print_gpu_utilization()
GPU memory occupied: 1343 MB.
```

We see that the kernels alone take up 1.3GB of GPU memory. Now let's see how much space the model uses.

## Load Model

First, we load the `google-bert/bert-large-uncased` model. We load the model weights directly to the GPU so that we can check 
how much space just the weights use.


```py
>>> from transformers import AutoModelForSequenceClassification


>>> model = AutoModelForSequenceClassification.from_pretrained("google-bert/bert-large-uncased").to("cuda")
>>> print_gpu_utilization()
GPU memory occupied: 2631 MB.
```

We can see that the model weights alone take up 1.3 GB of GPU memory. The exact number depends on the specific 
GPU you are using. Note that on newer GPUs a model can sometimes take up more space since the weights are loaded in an 
optimized fashion that speeds up the usage of the model. Now we can also quickly check if we get the same result 
as with `nvidia-smi` CLI:


```bash
nvidia-smi
```

```bash
Tue Jan 11 08:58:05 2022
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 460.91.03    Driver Version: 460.91.03    CUDA Version: 11.2     |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|                               |                      |               MIG M. |
|===============================+======================+======================|
|   0  Tesla V100-SXM2...  On   | 00000000:00:04.0 Off |                    0 |
| N/A   37C    P0    39W / 300W |   2631MiB / 16160MiB |      0%      Default |
|                               |                      |                  N/A |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                                  |
|  GPU   GI   CI        PID   Type   Process name                  GPU Memory |
|        ID   ID                                                   Usage      |
|=============================================================================|
|    0   N/A  N/A      3721      C   ...nvs/codeparrot/bin/python     2629MiB |
+-----------------------------------------------------------------------------+
```

We get the same number as before and you can also see that we are using a V100 GPU with 16GB of memory. So now we can 
start training the model and see how the GPU memory consumption changes. First, we set up a few standard training 
arguments:

```py
default_args = {
    "output_dir": "tmp",
    "eval_strategy": "steps",
    "num_train_epochs": 1,
    "log_level": "error",
    "report_to": "none",
}
```

<Tip>

 If you plan to run multiple experiments, in order to properly clear the memory between experiments, restart the Python 
 kernel between experiments.

</Tip>

## Memory utilization at vanilla training

Let's use the [`Trainer`] and train the model without using any GPU performance optimization techniques and a batch size of 4:

```py
>>> from transformers import TrainingArguments, Trainer, logging

>>> logging.set_verbosity_error()


key: _node_content
string_value:
{"id_": "338acab8-60cd-457d-bc01-185581232dd6", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/model_memory_anatomy", "title": "Model training anatomy", "tokens": 2516, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "5c302e90-7ccc-4394-ae4b-e45a8a5f2785", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/model_memory_anatomy", "title": "Model training anatomy", "tokens": 2516, "retrieve_doc": true, "source": "transformers"}, "hash": "13c1d1df5bd4f7d976e9a09a204c3ffea3813736bd49565008bda2dd6f1fc03d", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "3acb1b8d-9a71-4ad1-825a-6c0ced816492", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/model_memory_anatomy", "title": "Model training anatomy", "tokens": 2516, "retrieve_doc": true, "source": "transformers"}, "hash": "794a406bf0cd4f83901fcce966b84bd322ceca9b1d8495650652ee717530b3f7", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "178a5c53-2265-477f-84d6-53cc417e6127", "node_type": "1", "metadata": {}, "hash": "ce3bd0a4349584d623b0611e962a92bb7ab63b06c0f5212df274e862e9a4bcaf", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 6480, "end_char_idx": 8220, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
>>> training_args = TrainingArguments(per_device_train_batch_size=4, **default_args)
>>> trainer = Trainer(model=model, args=training_args, train_dataset=ds)
>>> result = trainer.train()
>>> print_summary(result)
```

```
Time: 57.82
Samples/second: 8.86
GPU memory occupied: 14949 MB.
```

We see that already a relatively small batch size almost fills up our GPU's entire memory. However, a larger batch size 
can often result in faster model convergence or better end performance. So ideally we want to tune the batch size to our
model's needs and not to the GPU limitations. What's interesting is that we use much more memory than the size of the model. 
To understand a bit better why this is the case let's have a look at a model's operations and memory needs.

## Anatomy of Model's Operations

Transformers architecture includes 3 main groups of operations grouped below by compute-intensity.

1. **Tensor Contractions**

    Linear layers and components of Multi-Head Attention all do batched **matrix-matrix multiplications**. These operations are the most compute-intensive part of training a transformer.

2. **Statistical Normalizations**

    Softmax and layer normalization are less compute-intensive than tensor contractions, and involve one or more **reduction operations**, the result of which is then applied via a map.

3. **Element-wise Operators**

    These are the remaining operators: **biases, dropout, activations, and residual connections**. These are the least compute-intensive operations.

This knowledge can be helpful to know when analyzing performance bottlenecks.

This summary is derived from [Data Movement Is All You Need: A Case Study on Optimizing Transformers 2020](https://arxiv.org/abs/2007.00072)


key: _node_content
string_value:
{"id_": "178a5c53-2265-477f-84d6-53cc417e6127", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/model_memory_anatomy", "title": "Model training anatomy", "tokens": 2516, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "5c302e90-7ccc-4394-ae4b-e45a8a5f2785", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/model_memory_anatomy", "title": "Model training anatomy", "tokens": 2516, "retrieve_doc": true, "source": "transformers"}, "hash": "13c1d1df5bd4f7d976e9a09a204c3ffea3813736bd49565008bda2dd6f1fc03d", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "338acab8-60cd-457d-bc01-185581232dd6", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/model_memory_anatomy", "title": "Model training anatomy", "tokens": 2516, "retrieve_doc": true, "source": "transformers"}, "hash": "0829a9f4370bdd0facadd507bdc0b91bc5faa1915e6ad1c4abf2a1e636f8c5ad", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 6480, "end_char_idx": 11390, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
>>> training_args = TrainingArguments(per_device_train_batch_size=4, **default_args)
>>> trainer = Trainer(model=model, args=training_args, train_dataset=ds)
>>> result = trainer.train()
>>> print_summary(result)
```

```
Time: 57.82
Samples/second: 8.86
GPU memory occupied: 14949 MB.
```

We see that already a relatively small batch size almost fills up our GPU's entire memory. However, a larger batch size 
can often result in faster model convergence or better end performance. So ideally we want to tune the batch size to our
model's needs and not to the GPU limitations. What's interesting is that we use much more memory than the size of the model. 
To understand a bit better why this is the case let's have a look at a model's operations and memory needs.

## Anatomy of Model's Operations

Transformers architecture includes 3 main groups of operations grouped below by compute-intensity.

1. **Tensor Contractions**

    Linear layers and components of Multi-Head Attention all do batched **matrix-matrix multiplications**. These operations are the most compute-intensive part of training a transformer.

2. **Statistical Normalizations**

    Softmax and layer normalization are less compute-intensive than tensor contractions, and involve one or more **reduction operations**, the result of which is then applied via a map.

3. **Element-wise Operators**

    These are the remaining operators: **biases, dropout, activations, and residual connections**. These are the least compute-intensive operations.

This knowledge can be helpful to know when analyzing performance bottlenecks.

This summary is derived from [Data Movement Is All You Need: A Case Study on Optimizing Transformers 2020](https://arxiv.org/abs/2007.00072)


## Anatomy of Model's Memory

We've seen that training the model uses much more memory than just putting the model on the GPU. This is because there 
are many components during training that use GPU memory. The components on GPU memory are the following:

1. model weights
2. optimizer states
3. gradients
4. forward activations saved for gradient computation
5. temporary buffers
6. functionality-specific memory

A typical model trained in mixed precision with AdamW requires 18 bytes per model parameter plus activation memory. For 
inference there are no optimizer states and gradients, so we can subtract those. And thus we end up with 6 bytes per 
model parameter for mixed precision inference, plus activation memory.

Let's look at the details.

**Model Weights:**

- 4 bytes * number of parameters for fp32 training
- 6 bytes * number of parameters for mixed precision training (maintains a model in fp32 and one in fp16 in memory)

**Optimizer States:**

- 8 bytes * number of parameters for normal AdamW (maintains 2 states)
- 2 bytes * number of parameters for 8-bit AdamW optimizers like [bitsandbytes](https://github.com/TimDettmers/bitsandbytes)
- 4 bytes * number of parameters for optimizers like SGD with momentum (maintains only 1 state)

**Gradients**

- 4 bytes * number of parameters for either fp32 or mixed precision training (gradients are always kept in fp32)

**Forward Activations**

- size depends on many factors, the key ones being sequence length, hidden size and batch size.

There are the input and output that are being passed and returned by the forward and the backward functions and the 
forward activations saved for gradient computation.

**Temporary Memory**

Additionally, there are all kinds of temporary variables which get released once the calculation is done, but in the 
moment these could require additional memory and could push to OOM. Therefore, when coding it's crucial to think 
strategically about such temporary variables and sometimes to explicitly free those as soon as they are no longer needed.

**Functionality-specific memory**

Then, your software could have special memory needs. For example, when generating text using beam search, the software 
needs to maintain multiple copies of inputs and outputs.

**`forward` vs `backward` Execution Speed**

For convolutions and linear layers there are 2x flops in the backward compared to the forward, which generally translates 
into ~2x slower (sometimes more, because sizes in the backward tend to be more awkward). Activations are usually 
bandwidth-limited, and it’s typical for an activation to have to read more data in the backward than in the forward 
(e.g. activation forward reads once, writes once, activation backward reads twice, gradOutput and output of the forward, 
and writes once, gradInput).

As you can see, there are potentially a few places where we could save GPU memory or speed up operations. 
Now that you understand what affects GPU utilization and computation speed, refer to 
the [Methods and tools for efficient training on a single GPU](perf_train_gpu_one) documentation page to learn about 
performance optimization techniques.


key: _node_content
string_value:
{"id_": "102b47df-d842-4013-a864-448c2c043a01", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/perplexity", "title": "Perplexity of fixed-length models", "tokens": 1903, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "720d90e9-5e84-405a-be21-75132ee4bc56", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/perplexity", "title": "Perplexity of fixed-length models", "tokens": 1903, "retrieve_doc": true, "source": "transformers"}, "hash": "c29ba1f258b9e32a5b6f976fff7045260dca085781f1e2dff67156b969945dc5", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "1938e98c-6bb0-4906-ba57-e7e1b726535a", "node_type": "1", "metadata": {}, "hash": "349273f6595ed9a52b59bc0c7e6170d465dee7e40a42eb62ca7e02927db7b804", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 3254, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# Perplexity of fixed-length models

[[open-in-colab]]

Perplexity (PPL) is one of the most common metrics for evaluating language models. Before diving in, we should note
that the metric applies specifically to classical language models (sometimes called autoregressive or causal language
models) and is not well defined for masked language models like BERT (see [summary of the models](model_summary)).

Perplexity is defined as the exponentiated average negative log-likelihood of a sequence. If we have a tokenized
sequence \\(X = (x_0, x_1, \dots, x_t)\\), then the perplexity of \\(X\\) is,

$$\text{PPL}(X) = \exp \left\{ {-\frac{1}{t}\sum_i^t \log p_\theta (x_i|x_{<i}) } \right\}$$

where \\(\log p_\theta (x_i|x_{<i})\\) is the log-likelihood of the ith token conditioned on the preceding tokens \\(x_{<i}\\) according to our model. Intuitively, it can be thought of as an evaluation of the model's ability to predict uniformly among the set of specified tokens in a corpus. Importantly, this means that the tokenization procedure has a direct impact on a model's perplexity which should always be taken into consideration when comparing different models.

This is also equivalent to the exponentiation of the cross-entropy between the data and model predictions. For more
intuition about perplexity and its relationship to Bits Per Character (BPC) and data compression, check out this
[fantastic blog post on The Gradient](https://thegradient.pub/understanding-evaluation-metrics-for-language-models/).

## Calculating PPL with fixed-length models

If we weren't limited by a model's context size, we would evaluate the model's perplexity by autoregressively
factorizing a sequence and conditioning on the entire preceding subsequence at each step, as shown below.

<img width="600" alt="Full decomposition of a sequence with unlimited context length" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/ppl_full.gif"/>

When working with approximate models, however, we typically have a constraint on the number of tokens the model can
process. The largest version of [GPT-2](model_doc/gpt2), for example, has a fixed length of 1024 tokens, so we
cannot calculate \\(p_\theta(x_t|x_{<t})\\) directly when \\(t\\) is greater than 1024.

Instead, the sequence is typically broken into subsequences equal to the model's maximum input size. If a model's max
input size is \\(k\\), we then approximate the likelihood of a token \\(x_t\\) by conditioning only on the
\\(k-1\\) tokens that precede it rather than the entire context. When evaluating the model's perplexity of a
sequence, a tempting but suboptimal approach is to break the sequence into disjoint chunks and add up the decomposed
log-likelihoods of each segment independently.

<img width="600" alt="Suboptimal PPL not taking advantage of full available context" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/ppl_chunked.gif"/>

This is quick to compute since the perplexity of each segment can be computed in one forward pass, but serves as a poor
approximation of the fully-factorized perplexity and will typically yield a higher (worse) PPL because the model will
have less context at most of the prediction steps.


key: _node_content
string_value:
{"id_": "1938e98c-6bb0-4906-ba57-e7e1b726535a", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/perplexity", "title": "Perplexity of fixed-length models", "tokens": 1903, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "720d90e9-5e84-405a-be21-75132ee4bc56", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/perplexity", "title": "Perplexity of fixed-length models", "tokens": 1903, "retrieve_doc": true, "source": "transformers"}, "hash": "c29ba1f258b9e32a5b6f976fff7045260dca085781f1e2dff67156b969945dc5", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "102b47df-d842-4013-a864-448c2c043a01", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/perplexity", "title": "Perplexity of fixed-length models", "tokens": 1903, "retrieve_doc": true, "source": "transformers"}, "hash": "d7916dff950d62ff915eec3023ee3506d5dcfa7f723cd1b0ee2480735a823bff", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "1e36de2d-48dd-4bc3-83e0-5905ac608d04", "node_type": "1", "metadata": {}, "hash": "d00b2ac07bc0c169ee16cb9e6f6a3a39734c923ce99e6ef2856b8bf083a4c9f1", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 1777, "end_char_idx": 5107, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
<img width="600" alt="Full decomposition of a sequence with unlimited context length" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/ppl_full.gif"/>

When working with approximate models, however, we typically have a constraint on the number of tokens the model can
process. The largest version of [GPT-2](model_doc/gpt2), for example, has a fixed length of 1024 tokens, so we
cannot calculate \\(p_\theta(x_t|x_{<t})\\) directly when \\(t\\) is greater than 1024.

Instead, the sequence is typically broken into subsequences equal to the model's maximum input size. If a model's max
input size is \\(k\\), we then approximate the likelihood of a token \\(x_t\\) by conditioning only on the
\\(k-1\\) tokens that precede it rather than the entire context. When evaluating the model's perplexity of a
sequence, a tempting but suboptimal approach is to break the sequence into disjoint chunks and add up the decomposed
log-likelihoods of each segment independently.

<img width="600" alt="Suboptimal PPL not taking advantage of full available context" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/ppl_chunked.gif"/>

This is quick to compute since the perplexity of each segment can be computed in one forward pass, but serves as a poor
approximation of the fully-factorized perplexity and will typically yield a higher (worse) PPL because the model will
have less context at most of the prediction steps.

Instead, the PPL of fixed-length models should be evaluated with a sliding-window strategy. This involves repeatedly
sliding the context window so that the model has more context when making each prediction.

<img width="600" alt="Sliding window PPL taking advantage of all available context" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/ppl_sliding.gif"/>

This is a closer approximation to the true decomposition of the sequence probability and will typically yield a more
favorable score. The downside is that it requires a separate forward pass for each token in the corpus. A good
practical compromise is to employ a strided sliding window, moving the context by larger strides rather than sliding by
1 token a time. This allows computation to proceed much faster while still giving the model a large context to make
predictions at each step.

## Example: Calculating perplexity with GPT-2 in 🤗 Transformers

Let's demonstrate this process with GPT-2.

```python
from transformers import GPT2LMHeadModel, GPT2TokenizerFast

device = "cuda"
model_id = "openai-community/gpt2-large"
model = GPT2LMHeadModel.from_pretrained(model_id).to(device)
tokenizer = GPT2TokenizerFast.from_pretrained(model_id)
```

We'll load in the WikiText-2 dataset and evaluate the perplexity using a few different sliding-window strategies. Since
this dataset is small and we're just doing one forward pass over the set, we can just load and encode the entire
dataset in memory.

```python
from datasets import load_dataset

test = load_dataset("wikitext", "wikitext-2-raw-v1", split="test")
encodings = tokenizer("\n\n".join(test["text"]), return_tensors="pt")
```

With 🤗 Transformers, we can simply pass the `input_ids` as the `labels` to our model, and the average negative
log-likelihood for each token is returned as the loss.


key: _node_content
string_value:
{"id_": "1e36de2d-48dd-4bc3-83e0-5905ac608d04", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/perplexity", "title": "Perplexity of fixed-length models", "tokens": 1903, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "720d90e9-5e84-405a-be21-75132ee4bc56", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/perplexity", "title": "Perplexity of fixed-length models", "tokens": 1903, "retrieve_doc": true, "source": "transformers"}, "hash": "c29ba1f258b9e32a5b6f976fff7045260dca085781f1e2dff67156b969945dc5", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "1938e98c-6bb0-4906-ba57-e7e1b726535a", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/perplexity", "title": "Perplexity of fixed-length models", "tokens": 1903, "retrieve_doc": true, "source": "transformers"}, "hash": "4e9d73b0f3eb332f77da00dd67c47d8c9a9edc87c83486902d6b910756073a42", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b673b162-c667-4e47-b76f-f3cfb79b495c", "node_type": "1", "metadata": {}, "hash": "cc7119436ec9342d105aafdbd37a8a900fc506df9e37bc54541fe10956c0782b", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 3465, "end_char_idx": 6335, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
<img width="600" alt="Sliding window PPL taking advantage of all available context" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/ppl_sliding.gif"/>

This is a closer approximation to the true decomposition of the sequence probability and will typically yield a more
favorable score. The downside is that it requires a separate forward pass for each token in the corpus. A good
practical compromise is to employ a strided sliding window, moving the context by larger strides rather than sliding by
1 token a time. This allows computation to proceed much faster while still giving the model a large context to make
predictions at each step.

## Example: Calculating perplexity with GPT-2 in 🤗 Transformers

Let's demonstrate this process with GPT-2.

```python
from transformers import GPT2LMHeadModel, GPT2TokenizerFast

device = "cuda"
model_id = "openai-community/gpt2-large"
model = GPT2LMHeadModel.from_pretrained(model_id).to(device)
tokenizer = GPT2TokenizerFast.from_pretrained(model_id)
```

We'll load in the WikiText-2 dataset and evaluate the perplexity using a few different sliding-window strategies. Since
this dataset is small and we're just doing one forward pass over the set, we can just load and encode the entire
dataset in memory.

```python
from datasets import load_dataset

test = load_dataset("wikitext", "wikitext-2-raw-v1", split="test")
encodings = tokenizer("\n\n".join(test["text"]), return_tensors="pt")
```

With 🤗 Transformers, we can simply pass the `input_ids` as the `labels` to our model, and the average negative
log-likelihood for each token is returned as the loss. With our sliding window approach, however, there is overlap in
the tokens we pass to the model at each iteration. We don't want the log-likelihood for the tokens we're just treating
as context to be included in our loss, so we can set these targets to `-100` so that they are ignored. The following
is an example of how we could do this with a stride of `512`. This means that the model will have at least 512 tokens
for context when calculating the conditional likelihood of any one token (provided there are 512 preceding tokens
available to condition on).

```python
import torch
from tqdm import tqdm

max_length = model.config.n_positions
stride = 512
seq_len = encodings.input_ids.size(1)

nlls = []
prev_end_loc = 0
for begin_loc in tqdm(range(0, seq_len, stride)):
    end_loc = min(begin_loc + max_length, seq_len)
    trg_len = end_loc - prev_end_loc  # may be different from stride on last loop
    input_ids = encodings.input_ids[:, begin_loc:end_loc].to(device)
    target_ids = input_ids.clone()
    target_ids[:, :-trg_len] = -100

    with torch.no_grad():
        outputs = model(input_ids, labels=target_ids)

        # loss is calculated using CrossEntropyLoss which averages over valid labels
        # N.B.


key: _node_content
string_value:
{"id_": "b673b162-c667-4e47-b76f-f3cfb79b495c", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/perplexity", "title": "Perplexity of fixed-length models", "tokens": 1903, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "720d90e9-5e84-405a-be21-75132ee4bc56", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/perplexity", "title": "Perplexity of fixed-length models", "tokens": 1903, "retrieve_doc": true, "source": "transformers"}, "hash": "c29ba1f258b9e32a5b6f976fff7045260dca085781f1e2dff67156b969945dc5", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "1e36de2d-48dd-4bc3-83e0-5905ac608d04", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/perplexity", "title": "Perplexity of fixed-length models", "tokens": 1903, "retrieve_doc": true, "source": "transformers"}, "hash": "5360e1737ae012a7c10509fa76687258ea419f54944909678c469293c284d652", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 4755, "end_char_idx": 7362, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
from datasets import load_dataset

test = load_dataset("wikitext", "wikitext-2-raw-v1", split="test")
encodings = tokenizer("\n\n".join(test["text"]), return_tensors="pt")
```

With 🤗 Transformers, we can simply pass the `input_ids` as the `labels` to our model, and the average negative
log-likelihood for each token is returned as the loss. With our sliding window approach, however, there is overlap in
the tokens we pass to the model at each iteration. We don't want the log-likelihood for the tokens we're just treating
as context to be included in our loss, so we can set these targets to `-100` so that they are ignored. The following
is an example of how we could do this with a stride of `512`. This means that the model will have at least 512 tokens
for context when calculating the conditional likelihood of any one token (provided there are 512 preceding tokens
available to condition on).

```python
import torch
from tqdm import tqdm

max_length = model.config.n_positions
stride = 512
seq_len = encodings.input_ids.size(1)

nlls = []
prev_end_loc = 0
for begin_loc in tqdm(range(0, seq_len, stride)):
    end_loc = min(begin_loc + max_length, seq_len)
    trg_len = end_loc - prev_end_loc  # may be different from stride on last loop
    input_ids = encodings.input_ids[:, begin_loc:end_loc].to(device)
    target_ids = input_ids.clone()
    target_ids[:, :-trg_len] = -100

    with torch.no_grad():
        outputs = model(input_ids, labels=target_ids)

        # loss is calculated using CrossEntropyLoss which averages over valid labels
        # N.B. the model only calculates loss over trg_len - 1 labels, because it internally shifts the labels
        # to the left by 1.
        neg_log_likelihood = outputs.loss

    nlls.append(neg_log_likelihood)

    prev_end_loc = end_loc
    if end_loc == seq_len:
        break

ppl = torch.exp(torch.stack(nlls).mean())
```

Running this with the stride length equal to the max input length is equivalent to the suboptimal, non-sliding-window
strategy we discussed above. The smaller the stride, the more context the model will have in making each prediction,
and the better the reported perplexity will typically be.

When we run the above with `stride = 1024`, i.e. no overlap, the resulting PPL is `19.44`, which is about the same
as the `19.93` reported in the GPT-2 paper. By using `stride = 512` and thereby employing our striding window
strategy, this jumps down to `16.45`. This is not only a more favorable score, but is calculated in a way that is
closer to the true autoregressive decomposition of a sequence likelihood.


key: _node_content
string_value:
{"id_": "fa85588b-bfcd-4b5f-865f-23c34bc25726", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "1c0c2e70-0214-4869-b53f-874503acf230", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers"}, "hash": "3c4db41f215ae561c744c2ae863968a76be548ad4988ec72355258e6160a8050", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "d23e43e0-6b77-4c19-98f5-3ddae52e1897", "node_type": "1", "metadata": {}, "hash": "501f5bb903ee0f797ed242e6f91fe24835c84f21825d678f28893455bf41fbe6", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 3420, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# Agents and tools

[[open-in-colab]]

### What is an agent?

Large Language Models (LLMs) trained to perform [causal language modeling](./tasks/language_modeling.) can tackle a wide range of tasks, but they often struggle with basic tasks like logic, calculation, and search. When prompted in domains in which they do not perform well, they often fail to generate the answer we expect them to.

One approach to overcome this weakness is to create an *agent*.

An agent is a system that uses an LLM as its engine, and it has access to functions called *tools*.

These *tools* are functions for performing a task, and they contain all necessary description for the agent to properly use them.

The agent can be programmed to:
- devise a series of actions/tools and run them all at once like the [`CodeAgent`] for example
- plan and execute actions/tools one by one and wait for the outcome of each action before launching the next one like the [`ReactJsonAgent`] for example

### Types of agents

#### Code agent

This agent has a planning step, then generates python code to execute all its actions at once. It natively handles different input and output types for its tools, thus it is the recommended choice for multimodal tasks.

#### React agents

This is the go-to agent to solve reasoning tasks, since the ReAct framework ([Yao et al., 2022](https://huggingface.co/papers/2210.03629)) makes it really efficient to think on the basis of its previous observations.

We implement two versions of ReactJsonAgent: 
- [`ReactJsonAgent`] generates tool calls as a JSON in its output.
- [`ReactCodeAgent`] is a new type of ReactJsonAgent that generates its tool calls as blobs of code, which works really well for LLMs that have strong coding performance.

> [!TIP]
> Read [Open-source LLMs as LangChain Agents](https://huggingface.co/blog/open-source-llms-as-agents) blog post to learn more the ReAct agent.

![Framework of a React Agent](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/open-source-llms-as-agents/ReAct.png)

For example, here is how a ReAct Code agent would work its way through the following question.

```py3
>>> agent.run(
...     "How many more blocks (also denoted as layers) in BERT base encoder than the encoder from the architecture proposed in Attention is All You Need?",
... )
=====New task=====
How many more blocks (also denoted as layers) in BERT base encoder than the encoder from the architecture proposed in Attention is All You Need?
====Agent is executing the code below:
bert_blocks = search(query="number of blocks in BERT base encoder")
print("BERT blocks:", bert_blocks)
====
Print outputs:
BERT blocks: twelve encoder blocks

====Agent is executing the code below:
attention_layer = search(query="number of layers in Attention is All You Need")
print("Attention layers:", attention_layer)
====
Print outputs:
Attention layers: Encoder: The encoder is composed of a stack of N = 6 identical layers. Each layer has two sub-layers. The first is a multi-head self-attention mechanism, and the second is a simple, position- 2 Page 3 Figure 1: The Transformer - model architecture.

====Agent is executing the code below:
bert_blocks = 12
attention_layers = 6
diff = bert_blocks - attention_layers
print("Difference in blocks:", diff)
final_answer(diff)
====

Print outputs:
Difference in blocks: 6

Final answer: 6
```

### How can I build an agent?


key: _node_content
string_value:
{"id_": "d23e43e0-6b77-4c19-98f5-3ddae52e1897", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "1c0c2e70-0214-4869-b53f-874503acf230", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers"}, "hash": "3c4db41f215ae561c744c2ae863968a76be548ad4988ec72355258e6160a8050", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "fa85588b-bfcd-4b5f-865f-23c34bc25726", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers"}, "hash": "350fb663e3d59c953674aaf34977431129496cdfcf69353276fe3e667b9f4fce", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "3db0f83d-aeb3-48bc-bce8-85f1d3d7cad7", "node_type": "1", "metadata": {}, "hash": "2665a91562ceb5f74c6f081d64e3da8eb37ba50b53239841fe798c73792b73c8", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 1755, "end_char_idx": 4973, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
> [!TIP]
> Read [Open-source LLMs as LangChain Agents](https://huggingface.co/blog/open-source-llms-as-agents) blog post to learn more the ReAct agent.

![Framework of a React Agent](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/open-source-llms-as-agents/ReAct.png)

For example, here is how a ReAct Code agent would work its way through the following question.

```py3
>>> agent.run(
...     "How many more blocks (also denoted as layers) in BERT base encoder than the encoder from the architecture proposed in Attention is All You Need?",
... )
=====New task=====
How many more blocks (also denoted as layers) in BERT base encoder than the encoder from the architecture proposed in Attention is All You Need?
====Agent is executing the code below:
bert_blocks = search(query="number of blocks in BERT base encoder")
print("BERT blocks:", bert_blocks)
====
Print outputs:
BERT blocks: twelve encoder blocks

====Agent is executing the code below:
attention_layer = search(query="number of layers in Attention is All You Need")
print("Attention layers:", attention_layer)
====
Print outputs:
Attention layers: Encoder: The encoder is composed of a stack of N = 6 identical layers. Each layer has two sub-layers. The first is a multi-head self-attention mechanism, and the second is a simple, position- 2 Page 3 Figure 1: The Transformer - model architecture.

====Agent is executing the code below:
bert_blocks = 12
attention_layers = 6
diff = bert_blocks - attention_layers
print("Difference in blocks:", diff)
final_answer(diff)
====

Print outputs:
Difference in blocks: 6

Final answer: 6
```

### How can I build an agent?

To initialize an agent, you need these arguments:

- an LLM to power your agent - the agent is not exactly the LLM, it’s more like the agent is a program that uses an LLM as its engine.
- a system prompt: what the LLM engine will be prompted with to generate its output
- a toolbox from which the agent pick tools to execute
- a parser to extract from the LLM output which tools are to call and with which arguments

Upon initialization of the agent system, the tool attributes are used to generate a tool description, then baked into the agent’s `system_prompt` to let it know which tools it can use and why.

To start with, please install the `agents` extras in order to install all default dependencies.

```bash
pip install transformers[agents]
```

Build your LLM engine by defining a `llm_engine` method which accepts a list of [messages](./chat_templating.) and returns text. This callable also needs to accept a `stop` argument that indicates when to stop generating.

```python
from huggingface_hub import login, InferenceClient

login("<YOUR_HUGGINGFACEHUB_API_TOKEN>")

client = InferenceClient(model="meta-llama/Meta-Llama-3-70B-Instruct")

def llm_engine(messages, stop_sequences=["Task"]) -> str:
    response = client.chat_completion(messages, stop=stop_sequences, max_tokens=1000)
    answer = response.choices[0].message.content
    return answer
```

You could use any `llm_engine` method as long as:
1. it follows the [messages format](./chat_templating.md) (`List[Dict[str, str]]`) for its input `messages`, and it returns a `str`.


key: _node_content
string_value:
{"id_": "3db0f83d-aeb3-48bc-bce8-85f1d3d7cad7", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "1c0c2e70-0214-4869-b53f-874503acf230", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers"}, "hash": "3c4db41f215ae561c744c2ae863968a76be548ad4988ec72355258e6160a8050", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "d23e43e0-6b77-4c19-98f5-3ddae52e1897", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers"}, "hash": "9095a397bca2e06c2ea753cc46da092253cd7551672de8d185e161621c271371", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b0064cc7-889a-451a-bc9c-71728a948d8b", "node_type": "1", "metadata": {}, "hash": "1f4d16157609a2784bc904746ce358e2e02a167e259da37dec98eda9fd80bdef", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 3422, "end_char_idx": 6641, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
To initialize an agent, you need these arguments:

- an LLM to power your agent - the agent is not exactly the LLM, it’s more like the agent is a program that uses an LLM as its engine.
- a system prompt: what the LLM engine will be prompted with to generate its output
- a toolbox from which the agent pick tools to execute
- a parser to extract from the LLM output which tools are to call and with which arguments

Upon initialization of the agent system, the tool attributes are used to generate a tool description, then baked into the agent’s `system_prompt` to let it know which tools it can use and why.

To start with, please install the `agents` extras in order to install all default dependencies.

```bash
pip install transformers[agents]
```

Build your LLM engine by defining a `llm_engine` method which accepts a list of [messages](./chat_templating.) and returns text. This callable also needs to accept a `stop` argument that indicates when to stop generating.

```python
from huggingface_hub import login, InferenceClient

login("<YOUR_HUGGINGFACEHUB_API_TOKEN>")

client = InferenceClient(model="meta-llama/Meta-Llama-3-70B-Instruct")

def llm_engine(messages, stop_sequences=["Task"]) -> str:
    response = client.chat_completion(messages, stop=stop_sequences, max_tokens=1000)
    answer = response.choices[0].message.content
    return answer
```

You could use any `llm_engine` method as long as:
1. it follows the [messages format](./chat_templating.md) (`List[Dict[str, str]]`) for its input `messages`, and it returns a `str`.
2. it stops generating outputs at the sequences passed in the argument `stop_sequences`

Additionally, `llm_engine` can also take a `grammar` argument. In the case where you specify a `grammar` upon agent initialization, this argument will be passed to the calls to llm_engine, with the `grammar` that you defined upon initialization, to allow [constrained generation](https://huggingface.co/docs/text-generation-inference/conceptual/guidance) in order to force properly-formatted agent outputs.

You will also need a `tools` argument which accepts a list of `Tools` - it can be an empty list. You can also add the default toolbox on top of your `tools` list by defining the optional argument `add_base_tools=True`.

Now you can create an agent, like [`CodeAgent`], and run it. For convenience, we also provide the [`HfEngine`] class that uses `huggingface_hub.InferenceClient` under the hood.

```python
from transformers import CodeAgent, HfEngine

llm_engine = HfEngine(model="meta-llama/Meta-Llama-3-70B-Instruct")
agent = CodeAgent(tools=[], llm_engine=llm_engine, add_base_tools=True)

agent.run(
    "Could you translate this sentence from French, say it out loud and return the audio.",
    sentence="Où est la boulangerie la plus proche?",
)
```

This will be handy in case of emergency baguette need!
You can even leave the argument `llm_engine` undefined, and an [`HfEngine`] will be created by default.

```python
from transformers import CodeAgent

agent = CodeAgent(tools=[], add_base_tools=True)

agent.run(
    "Could you translate this sentence from French, say it out loud and give me the audio.",
    sentence="Où est la boulangerie la plus proche?


key: _node_content
string_value:
{"id_": "b0064cc7-889a-451a-bc9c-71728a948d8b", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "1c0c2e70-0214-4869-b53f-874503acf230", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers"}, "hash": "3c4db41f215ae561c744c2ae863968a76be548ad4988ec72355258e6160a8050", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "3db0f83d-aeb3-48bc-bce8-85f1d3d7cad7", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers"}, "hash": "b36da4476d107ddc43db237a7316a36f42f04449ca3abfb0076665f1f5090f54", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "8a847532-70b6-4909-a1bc-be7eb392374d", "node_type": "1", "metadata": {}, "hash": "ed4f3cb2d18dc78fcd419774d2907c39000d939a6208ac94a01e4f19ec9cdd07", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 5126, "end_char_idx": 8202, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
In the case where you specify a `grammar` upon agent initialization, this argument will be passed to the calls to llm_engine, with the `grammar` that you defined upon initialization, to allow [constrained generation](https://huggingface.co/docs/text-generation-inference/conceptual/guidance) in order to force properly-formatted agent outputs.

You will also need a `tools` argument which accepts a list of `Tools` - it can be an empty list. You can also add the default toolbox on top of your `tools` list by defining the optional argument `add_base_tools=True`.

Now you can create an agent, like [`CodeAgent`], and run it. For convenience, we also provide the [`HfEngine`] class that uses `huggingface_hub.InferenceClient` under the hood.

```python
from transformers import CodeAgent, HfEngine

llm_engine = HfEngine(model="meta-llama/Meta-Llama-3-70B-Instruct")
agent = CodeAgent(tools=[], llm_engine=llm_engine, add_base_tools=True)

agent.run(
    "Could you translate this sentence from French, say it out loud and return the audio.",
    sentence="Où est la boulangerie la plus proche?",
)
```

This will be handy in case of emergency baguette need!
You can even leave the argument `llm_engine` undefined, and an [`HfEngine`] will be created by default.

```python
from transformers import CodeAgent

agent = CodeAgent(tools=[], add_base_tools=True)

agent.run(
    "Could you translate this sentence from French, say it out loud and give me the audio.",
    sentence="Où est la boulangerie la plus proche?",
)
```

Note that we used an additional `sentence` argument: you can pass text as additional arguments to the model.

You can also use this to indicate the path to local or remote files for the model to use:

```py
from transformers import ReactCodeAgent

agent = ReactCodeAgent(tools=[], llm_engine=llm_engine, add_base_tools=True)

agent.run("Why does Mike not know many people in New York?", audio="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/recording.mp3")
```


The prompt and output parser were automatically defined, but you can easily inspect them by calling the `system_prompt_template` on your agent.

```python
print(agent.system_prompt_template)
```

It's important to explain as clearly as possible the task you want to perform.
Every [`~Agent.run`] operation is independent, and since an agent is powered by an LLM, minor variations in your prompt might yield completely different results.
You can also run an agent consecutively for different tasks: each time the attributes `agent.task` and `agent.logs` will be re-initialized.


#### Code execution

A Python interpreter executes the code on a set of inputs passed along with your tools.
This should be safe because the only functions that can be called are the tools you provided (especially if it's only tools by Hugging Face) and the print function, so you're already limited in what can be executed.

The Python interpreter also doesn't allow imports by default outside of a safe list, so all the most obvious attacks shouldn't be an issue.


key: _node_content
string_value:
{"id_": "8a847532-70b6-4909-a1bc-be7eb392374d", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "1c0c2e70-0214-4869-b53f-874503acf230", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers"}, "hash": "3c4db41f215ae561c744c2ae863968a76be548ad4988ec72355258e6160a8050", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "b0064cc7-889a-451a-bc9c-71728a948d8b", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers"}, "hash": "5603cb6d0030f020f8412288b9661ed8adff63ea6703f1938481e63876cec82c", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "b581a76a-4bff-4704-b88e-38fa917e4148", "node_type": "1", "metadata": {}, "hash": "8b2519f77ed1939868b536fb51ca8364083a7303e4e72aefed805c062ba4f6b4", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 6390, "end_char_idx": 9884, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
from transformers import CodeAgent

agent = CodeAgent(tools=[], add_base_tools=True)

agent.run(
    "Could you translate this sentence from French, say it out loud and give me the audio.",
    sentence="Où est la boulangerie la plus proche?",
)
```

Note that we used an additional `sentence` argument: you can pass text as additional arguments to the model.

You can also use this to indicate the path to local or remote files for the model to use:

```py
from transformers import ReactCodeAgent

agent = ReactCodeAgent(tools=[], llm_engine=llm_engine, add_base_tools=True)

agent.run("Why does Mike not know many people in New York?", audio="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/recording.mp3")
```


The prompt and output parser were automatically defined, but you can easily inspect them by calling the `system_prompt_template` on your agent.

```python
print(agent.system_prompt_template)
```

It's important to explain as clearly as possible the task you want to perform.
Every [`~Agent.run`] operation is independent, and since an agent is powered by an LLM, minor variations in your prompt might yield completely different results.
You can also run an agent consecutively for different tasks: each time the attributes `agent.task` and `agent.logs` will be re-initialized.


#### Code execution

A Python interpreter executes the code on a set of inputs passed along with your tools.
This should be safe because the only functions that can be called are the tools you provided (especially if it's only tools by Hugging Face) and the print function, so you're already limited in what can be executed.

The Python interpreter also doesn't allow imports by default outside of a safe list, so all the most obvious attacks shouldn't be an issue.
You can still authorize additional imports by passing the authorized modules as a list of strings in argument `additional_authorized_imports` upon initialization of your [`ReactCodeAgent`] or [`CodeAgent`]:

```py
>>> from transformers import ReactCodeAgent

>>> agent = ReactCodeAgent(tools=[], additional_authorized_imports=['requests', 'bs4'])
>>> agent.run("Could you get me the title of the page at url 'https://huggingface.co/blog'?")

(...)
'Hugging Face – Blog'
```

The execution will stop at any code trying to perform an illegal operation or if there is a regular Python error with the code generated by the agent.

> [!WARNING]
> The LLM can generate arbitrary code that will then be executed: do not add any unsafe imports!

### The system prompt

An agent, or rather the LLM that drives the agent, generates an output based on the system prompt. The system prompt can be customized and tailored to the intended task. For example, check the system prompt for the [`ReactCodeAgent`] (below version is slightly simplified).

```text
You will be given a task to solve as best you can.
You have access to the following tools:
<<tool_descriptions>>

To solve the task, you must plan forward to proceed in a series of steps, in a cycle of 'Thought:', 'Code:', and 'Observation:' sequences.

At each step, in the 'Thought:' sequence, you should first explain your reasoning towards solving the task, then the tools that you want to use.
Then in the 'Code:' sequence, you shold write the code in simple Python. The code sequence must end with '/End code' sequence.
During each intermediate step, you can use 'print()' to save whatever important information you will then need.


key: _node_content
string_value:
{"id_": "b581a76a-4bff-4704-b88e-38fa917e4148", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "1c0c2e70-0214-4869-b53f-874503acf230", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers"}, "hash": "3c4db41f215ae561c744c2ae863968a76be548ad4988ec72355258e6160a8050", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "8a847532-70b6-4909-a1bc-be7eb392374d", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers"}, "hash": "65830ef04850d82e02fb5fcbbff46676fff5c0c1849c835587ca59bdf1e075cd", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "54377bb2-7927-4b50-8f22-8bd7528f7c52", "node_type": "1", "metadata": {}, "hash": "1597e91ac735ab511aae250004f9ecdecaef8ffb28aeb16142116aed2af5f0f9", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 8063, "end_char_idx": 11554, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
The Python interpreter also doesn't allow imports by default outside of a safe list, so all the most obvious attacks shouldn't be an issue.
You can still authorize additional imports by passing the authorized modules as a list of strings in argument `additional_authorized_imports` upon initialization of your [`ReactCodeAgent`] or [`CodeAgent`]:

```py
>>> from transformers import ReactCodeAgent

>>> agent = ReactCodeAgent(tools=[], additional_authorized_imports=['requests', 'bs4'])
>>> agent.run("Could you get me the title of the page at url 'https://huggingface.co/blog'?")

(...)
'Hugging Face – Blog'
```

The execution will stop at any code trying to perform an illegal operation or if there is a regular Python error with the code generated by the agent.

> [!WARNING]
> The LLM can generate arbitrary code that will then be executed: do not add any unsafe imports!

### The system prompt

An agent, or rather the LLM that drives the agent, generates an output based on the system prompt. The system prompt can be customized and tailored to the intended task. For example, check the system prompt for the [`ReactCodeAgent`] (below version is slightly simplified).

```text
You will be given a task to solve as best you can.
You have access to the following tools:
<<tool_descriptions>>

To solve the task, you must plan forward to proceed in a series of steps, in a cycle of 'Thought:', 'Code:', and 'Observation:' sequences.

At each step, in the 'Thought:' sequence, you should first explain your reasoning towards solving the task, then the tools that you want to use.
Then in the 'Code:' sequence, you shold write the code in simple Python. The code sequence must end with '/End code' sequence.
During each intermediate step, you can use 'print()' to save whatever important information you will then need.
These print outputs will then be available in the 'Observation:' field, for using this information as input for the next step.

In the end you have to return a final answer using the `final_answer` tool.

Here are a few examples using notional tools:
---
{examples}

Above example were using notional tools that might not exist for you. You only have acces to those tools:
<<tool_names>>
You also can perform computations in the python code you generate.

Always provide a 'Thought:' and a 'Code:\n```py' sequence ending with '```<end_code>' sequence. You MUST provide at least the 'Code:' sequence to move forward.

Remember to not perform too many operations in a single code block! You should split the task into intermediate code blocks.
Print results at the end of each step to save the intermediate results. Then use final_answer() to return the final result.

Remember to make sure that variables you use are all defined.

Now Begin!
```

The system prompt includes:
- An *introduction* that explains how the agent should behave and what tools are.
- A description of all the tools that is defined by a `<<tool_descriptions>>` token that is dynamically replaced at runtime with the tools defined/chosen by the user.
    - The tool description comes from the tool attributes, `name`, `description`, `inputs` and `output_type`,  and a simple `jinja2` template that you can refine.
- The expected output format.

You could improve the system prompt, for example, by adding an explanation of the output format.

For maximum flexibility, you can overwrite the whole system prompt template by passing your custom prompt as an argument to the `system_prompt` parameter.


key: _node_content
string_value:
{"id_": "54377bb2-7927-4b50-8f22-8bd7528f7c52", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "1c0c2e70-0214-4869-b53f-874503acf230", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers"}, "hash": "3c4db41f215ae561c744c2ae863968a76be548ad4988ec72355258e6160a8050", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "b581a76a-4bff-4704-b88e-38fa917e4148", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers"}, "hash": "350706ddccf45944cfff22f9942b25a5c72bc5f119d437a75fc4fdc9c009455e", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "e147e675-05de-4855-9b53-33e4a95cba77", "node_type": "1", "metadata": {}, "hash": "910a6b9dabc332606eed91decb9a5bb857238f301fb1013279bc3652aa737a24", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 9719, "end_char_idx": 11911, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
The code sequence must end with '/End code' sequence.
During each intermediate step, you can use 'print()' to save whatever important information you will then need.
These print outputs will then be available in the 'Observation:' field, for using this information as input for the next step.

In the end you have to return a final answer using the `final_answer` tool.

Here are a few examples using notional tools:
---
{examples}

Above example were using notional tools that might not exist for you. You only have acces to those tools:
<<tool_names>>
You also can perform computations in the python code you generate.

Always provide a 'Thought:' and a 'Code:\n```py' sequence ending with '```<end_code>' sequence. You MUST provide at least the 'Code:' sequence to move forward.

Remember to not perform too many operations in a single code block! You should split the task into intermediate code blocks.
Print results at the end of each step to save the intermediate results. Then use final_answer() to return the final result.

Remember to make sure that variables you use are all defined.

Now Begin!
```

The system prompt includes:
- An *introduction* that explains how the agent should behave and what tools are.
- A description of all the tools that is defined by a `<<tool_descriptions>>` token that is dynamically replaced at runtime with the tools defined/chosen by the user.
    - The tool description comes from the tool attributes, `name`, `description`, `inputs` and `output_type`,  and a simple `jinja2` template that you can refine.
- The expected output format.

You could improve the system prompt, for example, by adding an explanation of the output format.

For maximum flexibility, you can overwrite the whole system prompt template by passing your custom prompt as an argument to the `system_prompt` parameter.

```python
from transformers import ReactJsonAgent
from transformers.agents import PythonInterpreterTool

agent = ReactJsonAgent(tools=[PythonInterpreterTool()], system_prompt="{your_custom_prompt}")
```

> [!WARNING]
> Please make sure to define the `<<tool_descriptions>>` string somewhere in the `template` so the agent is aware 
of the available tools.


key: _node_content
string_value:
{"id_": "e147e675-05de-4855-9b53-33e4a95cba77", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "1c0c2e70-0214-4869-b53f-874503acf230", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers"}, "hash": "3c4db41f215ae561c744c2ae863968a76be548ad4988ec72355258e6160a8050", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "54377bb2-7927-4b50-8f22-8bd7528f7c52", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers"}, "hash": "c9694a8fe95d473ace400c2c6164356df1c166d13fb60291a5b2154963993df5", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "befcdcbc-cd6a-4870-9fda-d0795ede876d", "node_type": "1", "metadata": {}, "hash": "529c68a103c37035bd58003dba137a840a96e7af9fc865412e7a0b90fdfc313e", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 10090, "end_char_idx": 14127, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Here are a few examples using notional tools:
---
{examples}

Above example were using notional tools that might not exist for you. You only have acces to those tools:
<<tool_names>>
You also can perform computations in the python code you generate.

Always provide a 'Thought:' and a 'Code:\n```py' sequence ending with '```<end_code>' sequence. You MUST provide at least the 'Code:' sequence to move forward.

Remember to not perform too many operations in a single code block! You should split the task into intermediate code blocks.
Print results at the end of each step to save the intermediate results. Then use final_answer() to return the final result.

Remember to make sure that variables you use are all defined.

Now Begin!
```

The system prompt includes:
- An *introduction* that explains how the agent should behave and what tools are.
- A description of all the tools that is defined by a `<<tool_descriptions>>` token that is dynamically replaced at runtime with the tools defined/chosen by the user.
    - The tool description comes from the tool attributes, `name`, `description`, `inputs` and `output_type`,  and a simple `jinja2` template that you can refine.
- The expected output format.

You could improve the system prompt, for example, by adding an explanation of the output format.

For maximum flexibility, you can overwrite the whole system prompt template by passing your custom prompt as an argument to the `system_prompt` parameter.

```python
from transformers import ReactJsonAgent
from transformers.agents import PythonInterpreterTool

agent = ReactJsonAgent(tools=[PythonInterpreterTool()], system_prompt="{your_custom_prompt}")
```

> [!WARNING]
> Please make sure to define the `<<tool_descriptions>>` string somewhere in the `template` so the agent is aware 
of the available tools.


### Inspecting an agent run

Here are a few useful attributes to inspect what happened after a run:
- `agent.logs` stores the fine-grained logs of the agent. At every step of the agent's run, everything gets stored in a dictionary that then is appended to `agent.logs`.
- Running `agent.write_inner_memory_from_logs()` creates an inner memory of the agent's logs for the LLM to view, as a list of chat messages. This method goes over each step of the log and only stores what it's interested in as a message: for instance, it will save the system prompt and task in separate messages, then for each step it will store the LLM output as a message, and the tool call output as another message. Use this if you want a higher-level view of what has happened - but not every log will be transcripted by this method.

## Tools

A tool is an atomic function to be used by an agent.

You can for instance check the [`PythonInterpreterTool`]: it has a name, a description, input descriptions, an output type, and a `__call__` method to perform the action.

When the agent is initialized, the tool attributes are used to generate a tool description which is baked into the agent's system prompt. This lets the agent know which tools it can use and why.

### Default toolbox

Transformers comes with a default toolbox for empowering agents, that you can add to your agent upon initialization with argument `add_base_tools = True`:

- **Document question answering**: given a document (such as a PDF) in image format, answer a question on this document ([Donut](./model_doc/donut))
- **Image question answering**: given an image, answer a question on this image ([VILT](./model_doc/vilt))
- **Speech to text**: given an audio recording of a person talking, transcribe the speech into text ([Whisper](./model_doc/whisper))
- **Text to speech**: convert text to speech ([SpeechT5](./model_doc/speecht5))
- **Translation**: translates a given sentence from source language to target language.
- **Python code interpreter**: runs your the LLM generated Python code in a secure environment. This tool will only be added to [`ReactJsonAgent`] if you use `add_base_tools=True`, since code-based tools can already execute Python code


key: _node_content
string_value:
{"id_": "befcdcbc-cd6a-4870-9fda-d0795ede876d", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "1c0c2e70-0214-4869-b53f-874503acf230", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers"}, "hash": "3c4db41f215ae561c744c2ae863968a76be548ad4988ec72355258e6160a8050", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "e147e675-05de-4855-9b53-33e4a95cba77", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers"}, "hash": "46f4e8a1057b233d3b6725b9caa7f1e6ac4055f5d0f6ced502145eab486ac70d", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "bf70c751-eaf1-461d-a6d3-4ce22611aff7", "node_type": "1", "metadata": {}, "hash": "88476ff75c52c41a13390e4d1645b6bf50bc75b63a8097f11c4754d11ced2406", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 14130, "end_char_idx": 16343, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
You can manually use a tool by calling the [`load_tool`] function and a task to perform.


```python
from transformers import load_tool

tool = load_tool("text-to-speech")
audio = tool("This is a text to speech tool")
```


### Create a new tool

You can create your own tool for use cases not covered by the default tools from Hugging Face.
For example, let's create a tool that returns the most downloaded model for a given task from the Hub.

You'll start with the code below.

```python
from huggingface_hub import list_models

task = "text-classification"

model = next(iter(list_models(filter=task, sort="downloads", direction=-1)))
print(model.id)
```

This code can be converted into a class that inherits from the [`Tool`] superclass.


The custom tool needs:
- An attribute `name`, which corresponds to the name of the tool itself. The name usually describes what the tool does. Since the code returns the model with the most downloads for a task, let's name is `model_download_counter`.
- An attribute `description` is used to populate the agent's system prompt.
- An `inputs` attribute, which is a dictionary with keys `"type"` and `"description"`. It contains information that helps the Python interpreter make educated choices about the input.
- An `output_type` attribute, which specifies the output type.
- A `forward` method which contains the inference code to be executed.


```python
from transformers import Tool
from huggingface_hub import list_models

class HFModelDownloadsTool(Tool):
    name = "model_download_counter"
    description = (
        "This is a tool that returns the most downloaded model of a given task on the Hugging Face Hub. "
        "It returns the name of the checkpoint."
    )

    inputs = {
        "task": {
            "type": "text",
            "description": "the task category (such as text-classification, depth-estimation, etc)",
        }
    }
    output_type = "text"

    def forward(self, task: str):
        model = next(iter(list_models(filter=task, sort="downloads", direction=-1)))
        return model.id
```

Now that the custom `HfModelDownloadsTool` class is ready, you can save it to a file named `model_downloads.py` and import it for use.


key: _node_content
string_value:
{"id_": "bf70c751-eaf1-461d-a6d3-4ce22611aff7", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "1c0c2e70-0214-4869-b53f-874503acf230", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers"}, "hash": "3c4db41f215ae561c744c2ae863968a76be548ad4988ec72355258e6160a8050", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "befcdcbc-cd6a-4870-9fda-d0795ede876d", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers"}, "hash": "f57a82eb2944acac28d7c71b3c68d70c2909913440b35d01e27a51193bd19aaa", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "d46cb6b6-acf3-4f1e-982b-d370ecbc06f8", "node_type": "1", "metadata": {}, "hash": "b135bc356bee18b528c1d4046da4f95d0702bda3910087f66f1b092548c14379", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 14876, "end_char_idx": 17635, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
The custom tool needs:
- An attribute `name`, which corresponds to the name of the tool itself. The name usually describes what the tool does. Since the code returns the model with the most downloads for a task, let's name is `model_download_counter`.
- An attribute `description` is used to populate the agent's system prompt.
- An `inputs` attribute, which is a dictionary with keys `"type"` and `"description"`. It contains information that helps the Python interpreter make educated choices about the input.
- An `output_type` attribute, which specifies the output type.
- A `forward` method which contains the inference code to be executed.


```python
from transformers import Tool
from huggingface_hub import list_models

class HFModelDownloadsTool(Tool):
    name = "model_download_counter"
    description = (
        "This is a tool that returns the most downloaded model of a given task on the Hugging Face Hub. "
        "It returns the name of the checkpoint."
    )

    inputs = {
        "task": {
            "type": "text",
            "description": "the task category (such as text-classification, depth-estimation, etc)",
        }
    }
    output_type = "text"

    def forward(self, task: str):
        model = next(iter(list_models(filter=task, sort="downloads", direction=-1)))
        return model.id
```

Now that the custom `HfModelDownloadsTool` class is ready, you can save it to a file named `model_downloads.py` and import it for use.


```python
from model_downloads import HFModelDownloadsTool

tool = HFModelDownloadsTool()
```

You can also share your custom tool to the Hub by calling [`~Tool.push_to_hub`] on the tool. Make sure you've created a repository for it on the Hub and are using a token with read access.

```python
tool.push_to_hub("{your_username}/hf-model-downloads")
```

Load the tool with the [`~Tool.load_tool`] function and pass it to the `tools` parameter in your agent.

```python
from transformers import load_tool, CodeAgent

model_download_tool = load_tool("m-ric/hf-model-downloads")
agent = CodeAgent(tools=[model_download_tool], llm_engine=llm_engine)
agent.run(
    "Can you give me the name of the model that has the most downloads in the 'text-to-video' task on the Hugging Face Hub?"
)
```

You get the following:
```text
======== New task ========
Can you give me the name of the model that has the most downloads in the 'text-to-video' task on the Hugging Face Hub?
==== Agent is executing the code below:
most_downloaded_model = model_download_counter(task="text-to-video")
print(f"The most downloaded model for the 'text-to-video' task is {most_downloaded_model}.")
====
```

And the output:
`"The most downloaded model for the 'text-to-video' task is ByteDance/AnimateDiff-Lightning."`


key: _node_content
string_value:
{"id_": "d46cb6b6-acf3-4f1e-982b-d370ecbc06f8", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "1c0c2e70-0214-4869-b53f-874503acf230", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers"}, "hash": "3c4db41f215ae561c744c2ae863968a76be548ad4988ec72355258e6160a8050", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "bf70c751-eaf1-461d-a6d3-4ce22611aff7", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers"}, "hash": "65211203ec8a8007c69de014253072d3562478c05246889783bec97b9c8bbfd2", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "e161650d-62d7-4802-a049-e42baf3b9a35", "node_type": "1", "metadata": {}, "hash": "2c8c16a8a1470e35526a92a91bcbb35c86b892c3738273e1aecd3a7ec652c881", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 16346, "end_char_idx": 19459, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
from model_downloads import HFModelDownloadsTool

tool = HFModelDownloadsTool()
```

You can also share your custom tool to the Hub by calling [`~Tool.push_to_hub`] on the tool. Make sure you've created a repository for it on the Hub and are using a token with read access.

```python
tool.push_to_hub("{your_username}/hf-model-downloads")
```

Load the tool with the [`~Tool.load_tool`] function and pass it to the `tools` parameter in your agent.

```python
from transformers import load_tool, CodeAgent

model_download_tool = load_tool("m-ric/hf-model-downloads")
agent = CodeAgent(tools=[model_download_tool], llm_engine=llm_engine)
agent.run(
    "Can you give me the name of the model that has the most downloads in the 'text-to-video' task on the Hugging Face Hub?"
)
```

You get the following:
```text
======== New task ========
Can you give me the name of the model that has the most downloads in the 'text-to-video' task on the Hugging Face Hub?
==== Agent is executing the code below:
most_downloaded_model = model_download_counter(task="text-to-video")
print(f"The most downloaded model for the 'text-to-video' task is {most_downloaded_model}.")
====
```

And the output:
`"The most downloaded model for the 'text-to-video' task is ByteDance/AnimateDiff-Lightning."`


### Manage your agent's toolbox

If you have already initialized an agent, it is inconvenient to reinitialize it from scratch with a tool you want to use. With Transformers, you can manage an agent's toolbox by adding or replacing a tool.

Let's add the `model_download_tool` to an existing agent initialized with only the default toolbox.

```python
from transformers import CodeAgent

agent = CodeAgent(tools=[], llm_engine=llm_engine, add_base_tools=True)
agent.toolbox.add_tool(model_download_tool)
```
Now we can leverage both the new tool and the previous text-to-speech tool:

```python
agent.run(
    "Can you read out loud the name of the model that has the most downloads in the 'text-to-video' task on the Hugging Face Hub and return the audio?"
)
```


| **Audio**                                                                                                                                            |
|------------------------------------------------------------------------------------------------------------------------------------------------------|
| <audio controls><source src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/damo.wav" type="audio/wav"/> |


> [!WARNING]
> Beware when adding tools to an agent that already works well because it can bias selection towards your tool or select another tool other than the one already defined.


Use the `agent.toolbox.update_tool()` method to replace an existing tool in the agent's toolbox.
This is useful if your new tool is a one-to-one replacement of the existing tool because the agent already knows how to perform that specific task.
Just make sure the new tool follows the same API as the replaced tool or adapt the system prompt template to ensure all examples using the replaced tool are updated.


key: _node_content
string_value:
{"id_": "e161650d-62d7-4802-a049-e42baf3b9a35", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "1c0c2e70-0214-4869-b53f-874503acf230", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers"}, "hash": "3c4db41f215ae561c744c2ae863968a76be548ad4988ec72355258e6160a8050", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "d46cb6b6-acf3-4f1e-982b-d370ecbc06f8", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers"}, "hash": "7cb9230d0a21e7ae1d8c1d64b041b11d2ad87a71ab60e71728b226cbf8cea4dc", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "5c03b3ca-989d-404f-af61-51d97529e407", "node_type": "1", "metadata": {}, "hash": "b62fb82e1bdbd6ed7f0ddd97846387ecc4e088ee0ea82873ccaf71b598459f8e", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 17638, "end_char_idx": 20232, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
### Manage your agent's toolbox

If you have already initialized an agent, it is inconvenient to reinitialize it from scratch with a tool you want to use. With Transformers, you can manage an agent's toolbox by adding or replacing a tool.

Let's add the `model_download_tool` to an existing agent initialized with only the default toolbox.

```python
from transformers import CodeAgent

agent = CodeAgent(tools=[], llm_engine=llm_engine, add_base_tools=True)
agent.toolbox.add_tool(model_download_tool)
```
Now we can leverage both the new tool and the previous text-to-speech tool:

```python
agent.run(
    "Can you read out loud the name of the model that has the most downloads in the 'text-to-video' task on the Hugging Face Hub and return the audio?"
)
```


| **Audio**                                                                                                                                            |
|------------------------------------------------------------------------------------------------------------------------------------------------------|
| <audio controls><source src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/damo.wav" type="audio/wav"/> |


> [!WARNING]
> Beware when adding tools to an agent that already works well because it can bias selection towards your tool or select another tool other than the one already defined.


Use the `agent.toolbox.update_tool()` method to replace an existing tool in the agent's toolbox.
This is useful if your new tool is a one-to-one replacement of the existing tool because the agent already knows how to perform that specific task.
Just make sure the new tool follows the same API as the replaced tool or adapt the system prompt template to ensure all examples using the replaced tool are updated.


### Use a collection of tools

You can leverage tool collections by using the ToolCollection object, with the slug of the collection you want to use.
Then pass them as a list to initialize you agent, and start using them!

```py
from transformers import ToolCollection, ReactCodeAgent

image_tool_collection = ToolCollection(collection_slug="huggingface-tools/diffusion-tools-6630bb19a942c2306a2cdb6f")
agent = ReactCodeAgent(tools=[*image_tool_collection.tools], add_base_tools=True)

agent.run("Please draw me a picture of rivers and lakes.")
```

To speed up the start, tools are loaded only if called by the agent.

This gets you this image:

<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/rivers_and_lakes.png">


key: _node_content
string_value:
{"id_": "5c03b3ca-989d-404f-af61-51d97529e407", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "1c0c2e70-0214-4869-b53f-874503acf230", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers"}, "hash": "3c4db41f215ae561c744c2ae863968a76be548ad4988ec72355258e6160a8050", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "e161650d-62d7-4802-a049-e42baf3b9a35", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers"}, "hash": "ebaf60a29b68f89d9b47de7cadad67bce49b22bf1743eef4bdef5180791ca0a2", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "a719172d-8d54-423c-9146-e8d835007b9c", "node_type": "1", "metadata": {}, "hash": "c52582f0ab502898913258573e0d52cfa28289fd6acbedd3444c6874bc0e9e46", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 18403, "end_char_idx": 22217, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
| **Audio**                                                                                                                                            |
|------------------------------------------------------------------------------------------------------------------------------------------------------|
| <audio controls><source src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/damo.wav" type="audio/wav"/> |


> [!WARNING]
> Beware when adding tools to an agent that already works well because it can bias selection towards your tool or select another tool other than the one already defined.


Use the `agent.toolbox.update_tool()` method to replace an existing tool in the agent's toolbox.
This is useful if your new tool is a one-to-one replacement of the existing tool because the agent already knows how to perform that specific task.
Just make sure the new tool follows the same API as the replaced tool or adapt the system prompt template to ensure all examples using the replaced tool are updated.


### Use a collection of tools

You can leverage tool collections by using the ToolCollection object, with the slug of the collection you want to use.
Then pass them as a list to initialize you agent, and start using them!

```py
from transformers import ToolCollection, ReactCodeAgent

image_tool_collection = ToolCollection(collection_slug="huggingface-tools/diffusion-tools-6630bb19a942c2306a2cdb6f")
agent = ReactCodeAgent(tools=[*image_tool_collection.tools], add_base_tools=True)

agent.run("Please draw me a picture of rivers and lakes.")
```

To speed up the start, tools are loaded only if called by the agent.

This gets you this image:

<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/rivers_and_lakes.png">


### Use gradio-tools

[gradio-tools](https://github.com/freddyaboulton/gradio-tools) is a powerful library that allows using Hugging
Face Spaces as tools. It supports many existing Spaces as well as custom Spaces.

Transformers supports `gradio_tools` with the [`Tool.from_gradio`] method. For example, let's use the [`StableDiffusionPromptGeneratorTool`](https://github.com/freddyaboulton/gradio-tools/blob/main/gradio_tools/tools/prompt_generator.py) from `gradio-tools` toolkit for improving prompts to generate better images.

Import and instantiate the tool, then pass it to the `Tool.from_gradio` method:

```python
from gradio_tools import StableDiffusionPromptGeneratorTool
from transformers import Tool, load_tool, CodeAgent

gradio_prompt_generator_tool = StableDiffusionPromptGeneratorTool()
prompt_generator_tool = Tool.from_gradio(gradio_prompt_generator_tool)
```

Now you can use it just like any other tool. For example, let's improve the prompt  `a rabbit wearing a space suit`.

```python
image_generation_tool = load_tool('huggingface-tools/text-to-image')
agent = CodeAgent(tools=[prompt_generator_tool, image_generation_tool], llm_engine=llm_engine)

agent.run(
    "Improve this prompt, then generate an image of it.", prompt='A rabbit wearing a space suit'
)
```

The model adequately leverages the tool:
```text
======== New task ========
Improve this prompt, then generate an image of it.
You have been provided with these initial arguments: {'prompt': 'A rabbit wearing a space suit'}.
==== Agent is executing the code below:
improved_prompt = StableDiffusionPromptGenerator(query=prompt)
while improved_prompt == "QUEUE_FULL":
    improved_prompt = StableDiffusionPromptGenerator(query=prompt)
print(f"The improved prompt is {improved_prompt}.")
image = image_generator(prompt=improved_prompt)
====
```

Before finally generating the image:

<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/rabbit.png">


key: _node_content
string_value:
{"id_": "a719172d-8d54-423c-9146-e8d835007b9c", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "1c0c2e70-0214-4869-b53f-874503acf230", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers"}, "hash": "3c4db41f215ae561c744c2ae863968a76be548ad4988ec72355258e6160a8050", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "5c03b3ca-989d-404f-af61-51d97529e407", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/agents", "title": "Agents and tools", "tokens": 5612, "retrieve_doc": true, "source": "transformers"}, "hash": "dddbe7e9f4a3fe4987110aa5b1e8254a8a4284bfd03754981ae869fad4dd525a", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 22220, "end_char_idx": 24452, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
> [!WARNING]
> gradio-tools require *textual* inputs and outputs even when working with different modalities like image and audio objects. Image and audio inputs and outputs are currently incompatible.

### Use LangChain tools

We love Langchain and think it has a very compelling suite of tools.
To import a tool from LangChain, use the `from_langchain()` method.

Here is how you can use it to recreate the intro's search result using a LangChain web search tool.

```python
from langchain.agents import load_tools
from transformers import Tool, ReactCodeAgent

search_tool = Tool.from_langchain(load_tools(["serpapi"])[0])

agent = ReactCodeAgent(tools=[search_tool])

agent.run("How many more blocks (also denoted as layers) in BERT base encoder than the encoder from the architecture proposed in Attention is All You Need?")
```

## Gradio interface

You can leverage `gradio.Chatbot`to display your agent's thoughts using `stream_to_gradio`, here is an example:

```py
import gradio as gr
from transformers import (
    load_tool,
    ReactCodeAgent,
    HfEngine,
    stream_to_gradio,
)

# Import tool from Hub
image_generation_tool = load_tool("m-ric/text-to-image")

llm_engine = HfEngine("meta-llama/Meta-Llama-3-70B-Instruct")

# Initialize the agent with the image generation tool
agent = ReactCodeAgent(tools=[image_generation_tool], llm_engine=llm_engine)


def interact_with_agent(task):
    messages = []
    messages.append(gr.ChatMessage(role="user", content=task))
    yield messages
    for msg in stream_to_gradio(agent, task):
        messages.append(msg)
        yield messages + [
            gr.ChatMessage(role="assistant", content="⏳ Task not finished yet!")
        ]
    yield messages


with gr.Blocks() as demo:
    text_input = gr.Textbox(lines=1, label="Chat Message", value="Make me a picture of the Statue of Liberty.")
    submit = gr.Button("Run illustrator agent!")
    chatbot = gr.Chatbot(
        label="Agent",
        type="messages",
        avatar_images=(
            None,
            "https://em-content.zobj.net/source/twitter/53/robot-face_1f916.png",
        ),
    )
    submit.click(interact_with_agent, [text_input], [chatbot])

if __name__ == "__main__":
    demo.launch()
```


key: _node_content
string_value:
{"id_": "911e88e9-7449-4da9-b721-8eb3ac97debd", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/philosophy", "title": "Philosophy", "tokens": 1289, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "69bbd021-3897-49b6-960b-126ed07d82f5", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/philosophy", "title": "Philosophy", "tokens": 1289, "retrieve_doc": true, "source": "transformers"}, "hash": "4983a475d3ab0a23ac72363becda0b29a8e21c1d3851ad40ab1f87acbe8b622f", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "724d0800-7a7d-47ba-8548-3fb6ffc5fbc1", "node_type": "1", "metadata": {}, "hash": "6b282abe1fdaeab27847be3c03cf5c9f5af417d1ff98b5cc7d7500ce718b05e3", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 3305, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# Philosophy

🤗 Transformers is an opinionated library built for:

- machine learning researchers and educators seeking to use, study or extend large-scale Transformers models.
- hands-on practitioners who want to fine-tune those models or serve them in production, or both.
- engineers who just want to download a pretrained model and use it to solve a given machine learning task.

The library was designed with two strong goals in mind:

1. Be as easy and fast to use as possible:

  - We strongly limited the number of user-facing abstractions to learn, in fact, there are almost no abstractions,
    just three standard classes required to use each model: [configuration](main_classes/configuration),
    [models](main_classes/model), and a preprocessing class ([tokenizer](main_classes/tokenizer) for NLP, [image processor](main_classes/image_processor) for vision, [feature extractor](main_classes/feature_extractor) for audio, and [processor](main_classes/processors) for multimodal inputs).
  - All of these classes can be initialized in a simple and unified way from pretrained instances by using a common
    `from_pretrained()` method which downloads (if needed), caches and
    loads the related class instance and associated data (configurations' hyperparameters, tokenizers' vocabulary,
    and models' weights) from a pretrained checkpoint provided on [Hugging Face Hub](https://huggingface.co/models) or your own saved checkpoint.
  - On top of those three base classes, the library provides two APIs: [`pipeline`] for quickly
    using a model for inference on a given task and [`Trainer`] to quickly train or fine-tune a PyTorch model (all TensorFlow models are compatible with `Keras.fit`).
  - As a consequence, this library is NOT a modular toolbox of building blocks for neural nets. If you want to
    extend or build upon the library, just use regular Python, PyTorch, TensorFlow, Keras modules and inherit from the base
    classes of the library to reuse functionalities like model loading and saving. If you'd like to learn more about our coding philosophy for models, check out our [Repeat Yourself](https://huggingface.co/blog/transformers-design-philosophy) blog post.

2. Provide state-of-the-art models with performances as close as possible to the original models:

  - We provide at least one example for each architecture which reproduces a result provided by the official authors
    of said architecture.
  - The code is usually as close to the original code base as possible which means some PyTorch code may be not as
    *pytorchic* as it could be as a result of being converted TensorFlow code and vice versa.

A few other goals:

- Expose the models' internals as consistently as possible:

  - We give access, using a single API, to the full hidden-states and attention weights.
  - The preprocessing classes and base model APIs are standardized to easily switch between models.

- Incorporate a subjective selection of promising tools for fine-tuning and investigating these models:

  - A simple and consistent way to add new tokens to the vocabulary and embeddings for fine-tuning.
  - Simple ways to mask and prune Transformer heads.

- Easily switch between PyTorch, TensorFlow 2.0 and Flax, allowing training with one framework and inference with another.


key: _node_content
string_value:
{"id_": "724d0800-7a7d-47ba-8548-3fb6ffc5fbc1", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/philosophy", "title": "Philosophy", "tokens": 1289, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "69bbd021-3897-49b6-960b-126ed07d82f5", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/philosophy", "title": "Philosophy", "tokens": 1289, "retrieve_doc": true, "source": "transformers"}, "hash": "4983a475d3ab0a23ac72363becda0b29a8e21c1d3851ad40ab1f87acbe8b622f", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "911e88e9-7449-4da9-b721-8eb3ac97debd", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/philosophy", "title": "Philosophy", "tokens": 1289, "retrieve_doc": true, "source": "transformers"}, "hash": "fc8a9d35635f59b8774892de5f6f41aadbb50cd816d2ba2a0b2850555c2288a0", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "e59aabf3-4d74-4b41-8299-6af54d91eab0", "node_type": "1", "metadata": {}, "hash": "b5e72fff8aaaa7dee0ec177f6f1691305ae94d5e91286918e78e74a15032e1ec", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 1450, "end_char_idx": 5068, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
- On top of those three base classes, the library provides two APIs: [`pipeline`] for quickly
    using a model for inference on a given task and [`Trainer`] to quickly train or fine-tune a PyTorch model (all TensorFlow models are compatible with `Keras.fit`).
  - As a consequence, this library is NOT a modular toolbox of building blocks for neural nets. If you want to
    extend or build upon the library, just use regular Python, PyTorch, TensorFlow, Keras modules and inherit from the base
    classes of the library to reuse functionalities like model loading and saving. If you'd like to learn more about our coding philosophy for models, check out our [Repeat Yourself](https://huggingface.co/blog/transformers-design-philosophy) blog post.

2. Provide state-of-the-art models with performances as close as possible to the original models:

  - We provide at least one example for each architecture which reproduces a result provided by the official authors
    of said architecture.
  - The code is usually as close to the original code base as possible which means some PyTorch code may be not as
    *pytorchic* as it could be as a result of being converted TensorFlow code and vice versa.

A few other goals:

- Expose the models' internals as consistently as possible:

  - We give access, using a single API, to the full hidden-states and attention weights.
  - The preprocessing classes and base model APIs are standardized to easily switch between models.

- Incorporate a subjective selection of promising tools for fine-tuning and investigating these models:

  - A simple and consistent way to add new tokens to the vocabulary and embeddings for fine-tuning.
  - Simple ways to mask and prune Transformer heads.

- Easily switch between PyTorch, TensorFlow 2.0 and Flax, allowing training with one framework and inference with another.

## Main concepts

The library is built around three types of classes for each model:

- **Model classes** can be PyTorch models ([torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)), Keras models ([tf.keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model)) or JAX/Flax models ([flax.linen.Module](https://flax.readthedocs.io/en/latest/api_reference/flax.linen/module.html)) that work with the pretrained weights provided in the library.
- **Configuration classes** store the hyperparameters required to build a model (such as the number of layers and hidden size). You don't always need to instantiate these yourself. In particular, if you are using a pretrained model without any modification, creating the model will automatically take care of instantiating the configuration (which is part of the model).
- **Preprocessing classes** convert the raw data into a format accepted by the model. A [tokenizer](main_classes/tokenizer) stores the vocabulary for each model and provide methods for encoding and decoding strings in a list of token embedding indices to be fed to a model. [Image processors](main_classes/image_processor) preprocess vision inputs, [feature extractors](main_classes/feature_extractor) preprocess audio inputs, and a [processor](main_classes/processors) handles multimodal inputs.

All these classes can be instantiated from pretrained instances, saved locally, and shared on the Hub with three methods:

- `from_pretrained()` lets you instantiate a model, configuration, and preprocessing class from a pretrained version either
  provided by the library itself (the supported models can be found on the [Model Hub](https://huggingface.co/models)) or
  stored locally (or on a server) by the user.


key: _node_content
string_value:
{"id_": "e59aabf3-4d74-4b41-8299-6af54d91eab0", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/philosophy", "title": "Philosophy", "tokens": 1289, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "69bbd021-3897-49b6-960b-126ed07d82f5", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/philosophy", "title": "Philosophy", "tokens": 1289, "retrieve_doc": true, "source": "transformers"}, "hash": "4983a475d3ab0a23ac72363becda0b29a8e21c1d3851ad40ab1f87acbe8b622f", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "724d0800-7a7d-47ba-8548-3fb6ffc5fbc1", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/philosophy", "title": "Philosophy", "tokens": 1289, "retrieve_doc": true, "source": "transformers"}, "hash": "49d6ea5744e2f03094dba0f410c1a455dcc95dad84a5836d3dd241892f432956", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 3307, "end_char_idx": 5351, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
## Main concepts

The library is built around three types of classes for each model:

- **Model classes** can be PyTorch models ([torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)), Keras models ([tf.keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model)) or JAX/Flax models ([flax.linen.Module](https://flax.readthedocs.io/en/latest/api_reference/flax.linen/module.html)) that work with the pretrained weights provided in the library.
- **Configuration classes** store the hyperparameters required to build a model (such as the number of layers and hidden size). You don't always need to instantiate these yourself. In particular, if you are using a pretrained model without any modification, creating the model will automatically take care of instantiating the configuration (which is part of the model).
- **Preprocessing classes** convert the raw data into a format accepted by the model. A [tokenizer](main_classes/tokenizer) stores the vocabulary for each model and provide methods for encoding and decoding strings in a list of token embedding indices to be fed to a model. [Image processors](main_classes/image_processor) preprocess vision inputs, [feature extractors](main_classes/feature_extractor) preprocess audio inputs, and a [processor](main_classes/processors) handles multimodal inputs.

All these classes can be instantiated from pretrained instances, saved locally, and shared on the Hub with three methods:

- `from_pretrained()` lets you instantiate a model, configuration, and preprocessing class from a pretrained version either
  provided by the library itself (the supported models can be found on the [Model Hub](https://huggingface.co/models)) or
  stored locally (or on a server) by the user.
- `save_pretrained()` lets you save a model, configuration, and preprocessing class locally so that it can be reloaded using
  `from_pretrained()`.
- `push_to_hub()` lets you share a model, configuration, and a preprocessing class to the Hub, so it is easily accessible to everyone.


key: _node_content
string_value:
{"id_": "3a69fa31-c1f5-4b84-990d-de400039520e", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/add_new_pipeline", "title": "How to create a custom pipeline?", "tokens": 2459, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "12eaf971-4b8a-42e8-a00c-b9efcc38a687", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/add_new_pipeline", "title": "How to create a custom pipeline?", "tokens": 2459, "retrieve_doc": true, "source": "transformers"}, "hash": "dfc723367cd5a652da183b279025448c9e43e96dcb711ddab3229f7038b46a09", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "eb8869e4-62d6-44e1-966a-1cf715e6d530", "node_type": "1", "metadata": {}, "hash": "4df29ee53ebefe7dd4e6d4cfe2a526e8f13c5186113c82817fdfa82629878812", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 891, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# How to create a custom pipeline?

In this guide, we will see how to create a custom pipeline and share it on the [Hub](https://hf.co/models) or add it to the
🤗 Transformers library.

First and foremost, you need to decide the raw entries the pipeline will be able to take. It can be strings, raw bytes,
dictionaries or whatever seems to be the most likely desired input. Try to keep these inputs as pure Python as possible
as it makes compatibility easier (even through other languages via JSON). Those will be the `inputs` of the
pipeline (`preprocess`).

Then define the `outputs`. Same policy as the `inputs`. The simpler, the better. Those will be the outputs of
`postprocess` method.

Start by inheriting the base class `Pipeline` with the 4 methods needed to implement `preprocess`,
`_forward`, `postprocess`, and `_sanitize_parameters`.


```python
from transformers import Pipeline


key: _node_content
string_value:
{"id_": "eb8869e4-62d6-44e1-966a-1cf715e6d530", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/add_new_pipeline", "title": "How to create a custom pipeline?", "tokens": 2459, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "12eaf971-4b8a-42e8-a00c-b9efcc38a687", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/add_new_pipeline", "title": "How to create a custom pipeline?", "tokens": 2459, "retrieve_doc": true, "source": "transformers"}, "hash": "dfc723367cd5a652da183b279025448c9e43e96dcb711ddab3229f7038b46a09", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "3a69fa31-c1f5-4b84-990d-de400039520e", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/add_new_pipeline", "title": "How to create a custom pipeline?", "tokens": 2459, "retrieve_doc": true, "source": "transformers"}, "hash": "5a1bdc5dc9e62136184136e5608d98b7799e6c70c34a6be289716d73f4b98552", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "30426ae9-fe62-43ff-979f-df5d592a3253", "node_type": "1", "metadata": {}, "hash": "3ad1db1736d739b5537e5f409aee2129ce00d29d385af562a6e308d11cfa206b", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 3544, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# How to create a custom pipeline?

In this guide, we will see how to create a custom pipeline and share it on the [Hub](https://hf.co/models) or add it to the
🤗 Transformers library.

First and foremost, you need to decide the raw entries the pipeline will be able to take. It can be strings, raw bytes,
dictionaries or whatever seems to be the most likely desired input. Try to keep these inputs as pure Python as possible
as it makes compatibility easier (even through other languages via JSON). Those will be the `inputs` of the
pipeline (`preprocess`).

Then define the `outputs`. Same policy as the `inputs`. The simpler, the better. Those will be the outputs of
`postprocess` method.

Start by inheriting the base class `Pipeline` with the 4 methods needed to implement `preprocess`,
`_forward`, `postprocess`, and `_sanitize_parameters`.


```python
from transformers import Pipeline


class MyPipeline(Pipeline):
    def _sanitize_parameters(self, **kwargs):
        preprocess_kwargs = {}
        if "maybe_arg" in kwargs:
            preprocess_kwargs["maybe_arg"] = kwargs["maybe_arg"]
        return preprocess_kwargs, {}, {}

    def preprocess(self, inputs, maybe_arg=2):
        model_input = Tensor(inputs["input_ids"])
        return {"model_input": model_input}

    def _forward(self, model_inputs):
        # model_inputs == {"model_input": model_input}
        outputs = self.model(**model_inputs)
        # Maybe {"logits": Tensor(...)}
        return outputs

    def postprocess(self, model_outputs):
        best_class = model_outputs["logits"].softmax(-1)
        return best_class
```

The structure of this breakdown is to support relatively seamless support for CPU/GPU, while supporting doing
pre/postprocessing on the CPU on different threads

`preprocess` will take the originally defined inputs, and turn them into something feedable to the model. It might
contain more information and is usually a `Dict`.

`_forward` is the implementation detail and is not meant to be called directly. `forward` is the preferred
called method as it contains safeguards to make sure everything is working on the expected device. If anything is
linked to a real model it belongs in the `_forward` method, anything else is in the preprocess/postprocess.

`postprocess` methods will take the output of `_forward` and turn it into the final output that was decided
earlier.

`_sanitize_parameters` exists to allow users to pass any parameters whenever they wish, be it at initialization
time `pipeline(...., maybe_arg=4)` or at call time `pipe = pipeline(...); output = pipe(...., maybe_arg=4)`.

The returns of `_sanitize_parameters` are the 3 dicts of kwargs that will be passed directly to `preprocess`,
`_forward`, and `postprocess`. Don't fill anything if the caller didn't call with any extra parameter. That
allows to keep the default arguments in the function definition which is always more "natural".

A classic example would be a `top_k` argument in the post processing in classification tasks.

```python
>>> pipe = pipeline("my-new-task")
>>> pipe("This is a test")
[{"label": "1-star", "score": 0.8}, {"label": "2-star", "score": 0.1}, {"label": "3-star", "score": 0.05}
{"label": "4-star", "score": 0.025}, {"label": "5-star", "score": 0.025}]

>>> pipe("This is a test", top_k=2)
[{"label": "1-star", "score": 0.8}, {"label": "2-star", "score": 0.1}]
```

In order to achieve that, we'll update our `postprocess` method with a default parameter to `5`. and edit
`_sanitize_parameters` to allow this new parameter.


key: _node_content
string_value:
{"id_": "30426ae9-fe62-43ff-979f-df5d592a3253", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/add_new_pipeline", "title": "How to create a custom pipeline?", "tokens": 2459, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "12eaf971-4b8a-42e8-a00c-b9efcc38a687", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/add_new_pipeline", "title": "How to create a custom pipeline?", "tokens": 2459, "retrieve_doc": true, "source": "transformers"}, "hash": "dfc723367cd5a652da183b279025448c9e43e96dcb711ddab3229f7038b46a09", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "eb8869e4-62d6-44e1-966a-1cf715e6d530", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/add_new_pipeline", "title": "How to create a custom pipeline?", "tokens": 2459, "retrieve_doc": true, "source": "transformers"}, "hash": "b8003103246d4f67904e3849182ba389cb80620b3d4c6ed4dc900f6b92d848ec", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "64fed5eb-7799-4f92-8aaa-5c9bcba8e73e", "node_type": "1", "metadata": {}, "hash": "645742bf4165fdef73410a9af72f609f053bf3891fc91390c816e280edcd69fa", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 3547, "end_char_idx": 6671, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```python
def postprocess(self, model_outputs, top_k=5):
    best_class = model_outputs["logits"].softmax(-1)
    # Add logic to handle top_k
    return best_class


def _sanitize_parameters(self, **kwargs):
    preprocess_kwargs = {}
    if "maybe_arg" in kwargs:
        preprocess_kwargs["maybe_arg"] = kwargs["maybe_arg"]

    postprocess_kwargs = {}
    if "top_k" in kwargs:
        postprocess_kwargs["top_k"] = kwargs["top_k"]
    return preprocess_kwargs, {}, postprocess_kwargs
```

Try to keep the inputs/outputs very simple and ideally JSON-serializable as it makes the pipeline usage very easy
without requiring users to understand new kinds of objects. It's also relatively common to support many different types
of arguments for ease of use (audio files, which can be filenames, URLs or pure bytes)



## Adding it to the list of supported tasks

To register your `new-task` to the list of supported tasks, you have to add it to the `PIPELINE_REGISTRY`:

```python
from transformers.pipelines import PIPELINE_REGISTRY

PIPELINE_REGISTRY.register_pipeline(
    "new-task",
    pipeline_class=MyPipeline,
    pt_model=AutoModelForSequenceClassification,
)
```

You can specify a default model if you want, in which case it should come with a specific revision (which can be the name of a branch or a commit hash, here we took `"abcdef"`) as well as the type:

```python
PIPELINE_REGISTRY.register_pipeline(
    "new-task",
    pipeline_class=MyPipeline,
    pt_model=AutoModelForSequenceClassification,
    default={"pt": ("user/awesome_model", "abcdef")},
    type="text",  # current support type: text, audio, image, multimodal
)
```

## Share your pipeline on the Hub

To share your custom pipeline on the Hub, you just have to save the custom code of your `Pipeline` subclass in a
python file. For instance, let's say we want to use a custom pipeline for sentence pair classification like this:

```py
import numpy as np

from transformers import Pipeline


def softmax(outputs):
    maxes = np.max(outputs, axis=-1, keepdims=True)
    shifted_exp = np.exp(outputs - maxes)
    return shifted_exp / shifted_exp.sum(axis=-1, keepdims=True)


class PairClassificationPipeline(Pipeline):
    def _sanitize_parameters(self, **kwargs):
        preprocess_kwargs = {}
        if "second_text" in kwargs:
            preprocess_kwargs["second_text"] = kwargs["second_text"]
        return preprocess_kwargs, {}, {}

    def preprocess(self, text, second_text=None):
        return self.tokenizer(text, text_pair=second_text, return_tensors=self.framework)

    def _forward(self, model_inputs):
        return self.model(**model_inputs)

    def postprocess(self, model_outputs):
        logits = model_outputs.logits[0].numpy()
        probabilities = softmax(logits)

        best_class = np.argmax(probabilities)
        label = self.model.config.id2label[best_class]
        score = probabilities[best_class].item()
        logits = logits.tolist()
        return {"label": label, "score": score, "logits": logits}
```

The implementation is framework agnostic, and will work for PyTorch and TensorFlow models.


key: _node_content
string_value:
{"id_": "64fed5eb-7799-4f92-8aaa-5c9bcba8e73e", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/add_new_pipeline", "title": "How to create a custom pipeline?", "tokens": 2459, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "12eaf971-4b8a-42e8-a00c-b9efcc38a687", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/add_new_pipeline", "title": "How to create a custom pipeline?", "tokens": 2459, "retrieve_doc": true, "source": "transformers"}, "hash": "dfc723367cd5a652da183b279025448c9e43e96dcb711ddab3229f7038b46a09", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "30426ae9-fe62-43ff-979f-df5d592a3253", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/add_new_pipeline", "title": "How to create a custom pipeline?", "tokens": 2459, "retrieve_doc": true, "source": "transformers"}, "hash": "e444a6e1d042f7840ac54f752aa59c8816da1b113c21883faacd20b643982387", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "13b0f9dd-82e7-4700-8633-7a81aa876e01", "node_type": "1", "metadata": {}, "hash": "0109fa6cdc0dc26448456cb225bc2491261baa4645be00eadc10cd95393cd269", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 5522, "end_char_idx": 8897, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
def softmax(outputs):
    maxes = np.max(outputs, axis=-1, keepdims=True)
    shifted_exp = np.exp(outputs - maxes)
    return shifted_exp / shifted_exp.sum(axis=-1, keepdims=True)


class PairClassificationPipeline(Pipeline):
    def _sanitize_parameters(self, **kwargs):
        preprocess_kwargs = {}
        if "second_text" in kwargs:
            preprocess_kwargs["second_text"] = kwargs["second_text"]
        return preprocess_kwargs, {}, {}

    def preprocess(self, text, second_text=None):
        return self.tokenizer(text, text_pair=second_text, return_tensors=self.framework)

    def _forward(self, model_inputs):
        return self.model(**model_inputs)

    def postprocess(self, model_outputs):
        logits = model_outputs.logits[0].numpy()
        probabilities = softmax(logits)

        best_class = np.argmax(probabilities)
        label = self.model.config.id2label[best_class]
        score = probabilities[best_class].item()
        logits = logits.tolist()
        return {"label": label, "score": score, "logits": logits}
```

The implementation is framework agnostic, and will work for PyTorch and TensorFlow models. If we have saved this in
a file named `pair_classification.py`, we can then import it and register it like this:

```py
from pair_classification import PairClassificationPipeline
from transformers.pipelines import PIPELINE_REGISTRY
from transformers import AutoModelForSequenceClassification, TFAutoModelForSequenceClassification

PIPELINE_REGISTRY.register_pipeline(
    "pair-classification",
    pipeline_class=PairClassificationPipeline,
    pt_model=AutoModelForSequenceClassification,
    tf_model=TFAutoModelForSequenceClassification,
)
```

Once this is done, we can use it with a pretrained model. For instance `sgugger/finetuned-bert-mrpc` has been
fine-tuned on the MRPC dataset, which classifies pairs of sentences as paraphrases or not.

```py
from transformers import pipeline

classifier = pipeline("pair-classification", model="sgugger/finetuned-bert-mrpc")
```

Then we can share it on the Hub by using the `push_to_hub` method:

```py
classifier.push_to_hub("test-dynamic-pipeline")
```

This will copy the file where you defined `PairClassificationPipeline` inside the folder `"test-dynamic-pipeline"`,
along with saving the model and tokenizer of the pipeline, before pushing everything into the repository
`{your_username}/test-dynamic-pipeline`. After that, anyone can use it as long as they provide the option
`trust_remote_code=True`:

```py
from transformers import pipeline

classifier = pipeline(model="{your_username}/test-dynamic-pipeline", trust_remote_code=True)
```

## Add the pipeline to 🤗 Transformers

If you want to contribute your pipeline to 🤗 Transformers, you will need to add a new module in the `pipelines` submodule
with the code of your pipeline, then add it to the list of tasks defined in `pipelines/__init__.py`.

Then you will need to add tests. Create a new file `tests/test_pipelines_MY_PIPELINE.py` with examples of the other tests.

The `run_pipeline_test` function will be very generic and run on small random models on every possible
architecture as defined by `model_mapping` and `tf_model_mapping`.

This is very important to test future compatibility, meaning if someone adds a new model for
`XXXForQuestionAnswering` then the pipeline test will attempt to run on it.


key: _node_content
string_value:
{"id_": "13b0f9dd-82e7-4700-8633-7a81aa876e01", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/add_new_pipeline", "title": "How to create a custom pipeline?", "tokens": 2459, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "12eaf971-4b8a-42e8-a00c-b9efcc38a687", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/add_new_pipeline", "title": "How to create a custom pipeline?", "tokens": 2459, "retrieve_doc": true, "source": "transformers"}, "hash": "dfc723367cd5a652da183b279025448c9e43e96dcb711ddab3229f7038b46a09", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "64fed5eb-7799-4f92-8aaa-5c9bcba8e73e", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/add_new_pipeline", "title": "How to create a custom pipeline?", "tokens": 2459, "retrieve_doc": true, "source": "transformers"}, "hash": "d687fb8640f5efe63d4efff7e4b381b197a161109c1fcdcdb92bd45e5b87f1a4", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 7279, "end_char_idx": 10081, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
For instance `sgugger/finetuned-bert-mrpc` has been
fine-tuned on the MRPC dataset, which classifies pairs of sentences as paraphrases or not.

```py
from transformers import pipeline

classifier = pipeline("pair-classification", model="sgugger/finetuned-bert-mrpc")
```

Then we can share it on the Hub by using the `push_to_hub` method:

```py
classifier.push_to_hub("test-dynamic-pipeline")
```

This will copy the file where you defined `PairClassificationPipeline` inside the folder `"test-dynamic-pipeline"`,
along with saving the model and tokenizer of the pipeline, before pushing everything into the repository
`{your_username}/test-dynamic-pipeline`. After that, anyone can use it as long as they provide the option
`trust_remote_code=True`:

```py
from transformers import pipeline

classifier = pipeline(model="{your_username}/test-dynamic-pipeline", trust_remote_code=True)
```

## Add the pipeline to 🤗 Transformers

If you want to contribute your pipeline to 🤗 Transformers, you will need to add a new module in the `pipelines` submodule
with the code of your pipeline, then add it to the list of tasks defined in `pipelines/__init__.py`.

Then you will need to add tests. Create a new file `tests/test_pipelines_MY_PIPELINE.py` with examples of the other tests.

The `run_pipeline_test` function will be very generic and run on small random models on every possible
architecture as defined by `model_mapping` and `tf_model_mapping`.

This is very important to test future compatibility, meaning if someone adds a new model for
`XXXForQuestionAnswering` then the pipeline test will attempt to run on it. Because the models are random it's
impossible to check for actual values, that's why there is a helper `ANY` that will simply attempt to match the
output of the pipeline TYPE.

You also *need* to implement 2 (ideally 4) tests.

- `test_small_model_pt` : Define 1 small model for this pipeline (doesn't matter if the results don't make sense)
  and test the pipeline outputs. The results should be the same as `test_small_model_tf`.
- `test_small_model_tf` : Define 1 small model for this pipeline (doesn't matter if the results don't make sense)
  and test the pipeline outputs. The results should be the same as `test_small_model_pt`.
- `test_large_model_pt` (`optional`): Tests the pipeline on a real pipeline where the results are supposed to
  make sense. These tests are slow and should be marked as such. Here the goal is to showcase the pipeline and to make
  sure there is no drift in future releases.
- `test_large_model_tf` (`optional`): Tests the pipeline on a real pipeline where the results are supposed to
  make sense. These tests are slow and should be marked as such. Here the goal is to showcase the pipeline and to make
  sure there is no drift in future releases.


key: _node_content
string_value:
{"id_": "3bd6c9dd-1b49-4528-9aac-6867fe011133", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/multilingual", "title": "Multilingual models for inference", "tokens": 2131, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "7a5d89e9-e5dd-47e6-bdf5-cf6fa8e296ef", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/multilingual", "title": "Multilingual models for inference", "tokens": 2131, "retrieve_doc": true, "source": "transformers"}, "hash": "99d49851d4b4888e9d48b6a53ece48eb75860dc6f6a5b1d5abccd4d0e20bfb29", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "84dda9bd-af68-45ef-9c66-8aa184ae269f", "node_type": "1", "metadata": {}, "hash": "6746c3bd46cebe250934c963231c302122487af67cac19d1d09d2848ba1ac019", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 2495, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# Multilingual models for inference

[[open-in-colab]]

There are several multilingual models in 🤗 Transformers, and their inference usage differs from monolingual models. Not *all* multilingual model usage is different though. Some models, like [google-bert/bert-base-multilingual-uncased](https://huggingface.co/google-bert/bert-base-multilingual-uncased), can be used just like a monolingual model. This guide will show you how to use multilingual models whose usage differs for inference.

## XLM

XLM has ten different checkpoints, only one of which is monolingual. The nine remaining model checkpoints can be split into two categories: the checkpoints that use language embeddings and those that don't.

### XLM with language embeddings

The following XLM models use language embeddings to specify the language used at inference:

- `FacebookAI/xlm-mlm-ende-1024` (Masked language modeling, English-German)
- `FacebookAI/xlm-mlm-enfr-1024` (Masked language modeling, English-French)
- `FacebookAI/xlm-mlm-enro-1024` (Masked language modeling, English-Romanian)
- `FacebookAI/xlm-mlm-xnli15-1024` (Masked language modeling, XNLI languages)
- `FacebookAI/xlm-mlm-tlm-xnli15-1024` (Masked language modeling + translation, XNLI languages)
- `FacebookAI/xlm-clm-enfr-1024` (Causal language modeling, English-French)
- `FacebookAI/xlm-clm-ende-1024` (Causal language modeling, English-German)

Language embeddings are represented as a tensor of the same shape as the `input_ids` passed to the model. The values in these tensors depend on the language used and are identified by the tokenizer's `lang2id` and `id2lang` attributes.

In this example, load the `FacebookAI/xlm-clm-enfr-1024` checkpoint (Causal language modeling, English-French):

```py
>>> import torch
>>> from transformers import XLMTokenizer, XLMWithLMHeadModel

>>> tokenizer = XLMTokenizer.from_pretrained("FacebookAI/xlm-clm-enfr-1024")
>>> model = XLMWithLMHeadModel.from_pretrained("FacebookAI/xlm-clm-enfr-1024")
```

The `lang2id` attribute of the tokenizer displays this model's languages and their ids:

```py
>>> print(tokenizer.lang2id)
{'en': 0, 'fr': 1}
```

Next, create an example input:

```py
>>> input_ids = torch.tensor([tokenizer.encode("Wikipedia was used to")])  # batch size of 1
```

Set the language id as `"en"` and use it to define the language embedding. The language embedding is a tensor filled with `0` since that is the language id for English. This tensor should be the same size as `input_ids`.


key: _node_content
string_value:
{"id_": "84dda9bd-af68-45ef-9c66-8aa184ae269f", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/multilingual", "title": "Multilingual models for inference", "tokens": 2131, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "7a5d89e9-e5dd-47e6-bdf5-cf6fa8e296ef", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/multilingual", "title": "Multilingual models for inference", "tokens": 2131, "retrieve_doc": true, "source": "transformers"}, "hash": "99d49851d4b4888e9d48b6a53ece48eb75860dc6f6a5b1d5abccd4d0e20bfb29", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "3bd6c9dd-1b49-4528-9aac-6867fe011133", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/multilingual", "title": "Multilingual models for inference", "tokens": 2131, "retrieve_doc": true, "source": "transformers"}, "hash": "dd1ec0afdaeb290e8d3391171eadc9dca2f153697dfbc1ef85508d493641a2d6", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "0d9aee63-b27b-4d28-83e7-97ca97b403c5", "node_type": "1", "metadata": {}, "hash": "c88e540e08777fdc3c8b653f88e59d7067e87e01d6bdabaafe984397c2c4285d", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 1500, "end_char_idx": 4464, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
The values in these tensors depend on the language used and are identified by the tokenizer's `lang2id` and `id2lang` attributes.

In this example, load the `FacebookAI/xlm-clm-enfr-1024` checkpoint (Causal language modeling, English-French):

```py
>>> import torch
>>> from transformers import XLMTokenizer, XLMWithLMHeadModel

>>> tokenizer = XLMTokenizer.from_pretrained("FacebookAI/xlm-clm-enfr-1024")
>>> model = XLMWithLMHeadModel.from_pretrained("FacebookAI/xlm-clm-enfr-1024")
```

The `lang2id` attribute of the tokenizer displays this model's languages and their ids:

```py
>>> print(tokenizer.lang2id)
{'en': 0, 'fr': 1}
```

Next, create an example input:

```py
>>> input_ids = torch.tensor([tokenizer.encode("Wikipedia was used to")])  # batch size of 1
```

Set the language id as `"en"` and use it to define the language embedding. The language embedding is a tensor filled with `0` since that is the language id for English. This tensor should be the same size as `input_ids`. 

```py
>>> language_id = tokenizer.lang2id["en"]  # 0
>>> langs = torch.tensor([language_id] * input_ids.shape[1])  # torch.tensor([0, 0, 0, ..., 0])

>>> # We reshape it to be of size (batch_size, sequence_length)
>>> langs = langs.view(1, -1)  # is now of shape [1, sequence_length] (we have a batch size of 1)
```

Now you can pass the `input_ids` and language embedding to the model:

```py
>>> outputs = model(input_ids, langs=langs)
```

The [run_generation.py](https://github.com/huggingface/transformers/tree/main/examples/pytorch/text-generation/run_generation.py) script can generate text with language embeddings using the `xlm-clm` checkpoints.

### XLM without language embeddings

The following XLM models do not require language embeddings during inference:

- `FacebookAI/xlm-mlm-17-1280` (Masked language modeling, 17 languages)
- `FacebookAI/xlm-mlm-100-1280` (Masked language modeling, 100 languages)

These models are used for generic sentence representations, unlike the previous XLM checkpoints.

## BERT

The following BERT models can be used for multilingual tasks:

- `google-bert/bert-base-multilingual-uncased` (Masked language modeling + Next sentence prediction, 102 languages)
- `google-bert/bert-base-multilingual-cased` (Masked language modeling + Next sentence prediction, 104 languages)

These models do not require language embeddings during inference. They should identify the language from the
context and infer accordingly.

## XLM-RoBERTa

The following XLM-RoBERTa models can be used for multilingual tasks:

- `FacebookAI/xlm-roberta-base` (Masked language modeling, 100 languages)
- `FacebookAI/xlm-roberta-large` (Masked language modeling, 100 languages)

XLM-RoBERTa was trained on 2.5TB of newly created and cleaned CommonCrawl data in 100 languages. It provides strong gains over previously released multilingual models like mBERT or XLM on downstream tasks like classification, sequence labeling, and question answering.


key: _node_content
string_value:
{"id_": "0d9aee63-b27b-4d28-83e7-97ca97b403c5", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/multilingual", "title": "Multilingual models for inference", "tokens": 2131, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "7a5d89e9-e5dd-47e6-bdf5-cf6fa8e296ef", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/multilingual", "title": "Multilingual models for inference", "tokens": 2131, "retrieve_doc": true, "source": "transformers"}, "hash": "99d49851d4b4888e9d48b6a53ece48eb75860dc6f6a5b1d5abccd4d0e20bfb29", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "84dda9bd-af68-45ef-9c66-8aa184ae269f", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/multilingual", "title": "Multilingual models for inference", "tokens": 2131, "retrieve_doc": true, "source": "transformers"}, "hash": "f76c63838b6f33a938df9aba2bbb5c3fcefa1d714944b8c12ef7d9dceac77ddd", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "dabf0ce9-9eea-45d5-aefd-a02b8c3b3f80", "node_type": "1", "metadata": {}, "hash": "f2b7cf5c8aae23948aac1ebb6029475bfe9f3b753b870c1e307871e701573ee0", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 3155, "end_char_idx": 5747, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
### XLM without language embeddings

The following XLM models do not require language embeddings during inference:

- `FacebookAI/xlm-mlm-17-1280` (Masked language modeling, 17 languages)
- `FacebookAI/xlm-mlm-100-1280` (Masked language modeling, 100 languages)

These models are used for generic sentence representations, unlike the previous XLM checkpoints.

## BERT

The following BERT models can be used for multilingual tasks:

- `google-bert/bert-base-multilingual-uncased` (Masked language modeling + Next sentence prediction, 102 languages)
- `google-bert/bert-base-multilingual-cased` (Masked language modeling + Next sentence prediction, 104 languages)

These models do not require language embeddings during inference. They should identify the language from the
context and infer accordingly.

## XLM-RoBERTa

The following XLM-RoBERTa models can be used for multilingual tasks:

- `FacebookAI/xlm-roberta-base` (Masked language modeling, 100 languages)
- `FacebookAI/xlm-roberta-large` (Masked language modeling, 100 languages)

XLM-RoBERTa was trained on 2.5TB of newly created and cleaned CommonCrawl data in 100 languages. It provides strong gains over previously released multilingual models like mBERT or XLM on downstream tasks like classification, sequence labeling, and question answering.

## M2M100

The following M2M100 models can be used for multilingual translation:

- `facebook/m2m100_418M` (Translation)
- `facebook/m2m100_1.2B` (Translation)

In this example, load the `facebook/m2m100_418M` checkpoint to translate from Chinese to English. You can set the source language in the tokenizer:

```py
>>> from transformers import M2M100ForConditionalGeneration, M2M100Tokenizer

>>> en_text = "Do not meddle in the affairs of wizards, for they are subtle and quick to anger."
>>> chinese_text = "不要插手巫師的事務, 因為他們是微妙的, 很快就會發怒."

>>> tokenizer = M2M100Tokenizer.from_pretrained("facebook/m2m100_418M", src_lang="zh")
>>> model = M2M100ForConditionalGeneration.from_pretrained("facebook/m2m100_418M")
```

Tokenize the text:

```py
>>> encoded_zh = tokenizer(chinese_text, return_tensors="pt")
```

M2M100 forces the target language id as the first generated token to translate to the target language. Set the `forced_bos_token_id` to `en` in the `generate` method to translate to English:

```py
>>> generated_tokens = model.generate(**encoded_zh, forced_bos_token_id=tokenizer.get_lang_id("en"))
>>> tokenizer.batch_decode(generated_tokens, skip_special_tokens=True)
'Do not interfere with the matters of the witches, because they are delicate and will soon be angry.'


key: _node_content
string_value:
{"id_": "dabf0ce9-9eea-45d5-aefd-a02b8c3b3f80", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/multilingual", "title": "Multilingual models for inference", "tokens": 2131, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "7a5d89e9-e5dd-47e6-bdf5-cf6fa8e296ef", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/multilingual", "title": "Multilingual models for inference", "tokens": 2131, "retrieve_doc": true, "source": "transformers"}, "hash": "99d49851d4b4888e9d48b6a53ece48eb75860dc6f6a5b1d5abccd4d0e20bfb29", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "0d9aee63-b27b-4d28-83e7-97ca97b403c5", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/multilingual", "title": "Multilingual models for inference", "tokens": 2131, "retrieve_doc": true, "source": "transformers"}, "hash": "545ef307b6b3d86a545bc63b002bcc673feb3b2919c4613e31ee36611de1b871", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "439b225d-1a32-4d80-ac79-281f6295275d", "node_type": "1", "metadata": {}, "hash": "17e8accc0199a9afbabeffe6c84019a2b4b25c21e397fd28984dfeebced517cf", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 4293, "end_char_idx": 7079, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
It provides strong gains over previously released multilingual models like mBERT or XLM on downstream tasks like classification, sequence labeling, and question answering.

## M2M100

The following M2M100 models can be used for multilingual translation:

- `facebook/m2m100_418M` (Translation)
- `facebook/m2m100_1.2B` (Translation)

In this example, load the `facebook/m2m100_418M` checkpoint to translate from Chinese to English. You can set the source language in the tokenizer:

```py
>>> from transformers import M2M100ForConditionalGeneration, M2M100Tokenizer

>>> en_text = "Do not meddle in the affairs of wizards, for they are subtle and quick to anger."
>>> chinese_text = "不要插手巫師的事務, 因為他們是微妙的, 很快就會發怒."

>>> tokenizer = M2M100Tokenizer.from_pretrained("facebook/m2m100_418M", src_lang="zh")
>>> model = M2M100ForConditionalGeneration.from_pretrained("facebook/m2m100_418M")
```

Tokenize the text:

```py
>>> encoded_zh = tokenizer(chinese_text, return_tensors="pt")
```

M2M100 forces the target language id as the first generated token to translate to the target language. Set the `forced_bos_token_id` to `en` in the `generate` method to translate to English:

```py
>>> generated_tokens = model.generate(**encoded_zh, forced_bos_token_id=tokenizer.get_lang_id("en"))
>>> tokenizer.batch_decode(generated_tokens, skip_special_tokens=True)
'Do not interfere with the matters of the witches, because they are delicate and will soon be angry.'
```

## MBart

The following MBart models can be used for multilingual translation:

- `facebook/mbart-large-50-one-to-many-mmt` (One-to-many multilingual machine translation, 50 languages)
- `facebook/mbart-large-50-many-to-many-mmt` (Many-to-many multilingual machine translation, 50 languages)
- `facebook/mbart-large-50-many-to-one-mmt` (Many-to-one multilingual machine translation, 50 languages)
- `facebook/mbart-large-50` (Multilingual translation, 50 languages)
- `facebook/mbart-large-cc25`

In this example, load the `facebook/mbart-large-50-many-to-many-mmt` checkpoint to translate Finnish to English. You can set the source language in the tokenizer:

```py
>>> from transformers import AutoTokenizer, AutoModelForSeq2SeqLM

>>> en_text = "Do not meddle in the affairs of wizards, for they are subtle and quick to anger."
>>> fi_text = "Älä sekaannu velhojen asioihin, sillä ne ovat hienovaraisia ja nopeasti vihaisia."

>>> tokenizer = AutoTokenizer.from_pretrained("facebook/mbart-large-50-many-to-many-mmt", src_lang="fi_FI")
>>> model = AutoModelForSeq2SeqLM.from_pretrained("facebook/mbart-large-50-many-to-many-mmt")
```

Tokenize the text:

```py
>>> encoded_en = tokenizer(en_text, return_tensors="pt")
```

MBart forces the target language id as the first generated token to translate to the target language.


key: _node_content
string_value:
{"id_": "439b225d-1a32-4d80-ac79-281f6295275d", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/multilingual", "title": "Multilingual models for inference", "tokens": 2131, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "7a5d89e9-e5dd-47e6-bdf5-cf6fa8e296ef", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/multilingual", "title": "Multilingual models for inference", "tokens": 2131, "retrieve_doc": true, "source": "transformers"}, "hash": "99d49851d4b4888e9d48b6a53ece48eb75860dc6f6a5b1d5abccd4d0e20bfb29", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "dabf0ce9-9eea-45d5-aefd-a02b8c3b3f80", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/multilingual", "title": "Multilingual models for inference", "tokens": 2131, "retrieve_doc": true, "source": "transformers"}, "hash": "178e8d36ec7f838dd3801571daf9668cdc117479b261d291e2981659140f661d", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 5748, "end_char_idx": 7633, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
```

## MBart

The following MBart models can be used for multilingual translation:

- `facebook/mbart-large-50-one-to-many-mmt` (One-to-many multilingual machine translation, 50 languages)
- `facebook/mbart-large-50-many-to-many-mmt` (Many-to-many multilingual machine translation, 50 languages)
- `facebook/mbart-large-50-many-to-one-mmt` (Many-to-one multilingual machine translation, 50 languages)
- `facebook/mbart-large-50` (Multilingual translation, 50 languages)
- `facebook/mbart-large-cc25`

In this example, load the `facebook/mbart-large-50-many-to-many-mmt` checkpoint to translate Finnish to English. You can set the source language in the tokenizer:

```py
>>> from transformers import AutoTokenizer, AutoModelForSeq2SeqLM

>>> en_text = "Do not meddle in the affairs of wizards, for they are subtle and quick to anger."
>>> fi_text = "Älä sekaannu velhojen asioihin, sillä ne ovat hienovaraisia ja nopeasti vihaisia."

>>> tokenizer = AutoTokenizer.from_pretrained("facebook/mbart-large-50-many-to-many-mmt", src_lang="fi_FI")
>>> model = AutoModelForSeq2SeqLM.from_pretrained("facebook/mbart-large-50-many-to-many-mmt")
```

Tokenize the text:

```py
>>> encoded_en = tokenizer(en_text, return_tensors="pt")
```

MBart forces the target language id as the first generated token to translate to the target language. Set the `forced_bos_token_id` to `en` in the `generate` method to translate to English:

```py
>>> generated_tokens = model.generate(**encoded_en, forced_bos_token_id=tokenizer.lang_code_to_id["en_XX"])
>>> tokenizer.batch_decode(generated_tokens, skip_special_tokens=True)
"Don't interfere with the wizard's affairs, because they are subtle, will soon get angry."
```

If you are using the `facebook/mbart-large-50-many-to-one-mmt` checkpoint, you don't need to force the target language id as the first generated token otherwise the usage is the same.


key: _node_content
string_value:
{"id_": "c9115fe3-7966-4f47-b3ba-9e386ee594e3", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/debugging", "title": "Debugging", "tokens": 5079, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "3afbb714-b9f6-4e67-bda1-c03b779c2b6b", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/debugging", "title": "Debugging", "tokens": 5079, "retrieve_doc": true, "source": "transformers"}, "hash": "547ee66977115761f6778ec77a0f4395de63815dbe390968fa02dc78b9a4a944", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "7e64ae86-0f43-4fbc-9271-87f72fa2028b", "node_type": "1", "metadata": {}, "hash": "1635fd4e22cf59f4b430f695011bf44b5fffba2c7c4672a4914ecc2f1e15e203", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 0, "end_char_idx": 3468, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
# Debugging

Training on multiple GPUs can be a tricky endeavor whether you're running into installation issues or communication problems between your GPUs. This debugging guide covers some issues you may run into and how to resolve them.

## DeepSpeed CUDA installation

If you're using DeepSpeed, you've probably already installed it with the following command.

```bash
pip install deepspeed
```

DeepSpeed compiles CUDA C++ code and it can be a potential source of errors when building PyTorch extensions that require CUDA. These errors depend on how CUDA is installed on your system, and this section focuses on PyTorch built with *CUDA 10.2*.

<Tip>

For any other installation issues, please [open an issue](https://github.com/microsoft/DeepSpeed/issues) with the DeepSpeed team.

</Tip>

### Non-identical CUDA toolkits

PyTorch comes with its own CUDA toolkit, but to use DeepSpeed with PyTorch, you need to have an identical version of CUDA installed system-wide. For example, if you installed PyTorch with `cudatoolkit==10.2` in your Python environment, then you'll also need to have CUDA 10.2 installed system-wide. If you don't have CUDA installed system-wide, you should install it first.

The exact location may vary from system to system, but `usr/local/cuda-10.2` is the most common location on many Unix systems. When CUDA is correctly setup and added to your `PATH` environment variable, you can find the installation location with the following command:

```bash
which nvcc
```

### Multiple CUDA toolkits

You may also have more than one CUDA toolkit installed system-wide.

```bash
/usr/local/cuda-10.2
/usr/local/cuda-11.0
```

Typically, package installers set the paths to whatever the last version was installed. If the package build fails because it can't find the right CUDA version (despite it being installed system-wide already), then you need to configure the `PATH` and `LD_LIBRARY_PATH` environment variables to point to the correct path.

Take a look at the contents of these environment variables first:

```bash
echo $PATH
echo $LD_LIBRARY_PATH
```

`PATH` lists the locations of the executables and `LD_LIBRARY_PATH` lists where to look for shared libraries. Earlier entries are prioritized over later ones, and `:` is used to separate multiple entries. To tell the build program where to find the specific CUDA toolkit you want, insert the correct path to list first. This command prepends rather than overwrites the existing values.

```bash
# adjust the version and full path if needed
export PATH=/usr/local/cuda-10.2/bin:$PATH
export LD_LIBRARY_PATH=/usr/local/cuda-10.2/lib64:$LD_LIBRARY_PATH
```

In addition, you should also check the directories you assign actually exist. The `lib64` sub-directory contains various CUDA `.so` objects (like `libcudart.so`) and while it is unlikely your system names them differently, you should check the actual names and change them accordingly.

### Older CUDA versions

Sometimes, older CUDA versions may refuse to build with newer compilers. For example, if you have `gcc-9` but CUDA wants `gcc-7`. Usually, installing the latest CUDA toolkit enables support for the newer compiler.

You could also install an older version of the compiler in addition to the one you're currently using (or it may already be installed but it's not used by default and the build system can't see it). To resolve this, you can create a symlink to give the build system visibility to the older compiler.


key: _node_content
string_value:
{"id_": "7e64ae86-0f43-4fbc-9271-87f72fa2028b", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/debugging", "title": "Debugging", "tokens": 5079, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "3afbb714-b9f6-4e67-bda1-c03b779c2b6b", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/debugging", "title": "Debugging", "tokens": 5079, "retrieve_doc": true, "source": "transformers"}, "hash": "547ee66977115761f6778ec77a0f4395de63815dbe390968fa02dc78b9a4a944", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "c9115fe3-7966-4f47-b3ba-9e386ee594e3", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/debugging", "title": "Debugging", "tokens": 5079, "retrieve_doc": true, "source": "transformers"}, "hash": "6a2b8a6790004e7a196543e42a6464a579b2ee21af138cd57f97ad0ce280ad85", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "20931e00-4a96-445d-8e64-3824571ccd32", "node_type": "1", "metadata": {}, "hash": "b17cdd84ce2e3fef5fce5abab17b3b17fe97571a06420e6851585ff069949e56", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 1739, "end_char_idx": 4520, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
If the package build fails because it can't find the right CUDA version (despite it being installed system-wide already), then you need to configure the `PATH` and `LD_LIBRARY_PATH` environment variables to point to the correct path.

Take a look at the contents of these environment variables first:

```bash
echo $PATH
echo $LD_LIBRARY_PATH
```

`PATH` lists the locations of the executables and `LD_LIBRARY_PATH` lists where to look for shared libraries. Earlier entries are prioritized over later ones, and `:` is used to separate multiple entries. To tell the build program where to find the specific CUDA toolkit you want, insert the correct path to list first. This command prepends rather than overwrites the existing values.

```bash
# adjust the version and full path if needed
export PATH=/usr/local/cuda-10.2/bin:$PATH
export LD_LIBRARY_PATH=/usr/local/cuda-10.2/lib64:$LD_LIBRARY_PATH
```

In addition, you should also check the directories you assign actually exist. The `lib64` sub-directory contains various CUDA `.so` objects (like `libcudart.so`) and while it is unlikely your system names them differently, you should check the actual names and change them accordingly.

### Older CUDA versions

Sometimes, older CUDA versions may refuse to build with newer compilers. For example, if you have `gcc-9` but CUDA wants `gcc-7`. Usually, installing the latest CUDA toolkit enables support for the newer compiler.

You could also install an older version of the compiler in addition to the one you're currently using (or it may already be installed but it's not used by default and the build system can't see it). To resolve this, you can create a symlink to give the build system visibility to the older compiler.

```bash
# adapt the path to your system
sudo ln -s /usr/bin/gcc-7  /usr/local/cuda-10.2/bin/gcc
sudo ln -s /usr/bin/g++-7  /usr/local/cuda-10.2/bin/g++
```

### Prebuild

If you're still having issues with installing DeepSpeed or if you're building DeepSpeed at run time, you can try to prebuild the DeepSpeed modules before installing them. To make a local build for DeepSpeed:

```bash
git clone https://github.com/microsoft/DeepSpeed/
cd DeepSpeed
rm -rf build
TORCH_CUDA_ARCH_LIST="8.6" DS_BUILD_CPU_ADAM=1 DS_BUILD_UTILS=1 pip install . \
--global-option="build_ext" --global-option="-j8" --no-cache -v \
--disable-pip-version-check 2>&1 | tee build.log
```

<Tip>

To use NVMe offload, add the `DS_BUILD_AIO=1` parameter to the build command and make sure you install the libaio-dev package system-wide.

</Tip>

Next, you'll have to specify your GPU's architecture by editing the `TORCH_CUDA_ARCH_LIST` variable (find a complete list of NVIDIA GPUs and their corresponding architectures on this [page](https://developer.nvidia.com/cuda-gpus)).


key: _node_content
string_value:
{"id_": "20931e00-4a96-445d-8e64-3824571ccd32", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/debugging", "title": "Debugging", "tokens": 5079, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "3afbb714-b9f6-4e67-bda1-c03b779c2b6b", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/debugging", "title": "Debugging", "tokens": 5079, "retrieve_doc": true, "source": "transformers"}, "hash": "547ee66977115761f6778ec77a0f4395de63815dbe390968fa02dc78b9a4a944", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "7e64ae86-0f43-4fbc-9271-87f72fa2028b", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/debugging", "title": "Debugging", "tokens": 5079, "retrieve_doc": true, "source": "transformers"}, "hash": "915ac2171943b31988024743b6ccda8c5a05f467dcb682bce6a4eb09dfd6c696", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "6d3b3556-806a-472a-b73c-5acda84308e3", "node_type": "1", "metadata": {}, "hash": "8a12dec6c11fbf78aa24e990ad2d9ad9c584ecff3a4e98d1d9f0b156676110d3", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 3027, "end_char_idx": 5739, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
For example, if you have `gcc-9` but CUDA wants `gcc-7`. Usually, installing the latest CUDA toolkit enables support for the newer compiler.

You could also install an older version of the compiler in addition to the one you're currently using (or it may already be installed but it's not used by default and the build system can't see it). To resolve this, you can create a symlink to give the build system visibility to the older compiler.

```bash
# adapt the path to your system
sudo ln -s /usr/bin/gcc-7  /usr/local/cuda-10.2/bin/gcc
sudo ln -s /usr/bin/g++-7  /usr/local/cuda-10.2/bin/g++
```

### Prebuild

If you're still having issues with installing DeepSpeed or if you're building DeepSpeed at run time, you can try to prebuild the DeepSpeed modules before installing them. To make a local build for DeepSpeed:

```bash
git clone https://github.com/microsoft/DeepSpeed/
cd DeepSpeed
rm -rf build
TORCH_CUDA_ARCH_LIST="8.6" DS_BUILD_CPU_ADAM=1 DS_BUILD_UTILS=1 pip install . \
--global-option="build_ext" --global-option="-j8" --no-cache -v \
--disable-pip-version-check 2>&1 | tee build.log
```

<Tip>

To use NVMe offload, add the `DS_BUILD_AIO=1` parameter to the build command and make sure you install the libaio-dev package system-wide.

</Tip>

Next, you'll have to specify your GPU's architecture by editing the `TORCH_CUDA_ARCH_LIST` variable (find a complete list of NVIDIA GPUs and their corresponding architectures on this [page](https://developer.nvidia.com/cuda-gpus)). To check the PyTorch version that corresponds to your architecture, run the following command:

```bash
python -c "import torch; print(torch.cuda.get_arch_list())"
```

Find the architecture for a GPU with the following command:

<hfoptions id="arch">
<hfoption id="same GPUs">

```bash
CUDA_VISIBLE_DEVICES=0 python -c "import torch; print(torch.cuda.get_device_capability())"
```

</hfoption>
<hfoption id="specific GPU">

To find the architecture for GPU `0`:

```bash
CUDA_VISIBLE_DEVICES=0 python -c "import torch; \
print(torch.cuda.get_device_properties(torch.device('cuda')))
"_CudaDeviceProperties(name='GeForce RTX 3090', major=8, minor=6, total_memory=24268MB, multi_processor_count=82)"
```

This means your GPU architecture is `8.6`.

</hfoption>
</hfoptions>

If you get `8, 6`, then you can set `TORCH_CUDA_ARCH_LIST="8.6"`. For multiple GPUs with different architectures, list them like `TORCH_CUDA_ARCH_LIST="6.1;8.6"`.

It is also possible to not specify `TORCH_CUDA_ARCH_LIST` and the build program automatically queries the GPU architecture of the build. However, it may or may not match the actual GPU on the target machine which is why it is better to explicitly specify the correct architecture.


key: _node_content
string_value:
{"id_": "6d3b3556-806a-472a-b73c-5acda84308e3", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/debugging", "title": "Debugging", "tokens": 5079, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "3afbb714-b9f6-4e67-bda1-c03b779c2b6b", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/debugging", "title": "Debugging", "tokens": 5079, "retrieve_doc": true, "source": "transformers"}, "hash": "547ee66977115761f6778ec77a0f4395de63815dbe390968fa02dc78b9a4a944", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "20931e00-4a96-445d-8e64-3824571ccd32", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/debugging", "title": "Debugging", "tokens": 5079, "retrieve_doc": true, "source": "transformers"}, "hash": "f11f7473bb66309ee7128bab94dce7a93966e9d6014d08a483d0c9ed90ef45a9", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "6e244fcc-b022-4785-a207-046a934bfcb5", "node_type": "1", "metadata": {}, "hash": "d41a0b1ff0448b3bca8072a63edd39838056f5c3adb7a07e32a1afb634b19516", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 4281, "end_char_idx": 7107, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
</Tip>

Next, you'll have to specify your GPU's architecture by editing the `TORCH_CUDA_ARCH_LIST` variable (find a complete list of NVIDIA GPUs and their corresponding architectures on this [page](https://developer.nvidia.com/cuda-gpus)). To check the PyTorch version that corresponds to your architecture, run the following command:

```bash
python -c "import torch; print(torch.cuda.get_arch_list())"
```

Find the architecture for a GPU with the following command:

<hfoptions id="arch">
<hfoption id="same GPUs">

```bash
CUDA_VISIBLE_DEVICES=0 python -c "import torch; print(torch.cuda.get_device_capability())"
```

</hfoption>
<hfoption id="specific GPU">

To find the architecture for GPU `0`:

```bash
CUDA_VISIBLE_DEVICES=0 python -c "import torch; \
print(torch.cuda.get_device_properties(torch.device('cuda')))
"_CudaDeviceProperties(name='GeForce RTX 3090', major=8, minor=6, total_memory=24268MB, multi_processor_count=82)"
```

This means your GPU architecture is `8.6`.

</hfoption>
</hfoptions>

If you get `8, 6`, then you can set `TORCH_CUDA_ARCH_LIST="8.6"`. For multiple GPUs with different architectures, list them like `TORCH_CUDA_ARCH_LIST="6.1;8.6"`.

It is also possible to not specify `TORCH_CUDA_ARCH_LIST` and the build program automatically queries the GPU architecture of the build. However, it may or may not match the actual GPU on the target machine which is why it is better to explicitly specify the correct architecture.

For training on multiple machines with the same setup, you'll need to make a binary wheel:

```bash
git clone https://github.com/microsoft/DeepSpeed/
cd DeepSpeed
rm -rf build
TORCH_CUDA_ARCH_LIST="8.6" DS_BUILD_CPU_ADAM=1 DS_BUILD_UTILS=1 \
python setup.py build_ext -j8 bdist_wheel
```

This command generates a binary wheel that'll look something like `dist/deepspeed-0.3.13+8cd046f-cp38-cp38-linux_x86_64.whl`. Now you can install this wheel locally or on another machine.

```bash
pip install deepspeed-0.3.13+8cd046f-cp38-cp38-linux_x86_64.whl
```

## Multi-GPU Network Issues Debug

When training or inferencing with `DistributedDataParallel` and multiple GPU, if you run into issue of inter-communication between processes and/or nodes, you can use the following script to diagnose network issues.

```bash
wget https://raw.githubusercontent.com/huggingface/transformers/main/scripts/distributed/torch-distributed-gpu-test.py
```

For example to test how 2 GPUs interact do:

```bash
python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py
```
If both processes can talk to each and allocate GPU memory each will print an OK status.

For more GPUs or nodes adjust the arguments in the script.

You will find a lot more details inside the diagnostics script and even a recipe to how you could run it in a SLURM environment.


key: _node_content
string_value:
{"id_": "6e244fcc-b022-4785-a207-046a934bfcb5", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/debugging", "title": "Debugging", "tokens": 5079, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "3afbb714-b9f6-4e67-bda1-c03b779c2b6b", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/debugging", "title": "Debugging", "tokens": 5079, "retrieve_doc": true, "source": "transformers"}, "hash": "547ee66977115761f6778ec77a0f4395de63815dbe390968fa02dc78b9a4a944", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "6d3b3556-806a-472a-b73c-5acda84308e3", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/debugging", "title": "Debugging", "tokens": 5079, "retrieve_doc": true, "source": "transformers"}, "hash": "414ee40dcbacb3931e287db6de74897e3d22bdf6d4a2e05cbab24f5ac04bbd6f", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "5e8b61f8-cf98-47e4-9d6b-d22bcd6b3935", "node_type": "1", "metadata": {}, "hash": "576d36afd6b8fa648b546efa9eacd29548d4bf6136e8638374b50434909888bf", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 5596, "end_char_idx": 8770, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
However, it may or may not match the actual GPU on the target machine which is why it is better to explicitly specify the correct architecture.

For training on multiple machines with the same setup, you'll need to make a binary wheel:

```bash
git clone https://github.com/microsoft/DeepSpeed/
cd DeepSpeed
rm -rf build
TORCH_CUDA_ARCH_LIST="8.6" DS_BUILD_CPU_ADAM=1 DS_BUILD_UTILS=1 \
python setup.py build_ext -j8 bdist_wheel
```

This command generates a binary wheel that'll look something like `dist/deepspeed-0.3.13+8cd046f-cp38-cp38-linux_x86_64.whl`. Now you can install this wheel locally or on another machine.

```bash
pip install deepspeed-0.3.13+8cd046f-cp38-cp38-linux_x86_64.whl
```

## Multi-GPU Network Issues Debug

When training or inferencing with `DistributedDataParallel` and multiple GPU, if you run into issue of inter-communication between processes and/or nodes, you can use the following script to diagnose network issues.

```bash
wget https://raw.githubusercontent.com/huggingface/transformers/main/scripts/distributed/torch-distributed-gpu-test.py
```

For example to test how 2 GPUs interact do:

```bash
python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py
```
If both processes can talk to each and allocate GPU memory each will print an OK status.

For more GPUs or nodes adjust the arguments in the script.

You will find a lot more details inside the diagnostics script and even a recipe to how you could run it in a SLURM environment.

An additional level of debug is to add `NCCL_DEBUG=INFO` environment variable as follows:

```bash
NCCL_DEBUG=INFO python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py
```

This will dump a lot of NCCL-related debug information, which you can then search online if you find that some problems are reported. Or if you're not sure how to interpret the output you can share the log file in an Issue.



## Underflow and Overflow Detection

<Tip>

This feature is currently available for PyTorch-only.

</Tip>

<Tip>

For multi-GPU training it requires DDP (`torch.distributed.launch`).

</Tip>

<Tip>

This feature can be used with any `nn.Module`-based model.

</Tip>

If you start getting `loss=NaN` or the model inhibits some other abnormal behavior due to `inf` or `nan` in
activations or weights one needs to discover where the first underflow or overflow happens and what led to it. Luckily
you can accomplish that easily by activating a special module that will do the detection automatically.

If you're using [`Trainer`], you just need to add:

```bash
--debug underflow_overflow
```

to the normal command line arguments, or pass `debug="underflow_overflow"` when creating the
[`TrainingArguments`] object.

If you're using your own training loop or another Trainer you can accomplish the same with:

```python
from transformers.debug_utils import DebugUnderflowOverflow

debug_overflow = DebugUnderflowOverflow(model)
```

[`~debug_utils.DebugUnderflowOverflow`] inserts hooks into the model that immediately after each
forward call will test input and output variables and also the corresponding module's weights.


key: _node_content
string_value:
{"id_": "5e8b61f8-cf98-47e4-9d6b-d22bcd6b3935", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/debugging", "title": "Debugging", "tokens": 5079, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "3afbb714-b9f6-4e67-bda1-c03b779c2b6b", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/debugging", "title": "Debugging", "tokens": 5079, "retrieve_doc": true, "source": "transformers"}, "hash": "547ee66977115761f6778ec77a0f4395de63815dbe390968fa02dc78b9a4a944", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "6e244fcc-b022-4785-a207-046a934bfcb5", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/debugging", "title": "Debugging", "tokens": 5079, "retrieve_doc": true, "source": "transformers"}, "hash": "a69cdb79381112f6e1a581b063f9356133617e7428fb12c061f5712d2aff9ae9", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "18643554-c12e-4d74-85c7-9d3095612781", "node_type": "1", "metadata": {}, "hash": "3b519da78cade1bab1818163fb8e6cd49b88da400252a093db6444e3b11b5a7c", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 7109, "end_char_idx": 10398, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
An additional level of debug is to add `NCCL_DEBUG=INFO` environment variable as follows:

```bash
NCCL_DEBUG=INFO python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py
```

This will dump a lot of NCCL-related debug information, which you can then search online if you find that some problems are reported. Or if you're not sure how to interpret the output you can share the log file in an Issue.



## Underflow and Overflow Detection

<Tip>

This feature is currently available for PyTorch-only.

</Tip>

<Tip>

For multi-GPU training it requires DDP (`torch.distributed.launch`).

</Tip>

<Tip>

This feature can be used with any `nn.Module`-based model.

</Tip>

If you start getting `loss=NaN` or the model inhibits some other abnormal behavior due to `inf` or `nan` in
activations or weights one needs to discover where the first underflow or overflow happens and what led to it. Luckily
you can accomplish that easily by activating a special module that will do the detection automatically.

If you're using [`Trainer`], you just need to add:

```bash
--debug underflow_overflow
```

to the normal command line arguments, or pass `debug="underflow_overflow"` when creating the
[`TrainingArguments`] object.

If you're using your own training loop or another Trainer you can accomplish the same with:

```python
from transformers.debug_utils import DebugUnderflowOverflow

debug_overflow = DebugUnderflowOverflow(model)
```

[`~debug_utils.DebugUnderflowOverflow`] inserts hooks into the model that immediately after each
forward call will test input and output variables and also the corresponding module's weights. As soon as `inf` or
`nan` is detected in at least one element of the activations or weights, the program will assert and print a report
like this (this was caught with `google/mt5-small` under fp16 mixed precision):

```
Detected inf/nan during batch_number=0
Last 21 forward frames:
abs min  abs max  metadata
                  encoder.block.1.layer.1.DenseReluDense.dropout Dropout
0.00e+00 2.57e+02 input[0]
0.00e+00 2.85e+02 output
[...]
                  encoder.block.2.layer.0 T5LayerSelfAttention
6.78e-04 3.15e+03 input[0]
2.65e-04 3.42e+03 output[0]
             None output[1]
2.25e-01 1.00e+04 output[2]
                  encoder.block.2.layer.1.layer_norm T5LayerNorm
8.69e-02 4.18e-01 weight
2.65e-04 3.42e+03 input[0]
1.79e-06 4.65e+00 output
                  encoder.block.2.layer.1.DenseReluDense.wi_0 Linear
2.17e-07 4.50e+00 weight
1.79e-06 4.65e+00 input[0]
2.68e-06 3.70e+01 output
                  encoder.block.2.layer.1.DenseReluDense.wi_1 Linear
8.08e-07 2.66e+01 weight
1.79e-06 4.65e+00 input[0]
1.27e-04 2.37e+02 output
                  encoder.block.2.layer.1.DenseReluDense.dropout Dropout
0.00e+00 8.76e+03 input[0]
0.00e+00 9.74e+03 output
                  encoder.block.2.layer.1.DenseReluDense.wo Linear
1.01e-06 6.44e+00 weight
0.00e+00 9.74e+03 input[0]
3.18e-04 6.27e+04 output
                  encoder.block.2.layer.1.DenseReluDense T5DenseGatedGeluDense
1.79e-06 4.65e+00 input[0]
3.18e-04 6.27e+04 output
                  encoder.block.2.layer.1.dropout Dropout
3.18e-04 6.27e+04 input[0]
0.00e+00      inf output
```

The example output has been trimmed in the middle for brevity.


key: _node_content
string_value:
{"id_": "18643554-c12e-4d74-85c7-9d3095612781", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/debugging", "title": "Debugging", "tokens": 5079, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "3afbb714-b9f6-4e67-bda1-c03b779c2b6b", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/debugging", "title": "Debugging", "tokens": 5079, "retrieve_doc": true, "source": "transformers"}, "hash": "547ee66977115761f6778ec77a0f4395de63815dbe390968fa02dc78b9a4a944", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "5e8b61f8-cf98-47e4-9d6b-d22bcd6b3935", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/debugging", "title": "Debugging", "tokens": 5079, "retrieve_doc": true, "source": "transformers"}, "hash": "78d7aa0196a160fcb4a24199784dd0958b671579a5c1077de68f02bb9233accf", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "cc77445e-3136-42b5-ae77-6862a253c84e", "node_type": "1", "metadata": {}, "hash": "e8bca47fc6f6d00970b20c72a3aebb19b78a20df0ae9f0d10da2fd63e2693fcd", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 10400, "end_char_idx": 12865, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
The second column shows the value of the absolute largest element, so if you have a closer look at the last few frames,
the inputs and outputs were in the range of `1e4`. So when this training was done under fp16 mixed precision the very
last step overflowed (since under `fp16` the largest number before `inf` is `64e3`). To avoid overflows under
`fp16` the activations must remain way below `1e4`, because `1e4 * 1e4 = 1e8` so any matrix multiplication with
large activations is going to lead to a numerical overflow condition.

At the very start of the trace you can discover at which batch number the problem occurred (here `Detected inf/nan during batch_number=0` means the problem occurred on the first batch).

Each reported frame starts by declaring the fully qualified entry for the corresponding module this frame is reporting
for. If we look just at this frame:

```
                  encoder.block.2.layer.1.layer_norm T5LayerNorm
8.69e-02 4.18e-01 weight
2.65e-04 3.42e+03 input[0]
1.79e-06 4.65e+00 output
```

Here, `encoder.block.2.layer.1.layer_norm` indicates that it was a layer norm for the first layer, of the second
block of the encoder. And the specific calls of the `forward` is `T5LayerNorm`.

Let's look at the last few frames of that report:

```
Detected inf/nan during batch_number=0
Last 21 forward frames:
abs min  abs max  metadata
[...]
                  encoder.block.2.layer.1.DenseReluDense.wi_0 Linear
2.17e-07 4.50e+00 weight
1.79e-06 4.65e+00 input[0]
2.68e-06 3.70e+01 output
                  encoder.block.2.layer.1.DenseReluDense.wi_1 Linear
8.08e-07 2.66e+01 weight
1.79e-06 4.65e+00 input[0]
1.27e-04 2.37e+02 output
                  encoder.block.2.layer.1.DenseReluDense.wo Linear
1.01e-06 6.44e+00 weight
0.00e+00 9.74e+03 input[0]
3.18e-04 6.27e+04 output
                  encoder.block.2.layer.1.DenseReluDense T5DenseGatedGeluDense
1.79e-06 4.65e+00 input[0]
3.18e-04 6.27e+04 output
                  encoder.block.2.layer.1.dropout Dropout
3.18e-04 6.27e+04 input[0]
0.00e+00      inf output
```

The last frame reports for `Dropout.forward` function with the first entry for the only input and the second for the
only output. You can see that it was called from an attribute `dropout` inside `DenseReluDense` class. We can see
that it happened during the first layer, of the 2nd block, during the very first batch. Finally, the absolute largest
input elements was `6.27e+04` and same for the output was `inf`.


key: _node_content
string_value:
{"id_": "cc77445e-3136-42b5-ae77-6862a253c84e", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/debugging", "title": "Debugging", "tokens": 5079, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "3afbb714-b9f6-4e67-bda1-c03b779c2b6b", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/debugging", "title": "Debugging", "tokens": 5079, "retrieve_doc": true, "source": "transformers"}, "hash": "547ee66977115761f6778ec77a0f4395de63815dbe390968fa02dc78b9a4a944", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "18643554-c12e-4d74-85c7-9d3095612781", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/debugging", "title": "Debugging", "tokens": 5079, "retrieve_doc": true, "source": "transformers"}, "hash": "f4acb9cf56d53fd50146da44cac65c22a97bf878ec53d4afaa490c329e9efe6e", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "755af5b4-1ba6-48f8-a798-322d3124bc34", "node_type": "1", "metadata": {}, "hash": "2f2e14cd8e43031c6afd03293286b1960d0b617145d293f7e238aee961e1a13d", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 12582, "end_char_idx": 15743, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
You can see that it was called from an attribute `dropout` inside `DenseReluDense` class. We can see
that it happened during the first layer, of the 2nd block, during the very first batch. Finally, the absolute largest
input elements was `6.27e+04` and same for the output was `inf`.

You can see here, that `T5DenseGatedGeluDense.forward` resulted in output activations, whose absolute max value was
around 62.7K, which is very close to fp16's top limit of 64K. In the next frame we have `Dropout` which renormalizes
the weights, after it zeroed some of the elements, which pushes the absolute max value to more than 64K, and we get an
overflow (`inf`).

As you can see it's the previous frames that we need to look into when the numbers start going into very large for fp16
numbers.

Let's match the report to the code from `models/t5/modeling_t5.py`:

```python
class T5DenseGatedGeluDense(nn.Module):
    def __init__(self, config):
        super().__init__()
        self.wi_0 = nn.Linear(config.d_model, config.d_ff, bias=False)
        self.wi_1 = nn.Linear(config.d_model, config.d_ff, bias=False)
        self.wo = nn.Linear(config.d_ff, config.d_model, bias=False)
        self.dropout = nn.Dropout(config.dropout_rate)
        self.gelu_act = ACT2FN["gelu_new"]

    def forward(self, hidden_states):
        hidden_gelu = self.gelu_act(self.wi_0(hidden_states))
        hidden_linear = self.wi_1(hidden_states)
        hidden_states = hidden_gelu * hidden_linear
        hidden_states = self.dropout(hidden_states)
        hidden_states = self.wo(hidden_states)
        return hidden_states
```

Now it's easy to see the `dropout` call, and all the previous calls as well.

Since the detection is happening in a forward hook, these reports are printed immediately after each `forward`
returns.

Going back to the full report, to act on it and to fix the problem, we need to go a few frames up where the numbers
started to go up and most likely switch to the `fp32` mode here, so that the numbers don't overflow when multiplied
or summed up. Of course, there might be other solutions. For example, we could turn off `amp` temporarily if it's
enabled, after moving the original `forward` into a helper wrapper, like so:

```python
def _forward(self, hidden_states):
    hidden_gelu = self.gelu_act(self.wi_0(hidden_states))
    hidden_linear = self.wi_1(hidden_states)
    hidden_states = hidden_gelu * hidden_linear
    hidden_states = self.dropout(hidden_states)
    hidden_states = self.wo(hidden_states)
    return hidden_states


import torch


def forward(self, hidden_states):
    if torch.is_autocast_enabled():
        with torch.cuda.amp.autocast(enabled=False):
            return self._forward(hidden_states)
    else:
        return self._forward(hidden_states)
```

Since the automatic detector only reports on inputs and outputs of full frames, once you know where to look, you may
want to analyse the intermediary stages of any specific `forward` function as well. In such a case you can use the
`detect_overflow` helper function to inject the detector where you want it, for example:

```python
from debug_utils import detect_overflow


key: _node_content
string_value:
{"id_": "755af5b4-1ba6-48f8-a798-322d3124bc34", "embedding": null, "metadata": {"url": "https://huggingface.co/docs/transformers/debugging", "title": "Debugging", "tokens": 5079, "retrieve_doc": true, "source": "transformers"}, "excluded_embed_metadata_keys": ["url", "tokens", "retrieve_doc", "source"], "excluded_llm_metadata_keys": ["title", "tokens", "retrieve_doc", "source"], "relationships": {"1": {"node_id": "3afbb714-b9f6-4e67-bda1-c03b779c2b6b", "node_type": "4", "metadata": {"url": "https://huggingface.co/docs/transformers/debugging", "title": "Debugging", "tokens": 5079, "retrieve_doc": true, "source": "transformers"}, "hash": "547ee66977115761f6778ec77a0f4395de63815dbe390968fa02dc78b9a4a944", "class_name": "RelatedNodeInfo"}, "2": {"node_id": "cc77445e-3136-42b5-ae77-6862a253c84e", "node_type": "1", "metadata": {"url": "https://huggingface.co/docs/transformers/debugging", "title": "Debugging", "tokens": 5079, "retrieve_doc": true, "source": "transformers"}, "hash": "1d74b58852baa6f2c03ffdf0315e92b06c54f64d0aa3d5d52ce2bd76a9040ca0", "class_name": "RelatedNodeInfo"}, "3": {"node_id": "9b843449-0ca2-4683-88f9-b2c07d508372", "node_type": "1", "metadata": {}, "hash": "22e9aef06fa3af10f84e5e9b19dfdb4165cbfd8a0a16ea156b8dce3c357c6e5e", "class_name": "RelatedNodeInfo"}}, "text": "", "mimetype": "text/plain", "start_char_idx": 14268, "end_char_idx": 17480, "text_template": "{metadata_str}\n\n{content}", "metadata_template": "{key}: {value}", "metadata_seperator": "\n", "class_name": "TextNode"}


key: chroma:document
string_value:
Since the detection is happening in a forward hook, these reports are printed immediately after each `forward`
returns.

Going back to the full report, to act on it and to fix the problem, we need to go a few frames up where the numbers
started to go up and most likely switch to the `fp32` mode here, so that the numbers don't overflow when multiplied
or summed up. Of course, there might be other solutions. For example, we could turn off `amp` temporarily if it's
enabled, after moving the original `forward` into a helper wrapper, like so:

```python
def _forward(self, hidden_states):
    hidden_gelu = self.gelu_act(self.wi_0(hidden_states))
    hidden_linear = self.wi_1(hidden_states)
    hidden_states = hidden_gelu * hidden_linear
    hidden_states = self.dropout(hidden_states)
    hidden_states = self.wo(hidden_states)
    return hidden_states


import torch


def forward(self, hidden_states):
    if torch.is_autocast_enabled():
        with torch.cuda.amp.autocast(enabled=False):
            return self._forward(hidden_states)
    else:
        return self._forward(hidden_states)
```

Since the automatic detector only reports on inputs and outputs of full frames, once you know where to look, you may
want to analyse the intermediary stages of any specific `forward` function as well. In such a case you can use the
`detect_overflow` helper function to inject the detector where you want it, for example:

```python
from debug_utils import detect_overflow


class T5LayerFF(nn.Module):
    [...]

    def forward(self, hidden_states):
        forwarded_states = self.layer_norm(hidden_states)
        detect_overflow(forwarded_states, "after layer_norm")
        forwarded_states = self.DenseReluDense(forwarded_states)
        detect_overflow(forwarded_states, "after DenseReluDense")
        return hidden_states + self.dropout(forwarded_states)
```

You can see that we added 2 of these and now we track if `inf` or `nan` for `forwarded_states` was detected
somewhere in between.

Actually, the detector already reports these because each of the calls in the example above is a `nn.Module`, but
let's say if you had some local direct calculations this is how you'd do that.

Additionally, if you're instantiating the debugger in your own code, you can adjust the number of frames printed from
its default, e.g.:

```python
from transformers.debug_utils import DebugUnderflowOverflow

debug_overflow = DebugUnderflowOverflow(model, max_frames_to_save=100)
```

### Specific batch absolute min and max value tracing

The same debugging class can be used for per-batch tracing with the underflow/overflow detection feature turned off.

Let's say you want to watch the absolute min and max values for all the ingredients of each `forward` call of a given
batch, and only do that for batches 1 and 3. Then you instantiate this class as:

```python
debug_overflow = DebugUnderflowOverflow(model, trace_batch_nums=[1, 3])
```

And now full batches 1 and 3 will be traced using the same format as the underflow/overflow detector does.

Batches are 0-indexed.

This is helpful if you know that the program starts misbehaving after a certain batch number, so you can fast-forward
right to that area.


