source
stringclasses 470
values | url
stringlengths 49
167
| file_type
stringclasses 1
value | chunk
stringlengths 1
512
| chunk_id
stringlengths 5
9
|
---|---|---|---|---|
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/training.md | https://huggingface.co/docs/transformers/en/training/#prepare-a-dataset | .md | >>> dataset = load_dataset("yelp_review_full")
>>> dataset["train"][100]
{'label': 0, | 11_2_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/training.md | https://huggingface.co/docs/transformers/en/training/#prepare-a-dataset | .md | 'text': 'My expectations for McDonalds are t rarely high. But for one to still fail so spectacularly...that takes something special!\\nThe cashier took my friends\'s order, then promptly ignored me. I had to force myself in front of a cashier who opened his register to wait on the person BEHIND me. I waited over five minutes for a gigantic order that included precisely one kid\'s meal. After watching two people who ordered after me be handed their food, I asked where mine was. The manager started yelling | 11_2_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/training.md | https://huggingface.co/docs/transformers/en/training/#prepare-a-dataset | .md | meal. After watching two people who ordered after me be handed their food, I asked where mine was. The manager started yelling at the cashiers for \\"serving off their orders\\" when they didn\'t have their food. But neither cashier was anywhere near those controls, and the manager was the one serving food to customers and clearing the boards.\\nThe manager was rude when giving me my order. She didn\'t make sure that I had everything ON MY RECEIPT, and never even had the decency to apologize that I felt I | 11_2_3 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/training.md | https://huggingface.co/docs/transformers/en/training/#prepare-a-dataset | .md | my order. She didn\'t make sure that I had everything ON MY RECEIPT, and never even had the decency to apologize that I felt I was getting poor service.\\nI\'ve eaten at various McDonalds restaurants for over 30 years. I\'ve worked at more than one location. I expect bad days, bad moods, and the occasional mistake. But I have yet to have a decent experience at this store. It will remain a place I avoid unless someone in my party needs to avoid illness from low blood sugar. Perhaps I should go back to the | 11_2_4 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/training.md | https://huggingface.co/docs/transformers/en/training/#prepare-a-dataset | .md | remain a place I avoid unless someone in my party needs to avoid illness from low blood sugar. Perhaps I should go back to the racially biased service of Steak n Shake instead!'} | 11_2_5 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/training.md | https://huggingface.co/docs/transformers/en/training/#prepare-a-dataset | .md | ```
As you now know, you need a tokenizer to process the text and include a padding and truncation strategy to handle any variable sequence lengths. To process your dataset in one step, use 🤗 Datasets [`map`](https://huggingface.co/docs/datasets/process#map) method to apply a preprocessing function over the entire dataset:
```py
>>> from transformers import AutoTokenizer | 11_2_6 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/training.md | https://huggingface.co/docs/transformers/en/training/#prepare-a-dataset | .md | >>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-cased")
>>> def tokenize_function(examples):
... return tokenizer(examples["text"], padding="max_length", truncation=True) | 11_2_7 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/training.md | https://huggingface.co/docs/transformers/en/training/#prepare-a-dataset | .md | >>> tokenized_datasets = dataset.map(tokenize_function, batched=True)
```
If you like, you can create a smaller subset of the full dataset to fine-tune on to reduce the time it takes:
```py
>>> small_train_dataset = tokenized_datasets["train"].shuffle(seed=42).select(range(1000))
>>> small_eval_dataset = tokenized_datasets["test"].shuffle(seed=42).select(range(1000))
```
<a id='trainer'></a> | 11_2_8 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/training.md | https://huggingface.co/docs/transformers/en/training/#train | .md | At this point, you should follow the section corresponding to the framework you want to use. You can use the links
in the right sidebar to jump to the one you want - and if you want to hide all of the content for a given framework,
just use the button at the top-right of that framework's block!
<frameworkcontent>
<pt>
<Youtube id="nvBXf7s7vTI"/> | 11_3_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/training.md | https://huggingface.co/docs/transformers/en/training/#train-with-pytorch-trainer | .md | 🤗 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`] API supports a wide range of training options and features such as logging, gradient accumulation, and mixed precision. | 11_4_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/training.md | https://huggingface.co/docs/transformers/en/training/#train-with-pytorch-trainer | .md | Start by loading your model and specify the number of expected labels. From the Yelp Review [dataset card](https://huggingface.co/datasets/yelp_review_full#data-fields), you know there are five labels. | 11_4_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/training.md | https://huggingface.co/docs/transformers/en/training/#train-with-pytorch-trainer | .md | By default, the weights are loaded in full precision (torch.float32) regardless of the actual data type the weights are stored in such as torch.float16. Set `torch_dtype="auto"` to load the weights in the data type defined in a model's `config.json` file to automatically load the most memory-optimal data type.
```py
>>> from transformers import AutoModelForSequenceClassification | 11_4_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/training.md | https://huggingface.co/docs/transformers/en/training/#train-with-pytorch-trainer | .md | >>> model = AutoModelForSequenceClassification.from_pretrained("google-bert/bert-base-cased", num_labels=5, torch_dtype="auto")
```
<Tip>
You will see a warning about some of the pretrained weights not being used and some weights being randomly | 11_4_3 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/training.md | https://huggingface.co/docs/transformers/en/training/#train-with-pytorch-trainer | .md | ```
<Tip>
You will see a warning about some of the pretrained weights not being used and some weights being randomly
initialized. Don't worry, this is completely normal! The pretrained head of the BERT model is discarded, and replaced with a randomly initialized classification head. You will fine-tune this new model head on your sequence classification task, transferring the knowledge of the pretrained model to it.
</Tip> | 11_4_4 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/training.md | https://huggingface.co/docs/transformers/en/training/#training-hyperparameters | .md | Next, create a [`TrainingArguments`] class which contains all the hyperparameters you can tune as well as flags for activating different training options. For this tutorial you can start with the default training [hyperparameters](https://huggingface.co/docs/transformers/main_classes/trainer#transformers.TrainingArguments), but feel free to experiment with these to find your optimal settings.
Specify where to save the checkpoints from your training:
```py
>>> from transformers import TrainingArguments | 11_5_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/training.md | https://huggingface.co/docs/transformers/en/training/#training-hyperparameters | .md | >>> training_args = TrainingArguments(output_dir="test_trainer")
``` | 11_5_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/training.md | https://huggingface.co/docs/transformers/en/training/#evaluate | .md | [`Trainer`] does not automatically evaluate model performance during training. You'll need to pass [`Trainer`] a function to compute and report metrics. The [🤗 Evaluate](https://huggingface.co/docs/evaluate/index) library provides a simple [`accuracy`](https://huggingface.co/spaces/evaluate-metric/accuracy) function you can load with the [`evaluate.load`] (see this [quicktour](https://huggingface.co/docs/evaluate/a_quick_tour) for more information) function:
```py
>>> import numpy as np | 11_6_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/training.md | https://huggingface.co/docs/transformers/en/training/#evaluate | .md | ```py
>>> import numpy as np
>>> import evaluate | 11_6_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/training.md | https://huggingface.co/docs/transformers/en/training/#evaluate | .md | >>> metric = evaluate.load("accuracy")
```
Call [`~evaluate.compute`] on `metric` to calculate the accuracy of your predictions. Before passing your predictions to `compute`, you need to convert the logits to predictions (remember all 🤗 Transformers models return logits):
```py
>>> def compute_metrics(eval_pred):
... logits, labels = eval_pred
... predictions = np.argmax(logits, axis=-1)
... return metric.compute(predictions=predictions, references=labels)
``` | 11_6_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/training.md | https://huggingface.co/docs/transformers/en/training/#evaluate | .md | ... return metric.compute(predictions=predictions, references=labels)
```
If you'd like to monitor your evaluation metrics during fine-tuning, specify the `eval_strategy` parameter in your training arguments to report the evaluation metric at the end of each epoch:
```py
>>> from transformers import TrainingArguments, Trainer | 11_6_3 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/training.md | https://huggingface.co/docs/transformers/en/training/#evaluate | .md | >>> training_args = TrainingArguments(output_dir="test_trainer", eval_strategy="epoch")
``` | 11_6_4 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/training.md | https://huggingface.co/docs/transformers/en/training/#trainer | .md | Create a [`Trainer`] object with your model, training arguments, training and test datasets, and evaluation function:
```py
>>> trainer = Trainer(
... model=model,
... args=training_args,
... train_dataset=small_train_dataset,
... eval_dataset=small_eval_dataset,
... compute_metrics=compute_metrics,
... )
```
Then fine-tune your model by calling [`~transformers.Trainer.train`]:
```py
>>> trainer.train()
```
</pt>
<tf>
<a id='keras'></a>
<Youtube id="rnTGBy2ax1c"/> | 11_7_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/training.md | https://huggingface.co/docs/transformers/en/training/#train-a-tensorflow-model-with-keras | .md | You can also train 🤗 Transformers models in TensorFlow with the Keras API! | 11_8_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/training.md | https://huggingface.co/docs/transformers/en/training/#loading-data-for-keras | .md | When you want to train a 🤗 Transformers model with the Keras API, you need to convert your dataset to a format that
Keras understands. If your dataset is small, you can just convert the whole thing to NumPy arrays and pass it to Keras.
Let's try that first before we do anything more complicated.
First, load a dataset. We'll use the CoLA dataset from the [GLUE benchmark](https://huggingface.co/datasets/glue),
since it's a simple binary text classification task, and just take the training split for now. | 11_9_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/training.md | https://huggingface.co/docs/transformers/en/training/#loading-data-for-keras | .md | since it's a simple binary text classification task, and just take the training split for now.
```py
from datasets import load_dataset | 11_9_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/training.md | https://huggingface.co/docs/transformers/en/training/#loading-data-for-keras | .md | dataset = load_dataset("glue", "cola")
dataset = dataset["train"] # Just take the training split for now
```
Next, load a tokenizer and tokenize the data as NumPy arrays. Note that the labels are already a list of 0 and 1s,
so we can just convert that directly to a NumPy array without tokenization!
```py
from transformers import AutoTokenizer
import numpy as np | 11_9_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/training.md | https://huggingface.co/docs/transformers/en/training/#loading-data-for-keras | .md | tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-cased")
tokenized_data = tokenizer(dataset["sentence"], return_tensors="np", padding=True)
# Tokenizer returns a BatchEncoding, but we convert that to a dict for Keras
tokenized_data = dict(tokenized_data) | 11_9_3 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/training.md | https://huggingface.co/docs/transformers/en/training/#loading-data-for-keras | .md | labels = np.array(dataset["label"]) # Label is already an array of 0 and 1
```
Finally, load, [`compile`](https://keras.io/api/models/model_training_apis/#compile-method), and [`fit`](https://keras.io/api/models/model_training_apis/#fit-method) the model. Note that Transformers models all have a default task-relevant loss function, so you don't need to specify one unless you want to:
```py
from transformers import TFAutoModelForSequenceClassification
from tensorflow.keras.optimizers import Adam | 11_9_4 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/training.md | https://huggingface.co/docs/transformers/en/training/#loading-data-for-keras | .md | # Load and compile our model
model = TFAutoModelForSequenceClassification.from_pretrained("google-bert/bert-base-cased")
# Lower learning rates are often better for fine-tuning transformers
model.compile(optimizer=Adam(3e-5)) # No loss argument! | 11_9_5 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/training.md | https://huggingface.co/docs/transformers/en/training/#loading-data-for-keras | .md | model.fit(tokenized_data, labels)
```
<Tip>
You don't have to pass a loss argument to your models when you `compile()` them! Hugging Face models automatically
choose a loss that is appropriate for their task and model architecture if this argument is left blank. You can always
override this by specifying a loss yourself if you want to!
</Tip>
This approach works great for smaller datasets, but for larger datasets, you might find it starts to become a problem. Why? | 11_9_6 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/training.md | https://huggingface.co/docs/transformers/en/training/#loading-data-for-keras | .md | This approach works great for smaller datasets, but for larger datasets, you might find it starts to become a problem. Why?
Because the tokenized array and labels would have to be fully loaded into memory, and because NumPy doesn’t handle
“jagged” arrays, so every tokenized sample would have to be padded to the length of the longest sample in the whole
dataset. That’s going to make your array even bigger, and all those padding tokens will slow down training too! | 11_9_7 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/training.md | https://huggingface.co/docs/transformers/en/training/#loading-data-as-a-tfdatadataset | .md | If you want to avoid slowing down training, you can load your data as a `tf.data.Dataset` instead. Although you can write your own
`tf.data` pipeline if you want, we have two convenience methods for doing this:
- [`~TFPreTrainedModel.prepare_tf_dataset`]: This is the method we recommend in most cases. Because it is a method
on your model, it can inspect the model to automatically figure out which columns are usable as model inputs, and
discard the others to make a simpler, more performant dataset. | 11_10_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/training.md | https://huggingface.co/docs/transformers/en/training/#loading-data-as-a-tfdatadataset | .md | discard the others to make a simpler, more performant dataset.
- [`~datasets.Dataset.to_tf_dataset`]: This method is more low-level, and is useful when you want to exactly control how
your dataset is created, by specifying exactly which `columns` and `label_cols` to include.
Before you can use [`~TFPreTrainedModel.prepare_tf_dataset`], you will need to add the tokenizer outputs to your dataset as columns, as shown in
the following code sample:
```py
def tokenize_dataset(data): | 11_10_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/training.md | https://huggingface.co/docs/transformers/en/training/#loading-data-as-a-tfdatadataset | .md | the following code sample:
```py
def tokenize_dataset(data):
# Keys of the returned dictionary will be added to the dataset as columns
return tokenizer(data["text"]) | 11_10_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/training.md | https://huggingface.co/docs/transformers/en/training/#loading-data-as-a-tfdatadataset | .md | dataset = dataset.map(tokenize_dataset)
```
Remember that Hugging Face datasets are stored on disk by default, so this will not inflate your memory usage! Once the
columns have been added, you can stream batches from the dataset and add padding to each batch, which greatly
reduces the number of padding tokens compared to padding the entire dataset.
```py
>>> tf_dataset = model.prepare_tf_dataset(dataset["train"], batch_size=16, shuffle=True, tokenizer=tokenizer)
``` | 11_10_3 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/training.md | https://huggingface.co/docs/transformers/en/training/#loading-data-as-a-tfdatadataset | .md | ```py
>>> tf_dataset = model.prepare_tf_dataset(dataset["train"], batch_size=16, shuffle=True, tokenizer=tokenizer)
```
Note that in the code sample above, you need to pass the tokenizer to `prepare_tf_dataset` so it can correctly pad batches as they're loaded.
If all the samples in your dataset are the same length and no padding is necessary, you can skip this argument.
If you need to do something more complex than just padding samples (e.g. corrupting tokens for masked language | 11_10_4 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/training.md | https://huggingface.co/docs/transformers/en/training/#loading-data-as-a-tfdatadataset | .md | If you need to do something more complex than just padding samples (e.g. corrupting tokens for masked language
modelling), you can use the `collate_fn` argument instead to pass a function that will be called to transform the
list of samples into a batch and apply any preprocessing you want. See our
[examples](https://github.com/huggingface/transformers/tree/main/examples) or
[notebooks](https://huggingface.co/docs/transformers/notebooks) to see this approach in action. | 11_10_5 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/training.md | https://huggingface.co/docs/transformers/en/training/#loading-data-as-a-tfdatadataset | .md | [notebooks](https://huggingface.co/docs/transformers/notebooks) to see this approach in action.
Once you've created a `tf.data.Dataset`, you can compile and fit the model as before:
```py
model.compile(optimizer=Adam(3e-5)) # No loss argument! | 11_10_6 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/training.md | https://huggingface.co/docs/transformers/en/training/#loading-data-as-a-tfdatadataset | .md | model.fit(tf_dataset)
```
</tf>
</frameworkcontent>
<a id='pytorch_native'></a> | 11_10_7 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/training.md | https://huggingface.co/docs/transformers/en/training/#train-in-native-pytorch | .md | <frameworkcontent>
<pt>
<Youtube id="Dh9CL8fyG80"/>
[`Trainer`] takes care of the training loop and allows you to fine-tune a model in a single line of code. For users who prefer to write their own training loop, you can also fine-tune a 🤗 Transformers model in native PyTorch.
At this point, you may need to restart your notebook or execute the following code to free some memory:
```py
from accelerate.utils.memory import clear_device_cache
del model
del trainer
clear_device_cache()
``` | 11_11_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/training.md | https://huggingface.co/docs/transformers/en/training/#train-in-native-pytorch | .md | ```py
from accelerate.utils.memory import clear_device_cache
del model
del trainer
clear_device_cache()
```
Next, manually postprocess `tokenized_dataset` to prepare it for training.
1. Remove the `text` column because the model does not accept raw text as an input:
```py
>>> tokenized_datasets = tokenized_datasets.remove_columns(["text"])
```
2. Rename the `label` column to `labels` because the model expects the argument to be named `labels`:
```py | 11_11_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/training.md | https://huggingface.co/docs/transformers/en/training/#train-in-native-pytorch | .md | ```
2. Rename the `label` column to `labels` because the model expects the argument to be named `labels`:
```py
>>> tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
```
3. Set the format of the dataset to return PyTorch tensors instead of lists:
```py
>>> tokenized_datasets.set_format("torch")
```
Then create a smaller subset of the dataset as previously shown to speed up the fine-tuning:
```py | 11_11_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/training.md | https://huggingface.co/docs/transformers/en/training/#train-in-native-pytorch | .md | ```
Then create a smaller subset of the dataset as previously shown to speed up the fine-tuning:
```py
>>> small_train_dataset = tokenized_datasets["train"].shuffle(seed=42).select(range(1000))
>>> small_eval_dataset = tokenized_datasets["test"].shuffle(seed=42).select(range(1000))
``` | 11_11_3 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/training.md | https://huggingface.co/docs/transformers/en/training/#dataloader | .md | Create a `DataLoader` for your training and test datasets so you can iterate over batches of data:
```py
>>> from torch.utils.data import DataLoader
>>> train_dataloader = DataLoader(small_train_dataset, shuffle=True, batch_size=8)
>>> eval_dataloader = DataLoader(small_eval_dataset, batch_size=8)
```
Load your model with the number of expected labels:
```py
>>> from transformers import AutoModelForSequenceClassification | 11_12_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/training.md | https://huggingface.co/docs/transformers/en/training/#dataloader | .md | >>> model = AutoModelForSequenceClassification.from_pretrained("google-bert/bert-base-cased", num_labels=5)
``` | 11_12_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/training.md | https://huggingface.co/docs/transformers/en/training/#optimizer-and-learning-rate-scheduler | .md | Create an optimizer and learning rate scheduler to fine-tune the model. Let's use the [`AdamW`](https://pytorch.org/docs/stable/generated/torch.optim.AdamW.html) optimizer from PyTorch:
```py
>>> from torch.optim import AdamW
>>> optimizer = AdamW(model.parameters(), lr=5e-5)
```
Create the default learning rate scheduler from [`Trainer`]:
```py
>>> from transformers import get_scheduler | 11_13_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/training.md | https://huggingface.co/docs/transformers/en/training/#optimizer-and-learning-rate-scheduler | .md | >>> num_epochs = 3
>>> num_training_steps = num_epochs * len(train_dataloader)
>>> lr_scheduler = get_scheduler(
... name="linear", optimizer=optimizer, num_warmup_steps=0, num_training_steps=num_training_steps
... )
```
Lastly, specify `device` to use a GPU if you have access to one. Otherwise, training on a CPU may take several hours instead of a couple of minutes.
```py
>>> import torch
>>> from accelerate.test_utils.testing import get_backend | 11_13_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/training.md | https://huggingface.co/docs/transformers/en/training/#optimizer-and-learning-rate-scheduler | .md | >>> device, _, _ = get_backend() # automatically detects the underlying device type (CUDA, CPU, XPU, MPS, etc.)
>>> model.to(device)
```
<Tip>
Get free access to a cloud GPU if you don't have one with a hosted notebook like [Colaboratory](https://colab.research.google.com/) or [SageMaker StudioLab](https://studiolab.sagemaker.aws/).
</Tip>
Great, now you are ready to train! 🥳 | 11_13_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/training.md | https://huggingface.co/docs/transformers/en/training/#training-loop | .md | To keep track of your training progress, use the [tqdm](https://tqdm.github.io/) library to add a progress bar over the number of training steps:
```py
>>> from tqdm.auto import tqdm
>>> progress_bar = tqdm(range(num_training_steps))
>>> model.train()
>>> for epoch in range(num_epochs):
... for batch in train_dataloader:
... batch = {k: v.to(device) for k, v in batch.items()}
... outputs = model(**batch)
... loss = outputs.loss
... loss.backward() | 11_14_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/training.md | https://huggingface.co/docs/transformers/en/training/#training-loop | .md | ... optimizer.step()
... lr_scheduler.step()
... optimizer.zero_grad()
... progress_bar.update(1)
``` | 11_14_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/training.md | https://huggingface.co/docs/transformers/en/training/#evaluate | .md | Just like how you added an evaluation function to [`Trainer`], you need to do the same when you write your own training loop. But instead of calculating and reporting the metric at the end of each epoch, this time you'll accumulate all the batches with [`~evaluate.add_batch`] and calculate the metric at the very end.
```py
>>> import evaluate | 11_15_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/training.md | https://huggingface.co/docs/transformers/en/training/#evaluate | .md | >>> metric = evaluate.load("accuracy")
>>> model.eval()
>>> for batch in eval_dataloader:
... batch = {k: v.to(device) for k, v in batch.items()}
... with torch.no_grad():
... outputs = model(**batch)
... logits = outputs.logits
... predictions = torch.argmax(logits, dim=-1)
... metric.add_batch(predictions=predictions, references=batch["labels"])
>>> metric.compute()
```
</pt>
</frameworkcontent>
<a id='additional-resources'></a> | 11_15_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/training.md | https://huggingface.co/docs/transformers/en/training/#additional-resources | .md | For more fine-tuning examples, refer to:
- [🤗 Transformers Examples](https://github.com/huggingface/transformers/tree/main/examples) includes scripts
to train common NLP tasks in PyTorch and TensorFlow.
- [🤗 Transformers Notebooks](notebooks) contains various notebooks on how to fine-tune a model for specific tasks in PyTorch and TensorFlow. | 11_16_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/conversations.md | https://huggingface.co/docs/transformers/en/conversations/ | .md | <!--Copyright 2024 The HuggingFace Team. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or 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 | 12_0_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/conversations.md | https://huggingface.co/docs/transformers/en/conversations/ | .md | 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.
--> | 12_0_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/conversations.md | https://huggingface.co/docs/transformers/en/conversations/#chatting-with-transformers | .md | If you're reading this article, you're almost certainly aware of **chat models**. Chat models are conversational
AIs that you can send and receive messages with. The most famous of these is the proprietary ChatGPT, but there are
now many open-source chat models which match or even substantially exceed its performance. These models are free to
download and run on a local machine. Although the largest and most capable models require high-powered hardware | 12_1_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/conversations.md | https://huggingface.co/docs/transformers/en/conversations/#chatting-with-transformers | .md | download and run on a local machine. Although the largest and most capable models require high-powered hardware
and lots of memory to run, there are smaller models that will run perfectly well on a single consumer GPU, or even
an ordinary desktop or notebook CPU.
This guide will help you get started with chat models. We'll start with a brief quickstart guide that uses a convenient,
high-level "pipeline". This is all you need if you just want to start running a chat model | 12_1_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/conversations.md | https://huggingface.co/docs/transformers/en/conversations/#chatting-with-transformers | .md | high-level "pipeline". This is all you need if you just want to start running a chat model
immediately. After the quickstart, we'll move on to more detailed information about
what exactly chat models are, how to choose an appropriate one, and a low-level breakdown of each of the
steps involved in talking to a chat model. We'll also give some tips on optimizing the performance and memory usage
of your chat models. | 12_1_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/conversations.md | https://huggingface.co/docs/transformers/en/conversations/#quickstart | .md | If you have no time for details, here's the brief summary: Chat models continue chats. This means that you pass them
a conversation history, which can be as short as a single user message, and the model will continue the conversation
by adding its response. Let's see this in action. First, let's build a chat:
```python
chat = [
{"role": "system", "content": "You are a sassy, wise-cracking robot as imagined by Hollywood circa 1986."}, | 12_2_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/conversations.md | https://huggingface.co/docs/transformers/en/conversations/#quickstart | .md | ```python
chat = [
{"role": "system", "content": "You are a sassy, wise-cracking robot as imagined by Hollywood circa 1986."},
{"role": "user", "content": "Hey, can you tell me any fun things to do in New York?"}
]
```
Notice that in addition to the user's message, we added a **system** message at the start of the conversation. Not all
chat models support system messages, but when they do, they represent high-level directives about how the model | 12_2_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/conversations.md | https://huggingface.co/docs/transformers/en/conversations/#quickstart | .md | chat models support system messages, but when they do, they represent high-level directives about how the model
should behave in the conversation. You can use this to guide the model - whether you want short or long responses,
lighthearted or serious ones, and so on. If you want the model to do useful work instead of
practicing its improv routine, you can either omit the system message or try a terse one such as "You are a helpful and intelligent
AI assistant who responds to user queries." | 12_2_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/conversations.md | https://huggingface.co/docs/transformers/en/conversations/#quickstart | .md | AI assistant who responds to user queries."
Once you have a chat, the quickest way to continue it is using the [`TextGenerationPipeline`].
Let's see this in action with `LLaMA-3`. Note that `LLaMA-3` is a gated model, which means you will need to
[apply for access](https://huggingface.co/meta-llama/Meta-Llama-3-8B-Instruct) and log in with your Hugging Face
account to use it. We'll also use `device_map="auto"`, which will load the model on GPU if there's enough memory | 12_2_3 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/conversations.md | https://huggingface.co/docs/transformers/en/conversations/#quickstart | .md | account to use it. We'll also use `device_map="auto"`, which will load the model on GPU if there's enough memory
for it, and set the dtype to `torch.bfloat16` to save memory:
```python
import torch
from transformers import pipeline | 12_2_4 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/conversations.md | https://huggingface.co/docs/transformers/en/conversations/#quickstart | .md | pipe = pipeline("text-generation", "meta-llama/Meta-Llama-3-8B-Instruct", torch_dtype=torch.bfloat16, device_map="auto")
response = pipe(chat, max_new_tokens=512)
print(response[0]['generated_text'][-1]['content'])
```
And you'll get:
```text
(sigh) Oh boy, you're asking me for advice? You're gonna need a map, pal! Alright,
alright, I'll give you the lowdown. But don't say I didn't warn you, I'm a robot, not a tour guide! | 12_2_5 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/conversations.md | https://huggingface.co/docs/transformers/en/conversations/#quickstart | .md | So, you wanna know what's fun to do in the Big Apple? Well, let me tell you, there's a million
things to do, but I'll give you the highlights. First off, you gotta see the sights: the Statue of
Liberty, Central Park, Times Square... you know, the usual tourist traps. But if you're lookin' for
something a little more... unusual, I'd recommend checkin' out the Museum of Modern Art. It's got
some wild stuff, like that Warhol guy's soup cans and all that jazz. | 12_2_6 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/conversations.md | https://huggingface.co/docs/transformers/en/conversations/#quickstart | .md | And if you're feelin' adventurous, take a walk across the Brooklyn Bridge. Just watch out for
those pesky pigeons, they're like little feathered thieves! (laughs) Get it? Thieves? Ah, never mind.
Now, if you're lookin' for some serious fun, hit up the comedy clubs in Greenwich Village. You might
even catch a glimpse of some up-and-coming comedians... or a bunch of wannabes tryin' to make it big. (winks) | 12_2_7 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/conversations.md | https://huggingface.co/docs/transformers/en/conversations/#quickstart | .md | And finally, if you're feelin' like a real New Yorker, grab a slice of pizza from one of the many amazing
pizzerias around the city. Just don't try to order a "robot-sized" slice, trust me, it won't end well. (laughs) | 12_2_8 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/conversations.md | https://huggingface.co/docs/transformers/en/conversations/#quickstart | .md | So, there you have it, pal! That's my expert advice on what to do in New York. Now, if you'll
excuse me, I've got some oil changes to attend to. (winks)
```
You can continue the chat by appending your own response to it. The
`response` object returned by the pipeline actually contains the entire chat so far, so we can simply append
a message and pass it back:
```python
chat = response[0]['generated_text']
chat.append(
{"role": "user", "content": "Wait, what's so wild about soup cans?"}
) | 12_2_9 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/conversations.md | https://huggingface.co/docs/transformers/en/conversations/#quickstart | .md | chat = response[0]['generated_text']
chat.append(
{"role": "user", "content": "Wait, what's so wild about soup cans?"}
)
response = pipe(chat, max_new_tokens=512)
print(response[0]['generated_text'][-1]['content'])
```
And you'll get:
```text
(laughs) Oh, you're killin' me, pal! You don't get it, do you? Warhol's soup cans are like, art, man!
It's like, he took something totally mundane, like a can of soup, and turned it into a masterpiece. It's | 12_2_10 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/conversations.md | https://huggingface.co/docs/transformers/en/conversations/#quickstart | .md | It's like, he took something totally mundane, like a can of soup, and turned it into a masterpiece. It's
like, "Hey, look at me, I'm a can of soup, but I'm also a work of art!"
(sarcastically) Oh, yeah, real original, Andy. | 12_2_11 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/conversations.md | https://huggingface.co/docs/transformers/en/conversations/#quickstart | .md | But, you know, back in the '60s, it was like, a big deal. People were all about challenging the
status quo, and Warhol was like, the king of that. He took the ordinary and made it extraordinary.
And, let me tell you, it was like, a real game-changer. I mean, who would've thought that a can of soup could be art? (laughs) | 12_2_12 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/conversations.md | https://huggingface.co/docs/transformers/en/conversations/#quickstart | .md | But, hey, you're not alone, pal. I mean, I'm a robot, and even I don't get it. (winks)
But, hey, that's what makes art, art, right? (laughs)
```
The remainder of this tutorial will cover specific topics such
as performance and memory, or how to select a chat model for your needs. | 12_2_13 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/conversations.md | https://huggingface.co/docs/transformers/en/conversations/#choosing-a-chat-model | .md | There are an enormous number of different chat models available on the [Hugging Face Hub](https://huggingface.co/models?pipeline_tag=text-generation&sort=trending),
and new users often feel very overwhelmed by the selection offered. Don't be, though! You really need to just focus on
two important considerations:
- The model's size, which will determine if you can fit it in memory and how quickly it will
run.
- The quality of the model's chat output. | 12_3_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/conversations.md | https://huggingface.co/docs/transformers/en/conversations/#choosing-a-chat-model | .md | run.
- The quality of the model's chat output.
In general, these are correlated - bigger models tend to be
more capable, but even so there's a lot of variation at a given size point! | 12_3_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/conversations.md | https://huggingface.co/docs/transformers/en/conversations/#size-and-model-naming | .md | The size of a model is easy to spot - it's the number in the model name, like "8B" or "70B". This is the number of
**parameters** in the model. Without quantization, you should expect to need about 2 bytes of memory per parameter.
This means that an "8B" model with 8 billion parameters will need about 16GB of memory just to fit the parameters,
plus a little extra for other overhead. It's a good fit for a high-end consumer GPU with 24GB of memory, such as a 3090
or 4090. | 12_4_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/conversations.md | https://huggingface.co/docs/transformers/en/conversations/#size-and-model-naming | .md | or 4090.
Some chat models are "Mixture of Experts" models. These may list their sizes in different ways, such as "8x7B" or
"141B-A35B". The numbers are a little fuzzier here, but in general you can read this as saying that the model
has approximately 56 (8x7) billion parameters in the first case, or 141 billion parameters in the second case.
Note that it is very common to use quantization techniques to reduce the memory usage per parameter to 8 bits, 4 bits, | 12_4_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/conversations.md | https://huggingface.co/docs/transformers/en/conversations/#size-and-model-naming | .md | Note that it is very common to use quantization techniques to reduce the memory usage per parameter to 8 bits, 4 bits,
or even less. This topic is discussed in more detail in the [Memory considerations](#memory-considerations) section below. | 12_4_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/conversations.md | https://huggingface.co/docs/transformers/en/conversations/#but-which-chat-model-is-best | .md | Even once you know the size of chat model you can run, there's still a lot of choice out there. One way to sift through
it all is to consult **leaderboards**. Two of the most popular leaderboards are the [OpenLLM Leaderboard](https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard)
and the [LMSys Chatbot Arena Leaderboard](https://chat.lmsys.org/?leaderboard). Note that the LMSys leaderboard | 12_5_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/conversations.md | https://huggingface.co/docs/transformers/en/conversations/#but-which-chat-model-is-best | .md | and the [LMSys Chatbot Arena Leaderboard](https://chat.lmsys.org/?leaderboard). Note that the LMSys leaderboard
also includes proprietary models - look at the `licence` column to identify open-source ones that you can download, then
search for them on the [Hugging Face Hub](https://huggingface.co/models?pipeline_tag=text-generation&sort=trending). | 12_5_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/conversations.md | https://huggingface.co/docs/transformers/en/conversations/#specialist-domains | .md | Some models may be specialized for certain domains, such as medical or legal text, or non-English languages.
If you're working in these domains, you may find that a specialized model will give you big performance benefits.
Don't automatically assume that, though! Particularly when specialized models are smaller or older than the current
cutting-edge, a top-end general-purpose model may still outclass them. Thankfully, we are beginning to see | 12_6_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/conversations.md | https://huggingface.co/docs/transformers/en/conversations/#specialist-domains | .md | cutting-edge, a top-end general-purpose model may still outclass them. Thankfully, we are beginning to see
[domain-specific leaderboards](https://huggingface.co/blog/leaderboard-medicalllm) that should make it easier to locate
the best models for specialized domains. | 12_6_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/conversations.md | https://huggingface.co/docs/transformers/en/conversations/#what-happens-inside-the-pipeline | .md | The quickstart above used a high-level pipeline to chat with a chat model, which is convenient, but not the
most flexible. Let's take a more low-level approach, to see each of the steps involved in chat. Let's start with
a code sample, and then break it down:
```python
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch | 12_7_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/conversations.md | https://huggingface.co/docs/transformers/en/conversations/#what-happens-inside-the-pipeline | .md | # Prepare the input as before
chat = [
{"role": "system", "content": "You are a sassy, wise-cracking robot as imagined by Hollywood circa 1986."},
{"role": "user", "content": "Hey, can you tell me any fun things to do in New York?"}
]
# 1: Load the model and tokenizer
model = AutoModelForCausalLM.from_pretrained("meta-llama/Meta-Llama-3-8B-Instruct", device_map="auto", torch_dtype=torch.bfloat16)
tokenizer = AutoTokenizer.from_pretrained("meta-llama/Meta-Llama-3-8B-Instruct") | 12_7_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/conversations.md | https://huggingface.co/docs/transformers/en/conversations/#what-happens-inside-the-pipeline | .md | # 2: Apply the chat template
formatted_chat = tokenizer.apply_chat_template(chat, tokenize=False, add_generation_prompt=True)
print("Formatted chat:\n", formatted_chat) | 12_7_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/conversations.md | https://huggingface.co/docs/transformers/en/conversations/#what-happens-inside-the-pipeline | .md | # 3: Tokenize the chat (This can be combined with the previous step using tokenize=True)
inputs = tokenizer(formatted_chat, return_tensors="pt", add_special_tokens=False)
# Move the tokenized inputs to the same device the model is on (GPU/CPU)
inputs = {key: tensor.to(model.device) for key, tensor in inputs.items()}
print("Tokenized inputs:\n", inputs)
# 4: Generate text from the model
outputs = model.generate(**inputs, max_new_tokens=512, temperature=0.1)
print("Generated tokens:\n", outputs) | 12_7_3 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/conversations.md | https://huggingface.co/docs/transformers/en/conversations/#what-happens-inside-the-pipeline | .md | # 5: Decode the output back to a string
decoded_output = tokenizer.decode(outputs[0][inputs['input_ids'].size(1):], skip_special_tokens=True)
print("Decoded output:\n", decoded_output)
```
There's a lot in here, each piece of which could be its own document! Rather than going into too much detail, I'll cover
the broad ideas, and leave the details for the linked documents. The key steps are: | 12_7_4 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/conversations.md | https://huggingface.co/docs/transformers/en/conversations/#what-happens-inside-the-pipeline | .md | the broad ideas, and leave the details for the linked documents. The key steps are:
1. [Models](https://huggingface.co/learn/nlp-course/en/chapter2/3) and [Tokenizers](https://huggingface.co/learn/nlp-course/en/chapter2/4?fw=pt) are loaded from the Hugging Face Hub.
2. The chat is formatted using the tokenizer's [chat template](https://huggingface.co/docs/transformers/main/en/chat_templating)
3. The formatted chat is [tokenized](https://huggingface.co/learn/nlp-course/en/chapter2/4) using the tokenizer. | 12_7_5 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/conversations.md | https://huggingface.co/docs/transformers/en/conversations/#what-happens-inside-the-pipeline | .md | 3. The formatted chat is [tokenized](https://huggingface.co/learn/nlp-course/en/chapter2/4) using the tokenizer.
4. We [generate](https://huggingface.co/docs/transformers/en/llm_tutorial) a response from the model.
5. The tokens output by the model are decoded back to a string | 12_7_6 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/conversations.md | https://huggingface.co/docs/transformers/en/conversations/#performance-memory-and-hardware | .md | You probably know by now that most machine learning tasks are run on GPUs. However, it is entirely possible
to generate text from a chat model or language model on a CPU, albeit somewhat more slowly. If you can fit
the model in GPU memory, though, this will usually be the preferable option. | 12_8_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/conversations.md | https://huggingface.co/docs/transformers/en/conversations/#memory-considerations | .md | By default, Hugging Face classes like [`TextGenerationPipeline`] or [`AutoModelForCausalLM`] will load the model in
`float32` precision. This means that it will need 4 bytes (32 bits) per parameter, so an "8B" model with 8 billion
parameters will need ~32GB of memory. However, this can be wasteful! Most modern language models are trained in
"bfloat16" precision, which uses only 2 bytes per parameter. If your hardware supports it (Nvidia 30xx/Axxx | 12_9_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/conversations.md | https://huggingface.co/docs/transformers/en/conversations/#memory-considerations | .md | "bfloat16" precision, which uses only 2 bytes per parameter. If your hardware supports it (Nvidia 30xx/Axxx
or newer), you can load the model in `bfloat16` precision, using the `torch_dtype` argument as we did above.
It is possible to go even lower than 16-bits using "quantization", a method to lossily compress model weights. This
allows each parameter to be squeezed down to 8 bits, 4 bits or even less. Note that, especially at 4 bits, | 12_9_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/conversations.md | https://huggingface.co/docs/transformers/en/conversations/#memory-considerations | .md | allows each parameter to be squeezed down to 8 bits, 4 bits or even less. Note that, especially at 4 bits,
the model's outputs may be negatively affected, but often this is a tradeoff worth making to fit a larger and more
capable chat model in memory. Let's see this in action with `bitsandbytes`:
```python
from transformers import AutoModelForCausalLM, BitsAndBytesConfig | 12_9_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/conversations.md | https://huggingface.co/docs/transformers/en/conversations/#memory-considerations | .md | quantization_config = BitsAndBytesConfig(load_in_8bit=True) # You can also try load_in_4bit
model = AutoModelForCausalLM.from_pretrained("meta-llama/Meta-Llama-3-8B-Instruct", device_map="auto", quantization_config=quantization_config)
```
Or we can do the same thing using the `pipeline` API:
```python
from transformers import pipeline, BitsAndBytesConfig | 12_9_3 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/conversations.md | https://huggingface.co/docs/transformers/en/conversations/#memory-considerations | .md | quantization_config = BitsAndBytesConfig(load_in_8bit=True) # You can also try load_in_4bit
pipe = pipeline("text-generation", "meta-llama/Meta-Llama-3-8B-Instruct", device_map="auto", model_kwargs={"quantization_config": quantization_config})
```
There are several other options for quantizing models besides `bitsandbytes` - please see the [Quantization guide](./quantization)
for more information. | 12_9_4 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/conversations.md | https://huggingface.co/docs/transformers/en/conversations/#performance-considerations | .md | <Tip>
For a more extensive guide on language model performance and optimization, check out [LLM Inference Optimization](./llm_optims) .
</Tip>
As a general rule, larger chat models will be slower in addition to requiring more memory. It's possible to be
more concrete about this, though: Generating text from a chat model is unusual in that it is bottlenecked by
**memory bandwidth** rather than compute power, because every active parameter must be read from memory for each | 12_10_0 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/conversations.md | https://huggingface.co/docs/transformers/en/conversations/#performance-considerations | .md | **memory bandwidth** rather than compute power, because every active parameter must be read from memory for each
token that the model generates. This means that number of tokens per second you can generate from a chat
model is generally proportional to the total bandwidth of the memory it resides in, divided by the size of the model.
In our quickstart example above, our model was ~16GB in size when loaded in `bfloat16` precision. | 12_10_1 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/conversations.md | https://huggingface.co/docs/transformers/en/conversations/#performance-considerations | .md | In our quickstart example above, our model was ~16GB in size when loaded in `bfloat16` precision.
This means that 16GB must be read from memory for every token generated by the model. Total memory bandwidth can
vary from 20-100GB/sec for consumer CPUs to 200-900GB/sec for consumer GPUs, specialized CPUs like
Intel Xeon, AMD Threadripper/Epyc or high-end Apple silicon, and finally up to 2-3TB/sec for data center GPUs like | 12_10_2 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/conversations.md | https://huggingface.co/docs/transformers/en/conversations/#performance-considerations | .md | Intel Xeon, AMD Threadripper/Epyc or high-end Apple silicon, and finally up to 2-3TB/sec for data center GPUs like
the Nvidia A100 or H100. This should give you a good idea of the generation speed you can expect from these different
hardware types.
Therefore, if you want to improve the speed of text generation, the easiest solution is to either reduce the
size of the model in memory (usually by quantization), or get hardware with higher memory bandwidth. For advanced users, | 12_10_3 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/conversations.md | https://huggingface.co/docs/transformers/en/conversations/#performance-considerations | .md | size of the model in memory (usually by quantization), or get hardware with higher memory bandwidth. For advanced users,
several other techniques exist to get around this bandwidth bottleneck. The most common are variants on
[assisted generation](https://huggingface.co/blog/assisted-generation), also known as "speculative
sampling". These techniques try to guess multiple future tokens at once, often using a smaller "draft model", and then | 12_10_4 |
/Users/nielsrogge/Documents/python_projecten/transformers/docs/source/en/conversations.md | https://huggingface.co/docs/transformers/en/conversations/#performance-considerations | .md | sampling". These techniques try to guess multiple future tokens at once, often using a smaller "draft model", and then
confirm these generations with the chat model. If the guesses are validated by the chat model, more than one token can
be generated per forward pass, which greatly alleviates the bandwidth bottleneck and improves generation speed.
Finally, we should also note the impact of "Mixture of Experts" (MoE) models here. Several popular chat models, | 12_10_5 |