text stringlengths 5 58.6k | source stringclasses 470
values | url stringlengths 49 167 | source_section stringlengths 0 90 | file_type stringclasses 1
value | id stringlengths 3 6 |
|---|---|---|---|---|---|
Here you'll find techniques, tips and tricks that apply whether you are training a model, or running inference with it.
* [Instantiating a big model](big_models)
* [Troubleshooting performance issues](debugging) | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/performance.md | https://huggingface.co/docs/transformers/en/performance/#training-and-inference | #training-and-inference | .md | 32_4 |
This document is far from being complete and a lot more needs to be added, so if you have additions or corrections to
make please don't hesitate to open a PR or if you aren't sure start an Issue and we can discuss the details there.
When making contributions that A is better than B, please try to include a reproducib... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/performance.md | https://huggingface.co/docs/transformers/en/performance/#contribute | #contribute | .md | 32_5 |
<!--Copyright 2020 The HuggingFace Team. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agr... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/task_summary.md | https://huggingface.co/docs/transformers/en/task_summary/ | .md | 33_0 | |
🤗 Transformers is a library of pretrained state-of-the-art models for natural language processing (NLP), computer vision, and audio and speech processing tasks. Not only does the library contain Transformer models, but it also has non-Transformer models like modern convolutional networks for computer vision tasks. If ... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/task_summary.md | https://huggingface.co/docs/transformers/en/task_summary/#what--transformers-can-do | #what--transformers-can-do | .md | 33_1 |
Audio and speech processing tasks are a little different from the other modalities mainly because audio as an input is a continuous signal. Unlike text, a raw audio waveform can't be neatly split into discrete chunks the way a sentence can be divided into words. To get around this, the raw audio signal is typically sam... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/task_summary.md | https://huggingface.co/docs/transformers/en/task_summary/#audio | #audio | .md | 33_2 |
Audio classification is a task that labels audio data from a predefined set of classes. It is a broad category with many specific applications, some of which include:
* acoustic scene classification: label audio with a scene label ("office", "beach", "stadium")
* acoustic event detection: label audio with a sound eve... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/task_summary.md | https://huggingface.co/docs/transformers/en/task_summary/#audio-classification | #audio-classification | .md | 33_3 |
Automatic speech recognition (ASR) transcribes speech into text. It is one of the most common audio tasks due partly to speech being such a natural form of human communication. Today, ASR systems are embedded in "smart" technology products like speakers, phones, and cars. We can ask our virtual assistants to play music... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/task_summary.md | https://huggingface.co/docs/transformers/en/task_summary/#automatic-speech-recognition | #automatic-speech-recognition | .md | 33_4 |
One of the first and earliest successful computer vision tasks was recognizing images of zip code numbers using a [convolutional neural network (CNN)](glossary#convolution). An image is composed of pixels, and each pixel has a numerical value. This makes it easy to represent an image as a matrix of pixel values. Each p... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/task_summary.md | https://huggingface.co/docs/transformers/en/task_summary/#computer-vision | #computer-vision | .md | 33_5 |
Image classification labels an entire image from a predefined set of classes. Like most classification tasks, there are many practical use cases for image classification, some of which include:
* healthcare: label medical images to detect disease or monitor patient health
* environment: label satellite images to moni... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/task_summary.md | https://huggingface.co/docs/transformers/en/task_summary/#image-classification | #image-classification | .md | 33_6 |
Unlike image classification, object detection identifies multiple objects within an image and the objects' positions in an image (defined by the bounding box). Some example applications of object detection include:
* self-driving vehicles: detect everyday traffic objects such as other vehicles, pedestrians, and traff... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/task_summary.md | https://huggingface.co/docs/transformers/en/task_summary/#object-detection | #object-detection | .md | 33_7 |
Image segmentation is a pixel-level task that assigns every pixel in an image to a class. It differs from object detection, which uses bounding boxes to label and predict objects in an image because segmentation is more granular. Segmentation can detect objects at a pixel-level. There are several types of image segment... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/task_summary.md | https://huggingface.co/docs/transformers/en/task_summary/#image-segmentation | #image-segmentation | .md | 33_8 |
Depth estimation predicts the distance of each pixel in an image from the camera. This computer vision task is especially important for scene understanding and reconstruction. For example, in self-driving cars, vehicles need to understand how far objects like pedestrians, traffic signs, and other vehicles are to avoid ... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/task_summary.md | https://huggingface.co/docs/transformers/en/task_summary/#depth-estimation | #depth-estimation | .md | 33_9 |
NLP tasks are among the most common types of tasks because text is such a natural way for us to communicate. To get text into a format recognized by a model, it needs to be tokenized. This means dividing a sequence of text into separate words or subwords (tokens) and then converting these tokens into numbers. As a resu... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/task_summary.md | https://huggingface.co/docs/transformers/en/task_summary/#natural-language-processing | #natural-language-processing | .md | 33_10 |
Like classification tasks in any modality, text classification labels a sequence of text (it can be sentence-level, a paragraph, or a document) from a predefined set of classes. There are many practical applications for text classification, some of which include:
* sentiment analysis: label text according to some pol... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/task_summary.md | https://huggingface.co/docs/transformers/en/task_summary/#text-classification | #text-classification | .md | 33_11 |
In any NLP task, text is preprocessed by separating the sequence of text into individual words or subwords. These are known as [tokens](glossary#token). Token classification assigns each token a label from a predefined set of classes.
Two common types of token classification are:
* named entity recognition (NER): l... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/task_summary.md | https://huggingface.co/docs/transformers/en/task_summary/#token-classification | #token-classification | .md | 33_12 |
Question answering is another token-level task that returns an answer to a question, sometimes with context (open-domain) and other times without context (closed-domain). This task happens whenever we ask a virtual assistant something like whether a restaurant is open. It can also provide customer or technical support ... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/task_summary.md | https://huggingface.co/docs/transformers/en/task_summary/#question-answering | #question-answering | .md | 33_13 |
Summarization creates a shorter version of a text from a longer one while trying to preserve most of the meaning of the original document. Summarization is a sequence-to-sequence task; it outputs a shorter text sequence than the input. There are a lot of long-form documents that can be summarized to help readers quickl... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/task_summary.md | https://huggingface.co/docs/transformers/en/task_summary/#summarization | #summarization | .md | 33_14 |
Translation converts a sequence of text in one language to another. It is important in helping people from different backgrounds communicate with each other, help translate content to reach wider audiences, and even be a learning tool to help people learn a new language. Along with summarization, translation is a seque... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/task_summary.md | https://huggingface.co/docs/transformers/en/task_summary/#translation | #translation | .md | 33_15 |
Language modeling is a task that predicts a word in a sequence of text. It has become a very popular NLP task because a pretrained language model can be finetuned for many other downstream tasks. Lately, there has been a lot of interest in large language models (LLMs) which demonstrate zero- or few-shot learning. This ... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/task_summary.md | https://huggingface.co/docs/transformers/en/task_summary/#language-modeling | #language-modeling | .md | 33_16 |
Multimodal tasks require a model to process multiple data modalities (text, image, audio, video) to solve a particular problem. Image captioning is an example of a multimodal task where the model takes an image as input and outputs a sequence of text describing the image or some properties of the image.
Although mult... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/task_summary.md | https://huggingface.co/docs/transformers/en/task_summary/#multimodal | #multimodal | .md | 33_17 |
Document question answering is a task that answers natural language questions from a document. Unlike a token-level question answering task which takes text as input, document question answering takes an image of a document as input along with a question about the document and returns an answer. Document question answe... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/task_summary.md | https://huggingface.co/docs/transformers/en/task_summary/#document-question-answering | #document-question-answering | .md | 33_18 |
<!--Copyright 2022 The HuggingFace Team. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agr... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/hpo_train.md | https://huggingface.co/docs/transformers/en/hpo_train/ | .md | 34_0 | |
🤗 Transformers provides a [`Trainer`] class optimized for training 🤗 Transformers models, making it easier to start training without manually writing your own training loop. The [`Trainer`] provides API for hyperparameter search. This doc shows how to enable it in example. | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/hpo_train.md | https://huggingface.co/docs/transformers/en/hpo_train/#hyperparameter-search-using-trainer-api | #hyperparameter-search-using-trainer-api | .md | 34_1 |
[`Trainer`] supports four hyperparameter search backends currently:
[optuna](https://optuna.org/), [sigopt](https://sigopt.com/), [raytune](https://docs.ray.io/en/latest/tune/index.html) and [wandb](https://wandb.ai/site/sweeps).
you should install them before using them as the hyperparameter search backend
```bash
p... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/hpo_train.md | https://huggingface.co/docs/transformers/en/hpo_train/#hyperparameter-search-backend | #hyperparameter-search-backend | .md | 34_2 |
Define the hyperparameter search space, different backends need different format.
For sigopt, see sigopt [object_parameter](https://docs.sigopt.com/ai-module-api-references/api_reference/objects/object_parameter), it's like following:
```py
>>> def sigopt_hp_space(trial):
... return [
... {"bounds": {"min... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/hpo_train.md | https://huggingface.co/docs/transformers/en/hpo_train/#how-to-enable-hyperparameter-search-in-example | #how-to-enable-hyperparameter-search-in-example | .md | 34_3 |
Currently, Hyperparameter search for DDP is enabled for optuna and sigopt. Only the rank-zero process will generate the search trial and pass the argument to other ranks. | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/hpo_train.md | https://huggingface.co/docs/transformers/en/hpo_train/#hyperparameter-search-for-ddp-finetune | #hyperparameter-search-for-ddp-finetune | .md | 34_4 |
`transformers` is an opinionated framework; our philosophy is defined in the following [conceptual guide](./philosophy).
The core of that philosophy is exemplified by the [single model, single file](https://huggingface.co/blog/transformers-design-philosophy)
aspect of the library. This component's downside is that it... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/modular_transformers.md | https://huggingface.co/docs/transformers/en/modular_transformers/#modular-transformers | #modular-transformers | .md | 35_0 |
Modular Transformers introduces the concept of a "modular" file to a model folder. This modular file accepts code
that isn't typically accepted in modeling/processing files, as it allows importing from neighbouring models as well
as inheritance from classes to others.
This modular file defines models, processors, and... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/modular_transformers.md | https://huggingface.co/docs/transformers/en/modular_transformers/#what-is-it | #what-is-it | .md | 35_1 |
To generate a single file from the modular file, run the following command.
```bash
python utils/modular_model_converter.py --files-to-parse src/transformers/models/<your_model>/modular_<your_model>.py
```
The "linter", which unravels the inheritance and creates all single-files from the modular file, will flatten ... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/modular_transformers.md | https://huggingface.co/docs/transformers/en/modular_transformers/#details | #details | .md | 35_2 |
Run the command below to ensure the generated content matches `modular_<your_model>.py`
```bash
python utils/check_modular_conversion.py --files src/transformers/models/<your_model>/modular_<your_model>.py
``` | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/modular_transformers.md | https://huggingface.co/docs/transformers/en/modular_transformers/#enforcement | #enforcement | .md | 35_3 |
Here is a quick example with BERT and RoBERTa. The two models are intimately related: their modeling implementation
differs solely by a change in the embedding layer.
Instead of redefining the model entirely, here is what the `modular_roberta.py` file looks like for the modeling &
configuration classes (for the sake ... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/modular_transformers.md | https://huggingface.co/docs/transformers/en/modular_transformers/#examples | #examples | .md | 35_4 |
It is not a replacement for the modeling code (yet?), and if your model is not based on anything else that ever existed, then you can add a `modeling` file as usual. | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/modular_transformers.md | https://huggingface.co/docs/transformers/en/modular_transformers/#what-it-is-not | #what-it-is-not | .md | 35_5 |
To remove attributes that are not used in your modular model, and that you don't want to see in the unravelled modeling:
```python
class GemmaModel(LlamaModel): | class GemmaModel(PreTrainedModel):
def __init__(self, config): | def __init__(self, config):
super()._... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/modular_transformers.md | https://huggingface.co/docs/transformers/en/modular_transformers/#removing-attributes-and-functions | #removing-attributes-and-functions | .md | 35_6 |
If you define a new function in the `modular` file to be used inside a class, say
```python
def my_new_function(*args, **kwargs):
# Do something here
pass
class GemmaModel(LlamaModel):
def forward(*args, **kwargs):
# Call the function
example = my_new_function(*args, **kwargs)
# continue here
```
the `my_new_funct... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/modular_transformers.md | https://huggingface.co/docs/transformers/en/modular_transformers/#define-new-functions | #define-new-functions | .md | 35_7 |
We recently shipped a few features that allow you to go from:
```python
class GemmaTokenizer(LlamaTokenizer, PretrainedTokenizerFast): | class GemmaModel(nn.Module):
def __init__(self, eos_token="</s>"): | def __init__(self):
eos_token = AddedToken(eos_token) ... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/modular_transformers.md | https://huggingface.co/docs/transformers/en/modular_transformers/#calling-super | #calling-super | .md | 35_8 |
We now also support special cases like
```python
class GemmaVisionModel(CLIPModel):
pass
```
where the name of your class `GemmaVision` is not the same as the modular `Gemma`. This is super useful for composite models. | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/modular_transformers.md | https://huggingface.co/docs/transformers/en/modular_transformers/#special-naming | #special-naming | .md | 35_9 |
<!--Copyright 2022 The HuggingFace Team. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agr... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/perf_train_gpu_many.md | https://huggingface.co/docs/transformers/en/perf_train_gpu_many/ | .md | 36_0 | |
If training a model on a single GPU is too slow or if the model's weights do not fit in a single GPU's memory, transitioning
to a multi-GPU setup may be a viable option. Prior to making this transition, thoroughly explore all the strategies covered
in the [Methods and tools for efficient training on a single GPU](perf_... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/perf_train_gpu_many.md | https://huggingface.co/docs/transformers/en/perf_train_gpu_many/#efficient-training-on-multiple-gpus | #efficient-training-on-multiple-gpus | .md | 36_1 |
Begin by estimating how much vRAM is required to train your model. For models hosted on the 🤗 Hub, use our
[Model Memory Calculator](https://huggingface.co/spaces/hf-accelerate/model-memory-usage), which gives you
accurate calculations within a few percent margin.
**Parallelization strategy for a single Node / multi... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/perf_train_gpu_many.md | https://huggingface.co/docs/transformers/en/perf_train_gpu_many/#scalability-strategy | #scalability-strategy | .md | 36_2 |
Even with only 2 GPUs, you can readily leverage the accelerated training capabilities offered by PyTorch's built-in features,
such as `DataParallel` (DP) and `DistributedDataParallel` (DDP). Note that
[PyTorch documentation](https://pytorch.org/docs/master/generated/torch.nn.DataParallel.html) recommends to prefer
`Dis... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/perf_train_gpu_many.md | https://huggingface.co/docs/transformers/en/perf_train_gpu_many/#data-parallelism | #data-parallelism | .md | 36_3 |
To understand the key differences in inter-GPU communication overhead between the two methods, let's review the processes per batch:
[DDP](https://pytorch.org/docs/master/notes/ddp.html):
- At the start time the main process replicates the model once from GPU 0 to the rest of GPUs
- Then for each batch:
1. Each GPU... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/perf_train_gpu_many.md | https://huggingface.co/docs/transformers/en/perf_train_gpu_many/#dataparallel-vs-distributeddataparallel | #dataparallel-vs-distributeddataparallel | .md | 36_4 |
ZeRO-powered data parallelism (ZeRO-DP) is illustrated in the following diagram from this [blog post](https://www.microsoft.com/en-us/research/blog/zero-deepspeed-new-system-optimizations-enable-training-models-with-over-100-billion-parameters/).
<div class="flex justify-center">
<img src="https://huggingface.co/data... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/perf_train_gpu_many.md | https://huggingface.co/docs/transformers/en/perf_train_gpu_many/#zero-data-parallelism | #zero-data-parallelism | .md | 36_5 |
To explain Pipeline parallelism, we'll first look into Naive Model Parallelism (MP), also known as Vertical MP. This approach
involves distributing groups of model layers across multiple GPUs by assigning specific layers to specific GPUs with `.to()`.
As data flows through these layers, it is moved to the same GPU as t... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/perf_train_gpu_many.md | https://huggingface.co/docs/transformers/en/perf_train_gpu_many/#from-naive-model-parallelism-to-pipeline-parallelism | #from-naive-model-parallelism-to-pipeline-parallelism | .md | 36_6 |
In Tensor Parallelism, each GPU processes a slice of a tensor and only aggregates the full tensor for operations requiring it.
To describe this method, this section of the guide relies on the concepts and diagrams from the [Megatron-LM](https://github.com/NVIDIA/Megatron-LM)
paper: [Efficient Large-Scale Language Model... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/perf_train_gpu_many.md | https://huggingface.co/docs/transformers/en/perf_train_gpu_many/#tensor-parallelism | #tensor-parallelism | .md | 36_7 |
The following diagram from the DeepSpeed [pipeline tutorial](https://www.deepspeed.ai/tutorials/pipeline/) demonstrates
how one can combine DP with PP.
<div class="flex justify-center">
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/parallelism-zero-dp-pp.png" alt="DP + PP-2d"... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/perf_train_gpu_many.md | https://huggingface.co/docs/transformers/en/perf_train_gpu_many/#data-parallelism--pipeline-parallelism | #data-parallelism--pipeline-parallelism | .md | 36_8 |
To get an even more efficient training a 3D parallelism is used where PP is combined with TP and DP. This can be seen in the following diagram.
<div class="flex justify-center">
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/parallelism-deepspeed-3d.png" alt="dp-pp-tp-3d"/>
</... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/perf_train_gpu_many.md | https://huggingface.co/docs/transformers/en/perf_train_gpu_many/#data-parallelism--pipeline-parallelism--tensor-parallelism | #data-parallelism--pipeline-parallelism--tensor-parallelism | .md | 36_9 |
One of the main features of DeepSpeed is ZeRO, which is a super-scalable extension of DP. It has already been
discussed in [ZeRO Data Parallelism](#zero-data-parallelism). Normally it's a standalone feature that doesn't require PP or TP.
But it can be combined with PP and TP.
When ZeRO-DP is combined with PP (and opt... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/perf_train_gpu_many.md | https://huggingface.co/docs/transformers/en/perf_train_gpu_many/#zero-data-parallelism--pipeline-parallelism--tensor-parallelism | #zero-data-parallelism--pipeline-parallelism--tensor-parallelism | .md | 36_10 |
[FlexFlow](https://github.com/flexflow/FlexFlow) also solves the parallelization problem in a slightly different approach.
Paper: ["Beyond Data and Model Parallelism for Deep Neural Networks" by Zhihao Jia, Matei Zaharia, Alex Aiken](https://arxiv.org/abs/1807.05358)
It performs a sort of 4D Parallelism over Sample... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/perf_train_gpu_many.md | https://huggingface.co/docs/transformers/en/perf_train_gpu_many/#flexflow | #flexflow | .md | 36_11 |
When training on multiple GPUs, you can specify the number of GPUs to use and in what order. This can be useful for instance when you have GPUs with different computing power and want to use the faster GPU first. The selection process works for both [DistributedDataParallel](https://pytorch.org/docs/stable/generated/to... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/perf_train_gpu_many.md | https://huggingface.co/docs/transformers/en/perf_train_gpu_many/#gpu-selection | #gpu-selection | .md | 36_12 |
For example, if you have 4 GPUs and you only want to use the first 2:
<hfoptions id="select-gpu">
<hfoption id="torchrun">
Use the `--nproc_per_node` to select how many GPUs to use.
```bash
torchrun --nproc_per_node=2 trainer-program.py ...
```
</hfoption>
<hfoption id="Accelerate">
Use `--num_processes` to ... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/perf_train_gpu_many.md | https://huggingface.co/docs/transformers/en/perf_train_gpu_many/#number-of-gpus | #number-of-gpus | .md | 36_13 |
Now, to select which GPUs to use and their order, you'll use the `CUDA_VISIBLE_DEVICES` environment variable. It is easiest to set the environment variable in a `~/bashrc` or another startup config file. `CUDA_VISIBLE_DEVICES` is used to map which GPUs are used. For example, if you have 4 GPUs (0, 1, 2, 3) and you only... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/perf_train_gpu_many.md | https://huggingface.co/docs/transformers/en/perf_train_gpu_many/#order-of-gpus | #order-of-gpus | .md | 36_14 |
<!--Copyright 2023 The HuggingFace Team. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agr... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/chat_templating.md | https://huggingface.co/docs/transformers/en/chat_templating/ | .md | 37_0 | |
An increasingly common use case for LLMs is **chat**. In a chat context, rather than continuing a single string
of text (as is the case with a standard language model), the model instead continues a conversation that consists
of one or more **messages**, each of which includes a **role**, like "user" or "assistant", as... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/chat_templating.md | https://huggingface.co/docs/transformers/en/chat_templating/#introduction | #introduction | .md | 37_1 |
As you can see in the example above, chat templates are easy to use. Simply build a list of messages, with `role`
and `content` keys, and then pass it to the [`~PreTrainedTokenizer.apply_chat_template`] or [`~ProcessorMixin.apply_chat_template`] method
depending on what type of model you are using. Once you do that,
yo... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/chat_templating.md | https://huggingface.co/docs/transformers/en/chat_templating/#how-do-i-use-chat-templates | #how-do-i-use-chat-templates | .md | 37_2 |
Here's an example of preparing input for `model.generate()`, using `Zephyr` again:
```python
from transformers import AutoModelForCausalLM, AutoTokenizer
checkpoint = "HuggingFaceH4/zephyr-7b-beta"
tokenizer = AutoTokenizer.from_pretrained(checkpoint)
model = AutoModelForCausalLM.from_pretrained(checkpoint) # You m... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/chat_templating.md | https://huggingface.co/docs/transformers/en/chat_templating/#usage-with-text-only-llms | #usage-with-text-only-llms | .md | 37_3 |
For multimodal LLMs such as [LLaVA](https://huggingface.co/llava-hf) the prompts can be formatted in a similar way. The only difference is you need to pass input images/videos as well along with the text. Each `"content"`
has to be a list containing either a text or an image/video.
Here's an example of preparing inpu... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/chat_templating.md | https://huggingface.co/docs/transformers/en/chat_templating/#usage-with-multimodal-llms | #usage-with-multimodal-llms | .md | 37_4 |
Yes, there is! Our text generation pipelines support chat inputs, which makes it easy to use chat models. In the past,
we used to use a dedicated "ConversationalPipeline" class, but this has now been deprecated and its functionality
has been merged into the [`TextGenerationPipeline`]. Let's try the `Zephyr` example aga... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/chat_templating.md | https://huggingface.co/docs/transformers/en/chat_templating/#is-there-an-automated-pipeline-for-chat | #is-there-an-automated-pipeline-for-chat | .md | 37_5 |
You may have noticed that the `apply_chat_template` method has an `add_generation_prompt` argument. This argument tells
the template to add tokens that indicate the start of a bot response. For example, consider the following chat:
```python
messages = [
{"role": "user", "content": "Hi there!"},
{"role": "assistant",... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/chat_templating.md | https://huggingface.co/docs/transformers/en/chat_templating/#what-are-generation-prompts | #what-are-generation-prompts | .md | 37_6 |
When passing a list of messages to `apply_chat_template` or `TextGenerationPipeline`, you can choose
to format the chat so the model will continue the final message in the chat instead of starting a new one. This is done
by removing any end-of-sequence tokens that indicate the end of the final message, so that the mode... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/chat_templating.md | https://huggingface.co/docs/transformers/en/chat_templating/#what-does-continuefinalmessage-do | #what-does-continuefinalmessage-do | .md | 37_7 |
Yes! This is a good way to ensure that the chat template matches the tokens the model sees during training.
We recommend that you apply the chat template as a preprocessing step for your dataset. After this, you
can simply continue like any other language model training task. When training, you should usually set
`add_... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/chat_templating.md | https://huggingface.co/docs/transformers/en/chat_templating/#can-i-use-chat-templates-in-training | #can-i-use-chat-templates-in-training | .md | 37_8 |
The only argument that `apply_chat_template` requires is `messages`. However, you can pass any keyword
argument to `apply_chat_template` and it will be accessible inside the template. This gives you a lot of freedom to use
chat templates for many things. There are no restrictions on the names or the format of these arg... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/chat_templating.md | https://huggingface.co/docs/transformers/en/chat_templating/#advanced-extra-inputs-to-chat-templates | #advanced-extra-inputs-to-chat-templates | .md | 37_9 |
"Tool use" LLMs can choose to call functions as external tools before generating an answer. When passing tools
to a tool-use model, you can simply pass a list of functions to the `tools` argument:
```python
import datetime
def current_time():
"""Get the current local time as a string."""
return str(datetime.now())
... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/chat_templating.md | https://huggingface.co/docs/transformers/en/chat_templating/#advanced-tool-use--function-calling | #advanced-tool-use--function-calling | .md | 37_10 |
The sample code above is enough to list the available tools for your model, but what happens if it wants to actually use
one? If that happens, you should:
1. Parse the model's output to get the tool name(s) and arguments.
2. Add the model's tool call(s) to the conversation.
3. Call the corresponding function(s) with ... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/chat_templating.md | https://huggingface.co/docs/transformers/en/chat_templating/#passing-tool-results-to-the-model | #passing-tool-results-to-the-model | .md | 37_11 |
Let's walk through a tool use example, step by step. For this example, we will use an 8B `Hermes-2-Pro` model,
as it is one of the highest-performing tool-use models in its size category at the time of writing. If you have the
memory, you can consider using a larger model instead like [Command-R](https://huggingface.co... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/chat_templating.md | https://huggingface.co/docs/transformers/en/chat_templating/#a-complete-tool-use-example | #a-complete-tool-use-example | .md | 37_12 |
Each function you pass to the `tools` argument of `apply_chat_template` is converted into a
[JSON schema](https://json-schema.org/learn/getting-started-step-by-step). These schemas
are then passed to the model chat template. In other words, tool-use models do not see your functions directly, and they
never see the actu... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/chat_templating.md | https://huggingface.co/docs/transformers/en/chat_templating/#understanding-tool-schemas | #understanding-tool-schemas | .md | 37_13 |
"Retrieval-augmented generation" or "RAG" LLMs can search a corpus of documents for information before responding
to a query. This allows models to vastly expand their knowledge base beyond their limited context size. Our
recommendation for RAG models is that their template
should accept a `documents` argument. This sh... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/chat_templating.md | https://huggingface.co/docs/transformers/en/chat_templating/#advanced-retrieval-augmented-generation | #advanced-retrieval-augmented-generation | .md | 37_14 |
The chat template for a model is stored on the `tokenizer.chat_template` attribute. If no chat template is set, the
default template for that model class is used instead. Let's take a look at a `Zephyr` chat template, though note this
one is a little simplified from the actual one!
```
{%- for message in messages %}
... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/chat_templating.md | https://huggingface.co/docs/transformers/en/chat_templating/#advanced-how-do-chat-templates-work | #advanced-how-do-chat-templates-work | .md | 37_15 |
Simple, just write a jinja template and set `tokenizer.chat_template`. You may find it easier to start with an
existing template from another model and simply edit it for your needs! For example, we could take the LLaMA template
above and add "[ASST]" and "[/ASST]" to assistant messages:
```
{%- for message in messag... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/chat_templating.md | https://huggingface.co/docs/transformers/en/chat_templating/#how-do-i-create-a-chat-template | #how-do-i-create-a-chat-template | .md | 37_16 |
Some models use different templates for different use cases. For example, they might use one template for normal chat
and another for tool-use, or retrieval-augmented generation. In these cases, `tokenizer.chat_template` is a dictionary.
This can cause some confusion, and where possible, we recommend using a single tem... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/chat_templating.md | https://huggingface.co/docs/transformers/en/chat_templating/#why-do-some-models-have-multiple-templates | #why-do-some-models-have-multiple-templates | .md | 37_17 |
When setting the template for a model that's already been trained for chat, you should ensure that the template
exactly matches the message formatting that the model saw during training, or else you will probably experience
performance degradation. This is true even if you're training the model further - you will proba... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/chat_templating.md | https://huggingface.co/docs/transformers/en/chat_templating/#what-template-should-i-use | #what-template-should-i-use | .md | 37_18 |
If you have any chat models, you should set their `tokenizer.chat_template` attribute and test it using
[`~PreTrainedTokenizer.apply_chat_template`], then push the updated tokenizer to the Hub. This applies even if you're
not the model owner - if you're using a model with an empty chat template, or one that's still usi... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/chat_templating.md | https://huggingface.co/docs/transformers/en/chat_templating/#i-want-to-add-some-chat-templates-how-should-i-get-started | #i-want-to-add-some-chat-templates-how-should-i-get-started | .md | 37_19 |
<Tip>
The easiest way to get started with writing Jinja templates is to take a look at some existing ones. You can use
`print(tokenizer.chat_template)` for any chat model to see what template it's using. In general, models that support tool use have
much more complex templates than other models - so when you're just ... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/chat_templating.md | https://huggingface.co/docs/transformers/en/chat_templating/#advanced-template-writing-tips | #advanced-template-writing-tips | .md | 37_20 |
By default, Jinja will print any whitespace that comes before or after a block. This can be a problem for chat
templates, which generally want to be very precise with whitespace! To avoid this, we strongly recommend writing
your templates like this:
```
{%- for message in messages %}
{{- message['role'] + message['co... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/chat_templating.md | https://huggingface.co/docs/transformers/en/chat_templating/#trimming-whitespace | #trimming-whitespace | .md | 37_21 |
Inside your template, you will have access several special variables. The most important of these is `messages`,
which contains the chat history as a list of message dicts. However, there are several others. Not every
variable will be used in every template. The most common other variables are:
- `tools` contains a l... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/chat_templating.md | https://huggingface.co/docs/transformers/en/chat_templating/#special-variables | #special-variables | .md | 37_22 |
There is also a short list of callable functions available to you inside your templates. These are:
- `raise_exception(msg)`: Raises a `TemplateException`. This is useful for debugging, and for telling users when they're
doing something that your template doesn't support.
- `strftime_now(format_str)`: Equivalent to `... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/chat_templating.md | https://huggingface.co/docs/transformers/en/chat_templating/#callable-functions | #callable-functions | .md | 37_23 |
There are multiple implementations of Jinja in various languages. They generally have the same syntax,
but a key difference is that when you're writing a template in Python you can use Python methods, such as
`.lower()` on strings or `.items()` on dicts. This will break if someone tries to use your template on a non-Py... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/chat_templating.md | https://huggingface.co/docs/transformers/en/chat_templating/#compatibility-with-non-python-jinja | #compatibility-with-non-python-jinja | .md | 37_24 |
We mentioned above that `add_generation_prompt` is a special variable that will be accessible inside your template,
and is controlled by the user setting the `add_generation_prompt` flag. If your model expects a header for
assistant messages, then your template must support adding the header when `add_generation_prompt... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/chat_templating.md | https://huggingface.co/docs/transformers/en/chat_templating/#writing-generation-prompts | #writing-generation-prompts | .md | 37_25 |
When this feature was introduced, most templates were quite small, the Jinja equivalent of a "one-liner" script.
However, with new models and features like tool-use and RAG, some templates can be 100 lines long or more. When
writing templates like these, it's a good idea to write them in a separate file, using a text e... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/chat_templating.md | https://huggingface.co/docs/transformers/en/chat_templating/#writing-and-debugging-larger-templates | #writing-and-debugging-larger-templates | .md | 37_26 |
Although chat templates do not enforce a specific API for tools (or for anything, really), we recommend
template authors try to stick to a standard API where possible. The whole point of chat templates is to allow code
to be transferable across models, so deviating from the standard tools API means users will have to w... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/chat_templating.md | https://huggingface.co/docs/transformers/en/chat_templating/#writing-templates-for-tools | #writing-templates-for-tools | .md | 37_27 |
Your template should expect that the variable `tools` will either be null (if no tools are passed), or is a list
of JSON schema dicts. Our chat template methods allow users to pass tools as either JSON schema or Python functions, but when
functions are passed, we automatically generate JSON schema and pass that to your... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/chat_templating.md | https://huggingface.co/docs/transformers/en/chat_templating/#tool-definitions | #tool-definitions | .md | 37_28 |
Tool calls, if present, will be a list attached to a message with the "assistant" role. Note that `tool_calls` is
always a list, even though most tool-calling models only support single tool calls at a time, which means
the list will usually only have a single element. Here is a sample message dict containing a tool ca... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/chat_templating.md | https://huggingface.co/docs/transformers/en/chat_templating/#tool-calls | #tool-calls | .md | 37_29 |
Tool responses have a simple format: They are a message dict with the "tool" role, a "name" key giving the name
of the called function, and a "content" key containing the result of the tool call. Here is a sample tool response:
```json
{
"role": "tool",
"name": "multiply",
"content": "30"
}
```
You don't need to us... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/chat_templating.md | https://huggingface.co/docs/transformers/en/chat_templating/#tool-responses | #tool-responses | .md | 37_30 |
<!--Copyright 2020 The HuggingFace Team. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agr... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/add_new_model.md | https://huggingface.co/docs/transformers/en/add_new_model/ | .md | 38_0 | |
The 🤗 Transformers library is often able to offer new models thanks to community contributors. But this can be a challenging project and requires an in-depth knowledge of the 🤗 Transformers library and the model to implement. At Hugging Face, we're trying to empower more of the community to actively add models and we... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/add_new_model.md | https://huggingface.co/docs/transformers/en/add_new_model/#how-to-add-a-model-to--transformers | #how-to-add-a-model-to--transformers | .md | 38_1 |
First, you should get a general overview of 🤗 Transformers. 🤗 Transformers is a very opinionated library, so there is a
chance that you don't agree with some of the library's philosophies or design choices. From our experience, however, we
found that the fundamental design choices and philosophies of the library are ... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/add_new_model.md | https://huggingface.co/docs/transformers/en/add_new_model/#general-overview-of--transformers | #general-overview-of--transformers | .md | 38_2 |
To successfully add a model, it is important to understand the interaction between your model and its config,
[`PreTrainedModel`], and [`PretrainedConfig`]. For exemplary purposes, we will
call the model to be added to 🤗 Transformers `BrandNewBert`.
Let's take a look:
<img src="https://huggingface.co/datasets/hugg... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/add_new_model.md | https://huggingface.co/docs/transformers/en/add_new_model/#overview-of-models | #overview-of-models | .md | 38_3 |
When coding your new model, keep in mind that Transformers is an opinionated library and we have a few quirks of our
own regarding how code should be written :-)
1. The forward pass of your model should be fully written in the modeling file while being fully independent of other
models in the library. If you want to ... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/add_new_model.md | https://huggingface.co/docs/transformers/en/add_new_model/#code-style | #code-style | .md | 38_4 |
Not quite ready yet :-( This section will be added soon! | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/add_new_model.md | https://huggingface.co/docs/transformers/en/add_new_model/#overview-of-tokenizers | #overview-of-tokenizers | .md | 38_5 |
Everyone has different preferences of how to port a model so it can be very helpful for you to take a look at summaries
of how other contributors ported models to Hugging Face. Here is a list of community blog posts on how to port a model:
1. [Porting GPT2 Model](https://medium.com/huggingface/from-tensorflow-to-pyto... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/add_new_model.md | https://huggingface.co/docs/transformers/en/add_new_model/#step-by-step-recipe-to-add-a-model-to--transformers | #step-by-step-recipe-to-add-a-model-to--transformers | .md | 38_6 |
You should take some time to read *BrandNewBert's* paper, if such descriptive work exists. There might be large
sections of the paper that are difficult to understand. If this is the case, this is fine - don't worry! The goal is
not to get a deep theoretical understanding of the paper, but to extract the necessary info... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/add_new_model.md | https://huggingface.co/docs/transformers/en/add_new_model/#1-optional-theoretical-aspects-of-brandnewbert | #1-optional-theoretical-aspects-of-brandnewbert | .md | 38_7 |
1. Fork the [repository](https://github.com/huggingface/transformers) by clicking on the ‘Fork' button on the
repository's page. This creates a copy of the code under your GitHub user account.
2. Clone your `transformers` fork to your local disk, and add the base repository as a remote:
```bash
git clone https://gi... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/add_new_model.md | https://huggingface.co/docs/transformers/en/add_new_model/#2-next-prepare-your-environment | #2-next-prepare-your-environment | .md | 38_8 |
At first, you will work on the original *brand_new_bert* repository. Often, the original implementation is very
“researchy”. Meaning that documentation might be lacking and the code can be difficult to understand. But this should
be exactly your motivation to reimplement *brand_new_bert*. At Hugging Face, one of our ma... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/add_new_model.md | https://huggingface.co/docs/transformers/en/add_new_model/#3-4-run-a-pretrained-checkpoint-using-the-original-repository | #3-4-run-a-pretrained-checkpoint-using-the-original-repository | .md | 38_9 |
Next, you can finally start adding new code to 🤗 Transformers. Go into the clone of your 🤗 Transformers' fork:
```bash
cd transformers
```
In the special case that you are adding a model whose architecture exactly matches the model architecture of an
existing model you only have to add a conversion script as desc... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/add_new_model.md | https://huggingface.co/docs/transformers/en/add_new_model/#5-14-port-brandnewbert-to--transformers | #5-14-port-brandnewbert-to--transformers | .md | 38_10 |
Now, it's time to get some credit from the community for your work! Having completed a model addition is a major
contribution to Transformers and the whole NLP community. Your code and the ported pre-trained models will certainly be
used by hundreds and possibly even thousands of developers and researchers. You should ... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/add_new_model.md | https://huggingface.co/docs/transformers/en/add_new_model/#share-your-work | #share-your-work | .md | 38_11 |
We aim for `transformers` to have support for new model architectures and checkpoints as early as possible:
availability can range from day-0 (and hour-0) releases for some models, to a few days/weeks for others.
The availability of this is usually up to the model contributors, as well as how excited the community is... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/add_new_model.md | https://huggingface.co/docs/transformers/en/add_new_model/#model-additions-and-their-timeline-when-is-a-model-added-to-transformers | #model-additions-and-their-timeline-when-is-a-model-added-to-transformers | .md | 38_12 |
For a day-0 integration to work, we'll usually want to work hand-in-hand with you directly. In order to keep your
architecture private until your checkpoints and release are ready, we'll work together in a private fork of
transformers.
If you plan on having a transformers-first release, this is a great option: we run... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/add_new_model.md | https://huggingface.co/docs/transformers/en/add_new_model/#day-0-integration | #day-0-integration | .md | 38_13 |
A same-week integration usually happens when model authors do not reach out; but we see significant community
requests.
In order to specify you'd like for us to integrate a specific model, we'll redirect you to our
[issue tracker](https://github.com/huggingface/transformers/issues/new?assignees=&labels=New+model&proj... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/add_new_model.md | https://huggingface.co/docs/transformers/en/add_new_model/#same-week-integration | #same-week-integration | .md | 38_14 |
A post-release integration usually happens when there has not been sufficient activity/requests to warrant a same-week
integration, or that we lack the sufficient bandwidth to integrate it.
We very gladly welcome community contributions in those instances; more than half of the library was contributed
by contributors... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/add_new_model.md | https://huggingface.co/docs/transformers/en/add_new_model/#post-release-integration | #post-release-integration | .md | 38_15 |
Finally, transformers has a "remote-code" possibility, in which contributions are not made within the toolkit, but on
the Hub. This can be particularly interesting for groups that are using `transformers` as a backbone for their project,
but don't have the bandwidth to contribute the model to transformers directly.
I... | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/add_new_model.md | https://huggingface.co/docs/transformers/en/add_new_model/#code-on-hub-release | #code-on-hub-release | .md | 38_16 |
<!--⚠️ 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.
--> | /Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/pipeline_webserver.md | https://huggingface.co/docs/transformers/en/pipeline_webserver/ | .md | 39_0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.