NVMe Support

 reverse by starting with the most GPU memory efficient config and then going backwards. Or try bi-secting it.
Once you have your batch size 1 not leading to OOM, measure your effective throughput.
Next try to increase the batch size to as large as you can, since the higher the batch size the more efficient the GPUs are as they perform the best when matrices they multiply are huge.
Now the performance optimization game starts. You can turn off some offload features or step down in ZeRO stages and increase/decrease batch size and again measure your effective throughput. Rinse and repeat until satisfied.
Don’t spend forever on it, but if you’re about to start a 3 months training - do spend a few days on it to find the most effective throughput-wise setup. So that your training cost will be the lowest and you will finish training faster. In the current crazy-paced ML world, if it takes you an extra month to train something you are likely to miss a golden opportunity. Of co


NVMe Support

urse, this is only me sharing an observation and in no way I’m trying to rush you. Before beginning to train BLOOM-176B I spent 2 days on this process and was able to increase throughput from 90 to 150 TFLOPs! This effort saved us more than one month of training time.
These notes were written primarily for the training mode, but they should mostly apply for inference as well. For example, during inference Gradient Checkpointing is a no-op since it is only useful during training. Additionally, we found out that if you are doing a multi-GPU inference and not using DeepSpeed-Inference, Accelerate should provide a superior performance.
Other quick related performance notes:
if you are training something from scratch always try to have tensors with shapes that are divisible by 16 (e.g. hidden size). For batch size try divisible by 2 at least. There are wave and tile quanitization divisibility that is hardware-specific if you want to squeeze even higher performance from your


Activation Checkpointing or Gradient Checkpointing

Activation checkpointing and gradient checkpointing are two distinct terms that refer to the same methodology. It’s very confusing but this is how it is.
Gradient checkpointing allows one to trade speed for GPU memory, which either allows one to overcome a GPU OOM, or increase their batch size, which often leads to a better performance.
HF Transformers models don’t know anything about DeepSpeed’s activation checkpointing, so if you try to enable that feature in the DeepSpeed config file, nothing will happen.
Therefore you have two ways to take advantage of this very beneficial feature:
I


f you want to use a HF Transformers models you can do model.gradient_checkpointing_enable() or use --gradient_checkpointing in the HF Trainer, which will automatically enable this for you. torch.utils.checkpoint is used there. If you write your own model and you want to use DeepSpeed’s activation checkpointing you can use the API prescribed there. You can also take the HF Transformers modeling code and replace torch.utils.checkpoint with the DeepSpeed’s API. The latter is more flexible since it allows you to offload the forward activations to the CPU memory instead of recalculating them.


Optimizer and Scheduler

As long as you don’t enable offload_optimizer you can mix and match DeepSpeed and HuggingFace schedulers and
optimizers, with the exception of using the combination of HuggingFace scheduler and DeepSpeed optimizer:
| Combos       | HF Scheduler | DS Scheduler |
| HF Optimizer | Yes          | Yes          |
| DS Optimizer | No           | Yes          |
It is possible to use a non-DeepSpeed optimizer when offload_optimizer is enabled, as long as it has both CPU and
GPU implementation (except LAMB).
 Optimizer
DeepSpeed’s main optimizers are Adam, AdamW, OneBitAdam, and Lamb. These have been thoroughly tested with ZeRO and are
thus recommended to be used. It, however, can import other optimizers from torch. The full documentation is here.
If you don’t configure the optimizer entry in the configuration file, the Trainer will
automatically set it to AdamW and will use the supplied values or the defaults fo


Optimizer and Scheduler

r the following command line
arguments: --learning_rate, --adam_beta1, --adam_beta2, --adam_epsilon and --weight_decay.
Here is an example of the auto-configured optimizer entry for AdamW:
  Copied {
   "optimizer": {
       "type": "AdamW",
       "params": {
         "lr": "auto",
         "betas": "auto",
         "eps": "auto",
         "weight_decay": "auto"
       }
   }
}
Note that the command line arguments will set the values in the configuration file. This is so that there is one
definitive source of the values and to avoid hard to find errors when for example, the learning rate is set to
different values in different places. Command line rules. The values that get overridden are:
lr with the value of --learning_rate betas with the value of --adam_beta1 --adam_beta2 eps with the value of --adam_epsilon weight_decay with the value of --weight_decay
Therefore please remember to tune the shared h


Optimizer and Scheduler

yperparameters on the command line.
You can also set the values explicitly:
  Copied {
   "optimizer": {
       "type": "AdamW",
       "params": {
         "lr": 0.001,
         "betas": [0.8, 0.999],
         "eps": 1e-8,
         "weight_decay": 3e-7
       }
   }
}
But then you’re on your own synchronizing the Trainer command line arguments and the DeepSpeed
configuration.
If you want to use another optimizer which is not listed above, you will have to add to the top level configuration.
  Copied {
   "zero_allow_untested_optimizer": true
}
Similarly to AdamW, you can configure other officially supported optimizers. Just remember that those may have different config values. e.g. for Adam you will want weight_decay around 0.01.
Additionally, offload works the best when it’s used with Deepspeed’s CPU Adam optimizer. If you want to use a different optimizer with offload, since deepspeed==0.8.3 you need


Optimizer and Scheduler

 to also add:
  Copied {
   "zero_force_ds_cpu_optimizer": false
}
to the top level configuration.
 Scheduler
DeepSpeed supports LRRangeTest, OneCycle, WarmupLR and WarmupDecayLR learning rate schedulers. The full
documentation is here.
Here is where the schedulers overlap between 🤗 Transformers and DeepSpeed:
WarmupLR via --lr_scheduler_type constant_with_warmup WarmupDecayLR via --lr_scheduler_type linear. This is also the default value for --lr_scheduler_type,
therefore, if you don’t configure the scheduler this is scheduler that will get configured by default.
If you don’t configure the scheduler entry in the configuration file, the Trainer will use
the values of --lr_scheduler_type, --learning_rate and --warmup_steps or --warmup_ratio to configure a
🤗 Transformers version of it.
Here is an example of the auto-configured scheduler entry for WarmupLR:
  Copied {
   "scheduler": {
         "type": "Wa


Optimizer and Scheduler

rmupLR",
         "params": {
             "warmup_min_lr": "auto",
             "warmup_max_lr": "auto",
             "warmup_num_steps": "auto"
         }
     }
}
Since “auto” is used the Trainer arguments will set the correct values in the configuration
file. This is so that there is one definitive source of the values and to avoid hard to find errors when, for example,
the learning rate is set to different values in different places. Command line rules. The values that get set are:
warmup_min_lr with the value of 0. warmup_max_lr with the value of --learning_rate. warmup_num_steps with the value of --warmup_steps if provided. Otherwise will use --warmup_ratio
multiplied by the number of training steps and rounded up. total_num_steps with either the value of --max_steps or if it is not provided, derived automatically at run
time based on the environment and the size of the dataset and other command


Optimizer and Scheduler

line arguments (needed for
WarmupDecayLR).
You can, of course, take over any or all of the configuration values and set those yourself:
  Copied {
   "scheduler": {
         "type": "WarmupLR",
         "params": {
             "warmup_min_lr": 0,
             "warmup_max_lr": 0.001,
             "warmup_num_steps": 1000
         }
     }
}
But then you’re on your own synchronizing the Trainer command line arguments and the DeepSpeed
configuration.
For example, for WarmupDecayLR, you can use the following entry:
  Copied {
   "scheduler": {
         "type": "WarmupDecayLR",
         "params": {
             "last_batch_iteration": -1,
             "total_num_steps": "auto",
             "warmup_min_lr": "auto",
             "warmup_max_lr": "auto",
             "warmup_num_steps": "auto"
         }
     }
}
and total_num_steps, warmup_max_lr, warmup_num_steps and total_num_steps will be set at loading t


fp32 Precision

Deepspeed supports the full fp32 and the fp16 mixed precision.
Because of the much reduced memory needs and faster speed one gets with the fp16 mixed precision, the only time you
will want to not use it is when the model you’re using doesn’t behave well under this training mode. Typically this
happens when the model wasn’t pretrained in the fp16 mixed precision (e.g. often this happens with bf16-pretrained
models). Such models may overflow or underflow leading to NaN loss. If this is your case then you will want to use
the full fp32 mode, by explicitly disabling the otherwise default fp16 mixed precision mode


fp32 Precision

 with:
  Copied {
    "fp16": {
        "enabled": false,
    }
}
If you’re using the Ampere-architecture based GPU, pytorch version 1.7 and higher will automatically switch to using
the much more efficient tf32 format for some operations, but the results will still be in fp32. For details and
benchmarks, please, see TensorFloat-32(TF32) on Ampere devices. The document includes
instructions on how to disable this automatic conversion if for some reason you prefer not to use it.
With the 🤗 Trainer you can use --tf32 to enable it, or disable it with --tf32 0 or --no_tf32. By default the PyTorch default is used.


fp16

To configure pytorch AMP-like mode with fp16 (float16) set:
  Copied {
    "fp16": {
        "enabled": "auto",
        "loss_scale": 0,
        "loss_scale_window": 1000,
        "initial_scale_power": 16,
        "hysteresis": 2,
        "min_loss_scale": 1
    }
}
and the Trainer will automatically enable or disable it based on the value of
args.fp16_backend. The rest of config values are up to you.
This mode gets enabled when --fp16 --fp16_backend amp or --fp16_full_eval command line args are passed.
You can also enable/disable this mode explicitly:
  Copied {
    "fp16": {
        "enabled": true,
        "loss_scale": 0,
        "loss_scale_window": 1000,
        "initial_scale_power": 16,
        "hysteresis": 2,
        "min_loss_scale": 1
    }
}
But then you’re on your own synchronizing the Trainer command line arguments and the DeepSpeed
configuration.
Here is the documentation.


bf16

If bf16 (bfloat16) is desired instead of fp16 then the following configuration section is to be used:
  Copied {
    "bf16": {
        "enabled": "auto"
    }
}
bf16 has the same dynamic range as fp32 and thus doesn’t require loss scaling.
This mode gets enabled when --bf16 or --bf16_full_eval command line args are passed.
You can also enable/disable this mode explicitly:
  Copied {
    "bf16": {
        "enabled": true
    }
}
As of deepspeed==0.6.0 the bf16 support is new and experimental. If you use gradient accumulation with bf16-enabled, you need to be aware that it’ll accumulate gradients in bf16, which may not be what you want due to this format’s low precision, as it may lead to a lossy accumulation. A work is being done to fix that and provide an option to use a higher precision dtype (fp16 or fp32).


NCCL Collectives

There is the dtype of the training regime and there is a separate dtype that is used for communication collectives like various reduction and gathering/scattering operations.
All gather/scatter ops are performed in the same dtype the data is in, so if you’re using bf16 training regime it gets gathered in bf16 - gathering is a non-lossy operation.
Various reduce operations can be quite lossy, for example when gradients are averaged across multiple-gpus, if the communications are done in fp16 or bf16 the outcome is likely be lossy - since when one ads multiple numbers in low precision the result isn’t exact. More so with bf16 as it has a lower precision than fp16. Often fp16 is good enough as the loss is mini


NCCL Collectives

mal when averaging grads which are typically very small. Therefore, by default for half precision training fp16 is used as the default for reduction operations. But you have full control over this functionality and if you choose you can add a small overhead and ensure that reductions will be using fp32 as the accumulation dtype and only when the result is ready it’ll get downcast to the half precision dtype you’re training in.
In order to override the default you simply add a new configuration entry:
  Copied {
    "communication_data_type": "fp32"
}
The valid values as of this writing are “fp16”, “bfp16”, “fp32”.
note: stage zero 3 had a bug with regards to bf16 comm dtype that was fixed in deepspeed==0.8.


apex

To configure apex AMP-like mode set:
  Copied "amp": {
    "enabled": "auto",
    "opt_level": "auto"
}
and the Trainer will automatically configure it based on the values of args.fp16_backend and
args.fp16_opt_level.
This mode gets enabled when --fp16 --fp16_backend apex --fp16_opt_level 01 command line args are passed.
You can also configure this mode explicitly:
  Copied {
    "amp": {
        "enabled": true,
        "opt_level": "O1"
    }
}
But then you’re on your own synchronizing the Trainer command line arguments and the DeepSpeed
configuration.
Here is the documentation.


Batch Size

To configure batch size, use:
  Copied {
    "train_batch_size": "auto",
    "train_micro_batch_size_per_gpu": "auto"
}
and the Trainer will automatically set train_micro_batch_size_per_gpu to the value of
args.per_device_train_batch_size and train_batch_size to args.world_size * args.per_device_train_batch_size * args.gradient_accumulation_steps.
You can also set the values explicitly:
  Copied {
    "train_batch_size": 12,
    "train_micro_batch_size_per_gpu": 4
}
But then you’re on your own synchronizing the Trainer command line arguments and the DeepSpeed
configuration.


Gradient Accumulation

To configure gradient accumulation set:
  Copied {
    "gradient_accumulation_steps": "auto"
}
and the Trainer will automatically set it to the value of args.gradient_accumulation_steps.
You can also set the value explicitly:
  Copied {
    "gradient_accumulation_steps": 3
}
But then you’re on your own synchronizing the Trainer command line arguments and the DeepSpeed
configuration.


Gradient Clipping

To configure gradient gradient clipping set:
  Copied {
    "gradient_clipping": "auto"
}
and the Trainer will automatically set it to the value of args.max_grad_norm.
You can also set the value explicitly:
  Copied {
    "gradient_clipping": 1.0
}
But then you’re on your own synchronizing the Trainer command line arguments and the DeepSpeed
configuration.


Getting The Model Weights Out

As long as you continue training and resuming using DeepSpeed you don’t need to worry about anything. DeepSpeed stores
fp32 master weights in its custom checkpoint optimizer files, which are global_step*/*optim_states.pt (this is glob
pattern), and are saved under the normal checkpoint.
FP16 Weights:
When a model is saved under ZeRO-2, you end up having the normal pytorch_model.bin file with the model weights, but
they are only the fp16 version of the weights.
Under ZeRO-3, things are much more complicated, since the model weights are partitioned out over multiple GPUs,
therefore "stage3_gather_16bit_weights_on_model_save": true is required to get the Trainer to save the fp16
version of the weights. If this setting is False pytorch_model.bin won’t be created. This is because by default DeepSpeed’s state_dict contains a placeholder and not the real weights. If we were t


Getting The Model Weights Out

o save this state_dict it won’t be possible to load it back.
  Copied {
    "zero_optimization": {
        "stage3_gather_16bit_weights_on_model_save": true
    }
}
FP32 Weights:
While the fp16 weights are fine for resuming training, if you finished finetuning your model and want to upload it to
the models hub or pass it to someone else you most likely will want to get the fp32
weights. This ideally shouldn’t be done during training since this is a process that requires a lot of memory, and
therefore best to be performed offline after the training is complete. But if desired and you have plenty of free CPU
memory it can be done in the same training script. The following sections will discuss both approaches.
Live FP32 Weights Recovery:
This approach may not work if you model is large and you have little free CPU memory left, at the end of the training.
If you have save


Getting The Model Weights Out

d at least one checkpoint, and you want to use the latest one, you can do the following:
  Copied from transformers.trainer_utils import get_last_checkpoint
from deepspeed.utils.zero_to_fp32 import load_state_dict_from_zero_checkpoint
checkpoint_dir = get_last_checkpoint(trainer.args.output_dir)
fp32_model = load_state_dict_from_zero_checkpoint(trainer.model, checkpoint_dir)
If you’re using the --load_best_model_at_end class:~transformers.TrainingArguments argument (to track the best
checkpoint), then you can finish the training by first saving the final model explicitly and then do the same as above:
  Copied from deepspeed.utils.zero_to_fp32 import load_state_dict_from_zero_checkpoint
checkpoint_dir = os.path.join(trainer.args.output_dir, "checkpoint-final")
trainer.deepspeed.save_checkpoint(checkpoint_dir)
fp32_model = load_state_dict_from_zero_checkpoint(trainer.mo


Getting The Model Weights Out

del, checkpoint_dir)
Note, that once load_state_dict_from_zero_checkpoint was run, the model will no longer be usable in the
DeepSpeed context of the same application. i.e. you will need to re-initialize the deepspeed engine, since
model.load_state_dict(state_dict) will remove all the DeepSpeed magic from it. So do this only at the very end
of the training.
Of course, you don’t have to use class:~transformers.Trainer and you can adjust the examples above to your own
trainer.
If for some reason you want more refinement, you can also extract the fp32 state_dict of the weights and apply
these yourself as is shown in the following example:
  Copied from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint
state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir)  # already on cpu
model = model.cpu()
model.load_state_dict(state_dict)
Offl


Getting The Model Weights Out

ine FP32 Weights Recovery:
DeepSpeed creates a special conversion script zero_to_fp32.py which it places in the top-level of the checkpoint
folder. Using this script you can extract the weights at any point. The script is standalone and you no longer need to
have the configuration file or a Trainer to do the extraction.
Let’s say your checkpoint folder looks like this:
  Copied $ ls -l output_dir/checkpoint-1/
-rw-rw-r-- 1 stas stas 1.4K Mar 27 20:42 config.json
drwxrwxr-x 2 stas stas 4.0K Mar 25 19:52 global_step1/
-rw-rw-r-- 1 stas stas   12 Mar 27 13:16 latest
-rw-rw-r-- 1 stas stas 827K Mar 27 20:42 optimizer.pt
-rw-rw-r-- 1 stas stas 231M Mar 27 20:42 pytorch_model.bin
-rw-rw-r-- 1 stas stas  623 Mar 27 20:42 scheduler.pt
-rw-rw-r-- 1 stas stas 1.8K Mar 27 20:42 special_tokens_map.json
-rw-rw-r-- 1 stas stas 774K Mar 27 20:42 spiece.model
-rw-rw-r-- 1 stas stas 1.


Getting The Model Weights Out

9K Mar 27 20:42 tokenizer_config.json
-rw-rw-r-- 1 stas stas  339 Mar 27 20:42 trainer_state.json
-rw-rw-r-- 1 stas stas 2.3K Mar 27 20:42 training_args.bin
-rwxrw-r-- 1 stas stas 5.5K Mar 27 13:16 zero_to_fp32.py*
In this example there is just one DeepSpeed checkpoint sub-folder global_step1. Therefore to reconstruct the fp32
weights just run:
  Copied python zero_to_fp32.py . pytorch_model.bin
This is it. pytorch_model.bin will now contain the full fp32 model weights consolidated from multiple GPUs.
The script will automatically be able to handle either a ZeRO-2 or ZeRO-3 checkpoint.
python zero_to_fp32.py -h will give you usage details.
The script will auto-discover the deepspeed sub-folder using the contents of the file latest, which in the current
example will contain global_step1.
Note: currently the script requires 2x general RAM of the final fp32 model weights.


ZeRO-3 and Infinity Nuances

ZeRO-3 is quite different from ZeRO-2 because of its param sharding feature.
ZeRO-Infinity further extends ZeRO-3 to support NVMe memory and multiple other speed and scalability improvements.
While all the efforts were made for things to just work without needing any special changes to your models, in certain
circumstances you may find the following information to be needed.
 Constructing Massive Models
DeepSpeed/ZeRO-3 can handle models with Trillions of parameters which may not fit onto the existing RAM. In such cases,
but also if you want the initialization to happen much faster, initialize the model using deepspeed.zero.Init()
context manager (which is also a function decorator), like so:
  Copied from transformers import T5ForConditionalGeneration, T5Config
import deepspeed
with deepspeed.zero.Init():
    config


ZeRO-3 and Infinity Nuances

 = T5Config.from_pretrained("t5-small")
    model = T5ForConditionalGeneration(config)
As you can see this gives you a randomly initialized model.
If you want to use a pretrained model, model_class.from_pretrained will activate this feature as long as
is_deepspeed_zero3_enabled() returns True, which currently is setup by the
TrainingArguments object if the passed DeepSpeed configuration file contains ZeRO-3 config
section. Thus you must create the TrainingArguments object before calling
from_pretrained. Here is an example of a possible sequence:
  Copied from transformers import AutoModel, Trainer, TrainingArguments
training_args = TrainingArguments(..., deepspeed=ds_config)
model = AutoModel.from_pretrained("t5-small")
trainer = Trainer(model=model, args=training_args, ...)
If you’re using the official example scrip


ZeRO-3 and Infinity Nuances

ts and your command line arguments include --deepspeed ds_config.json
with ZeRO-3 config enabled, then everything is already done for you, since this is how example scripts are written.
Note: If the fp16 weights of the model can’t fit onto the memory of a single GPU this feature must be used.
For full details on this method and other related features please refer to Constructing Massive Models.
Also when loading fp16-pretrained models, you will want to tell from_pretrained to use
torch_dtype=torch.float16. For details, please, see from_pretrained-torch-dtype.
 Gathering Parameters
Under ZeRO-3 on multiple GPUs no single GPU has all the parameters unless it’s the parameters for the currently
executing layer. So if you need to access all parameters from all layers at once there is a specific method to do it.
Most likel


ZeRO-3 and Infinity Nuances

y you won’t need it, but if you do please refer to Gathering Parameters
We do however use it internally in several places, one such example is when loading pretrained model weights in
from_pretrained. We load one layer at a time and immediately partition it to all participating GPUs, as for very
large models it won’t be possible to load it on one GPU and then spread it out to multiple GPUs, due to memory
limitations.
Also under ZeRO-3, if you write your own code and run into a model parameter weight that looks like:
  Copied tensor([1.0], device="cuda:0", dtype=torch.float16, requires_grad=True)
stress on tensor([1.]), or if you get an error where it says the parameter is of size 1, instead of some much
larger multi-dimensional shape, this means that the parameter is partitioned and what you see is a ZeRO-3 placehold


ZeRO Inference

ZeRO Inference uses the same config as ZeRO-3 Training. You just don’t need the optimizer and scheduler sections. In
fact you can leave these in the config file if you want to share the same one with the training. They will just be
ignored.
Otherwise you just need to pass the usual TrainingArguments arguments. For example:
  Copied deepspeed --num_gpus=2 your_program.py <normal cl args> --do_eval --deepspeed ds_config.json
The only important thing is that you need to use a ZeRO-3 configuration, since ZeRO-2 provides no benefit whatsoever
for the inference as only ZeRO-3 performs sharding of parameters, whereas ZeRO-1 shards gradients and optimizer states.
Here is an example of running run_translation.py under DeepSpeed deploying all available GPUs:
  Copied deepspeed examples/pytorch/translation/run_translation.py \
--deepspeed tests/deepspeed/ds_config_zero3.json \
--model_name_or


ZeRO Inference

_path t5-small --output_dir output_dir \
--do_eval --max_eval_samples 50 --warmup_steps 50  \
--max_source_length 128 --val_max_target_length 128 \
--overwrite_output_dir --per_device_eval_batch_size 4 \
--predict_with_generate --dataset_config "ro-en" --fp16 \
--source_lang en --target_lang ro --dataset_name wmt16 \
--source_prefix "translate English to Romanian: "
Since for inference there is no need for additional large memory used by the optimizer states and the gradients you
should be able to fit much larger batches and/or sequence length onto the same hardware.
Additionally DeepSpeed is currently developing a related product called Deepspeed-Inference which has no relationship
to the ZeRO technology, but instead uses tensor parallelism to scale models that can’t fit onto a single GPU. This is a
work in progress and we will provide the integration once that product is complete


Memory Requirements

Since Deepspeed ZeRO can offload memory to CPU (and NVMe) the framework provides utils that allow one to tell how much CPU and GPU memory will be needed depending on the number of GPUs being used.
Let’s estimate how much memory is needed to finetune “bigscience/T0_3B” on a single GPU:
  Copied $ python -c 'from transformers import AutoModel; \
from deepspeed.runtime.zero.stage3 import estimate_zero3_model_states_mem_needs_all_live; \
model = AutoModel.from_pretrained("bigscience/T0_3B"); \
estimate_zero3_model_states_mem_needs_all_live(model, num_gpus_per_node=1, num_nodes=1)'
[...]
Estimated memory needed for params, optim states and gradients for a:
HW: Setup with 1 node, 1 GPU per node.
SW: Model with 2783M total params, 65M largest layer params.
  per CPU  |  per GPU |   Options


Memory Requirements

   70.00GB |   0.25GB | offload_param=cpu , offload_optimizer=cpu , zero_init=1
   70.00GB |   0.25GB | offload_param=cpu , offload_optimizer=cpu , zero_init=0
   62.23GB |   5.43GB | offload_param=none, offload_optimizer=cpu , zero_init=1
   62.23GB |   5.43GB | offload_param=none, offload_optimizer=cpu , zero_init=0
    0.37GB |  46.91GB | offload_param=none, offload_optimizer=none, zero_init=1
   15.56GB |  46.91GB | offload_param=none, offload_optimizer=none, zero_init=0
So you can fit it on a single 80GB GPU and no CPU offload, or a tiny 8GB GPU but then need ~60GB of CPU memory. (Remember this is just the memory for params, optimizer states and gradients - you will need a bit more memory for cuda kernels, activations and temps.)
Then it’s a tradeoff of cost vs speed. It’ll be


Memory Requirements

 cheaper to buy/rent a smaller GPU (or less GPUs since you can use multiple GPUs with Deepspeed ZeRO. But then it’ll be slower, so even if you don’t care about how fast something will be done, the slowdown has a direct impact on the duration of using the GPU and thus bigger cost. So experiment and compare which works the best.
If you have enough GPU memory make sure to disable the CPU/NVMe offload as it’ll make everything faster.
For example, let’s repeat the same for 2 GPUs:
  Copied $ python -c 'from transformers import AutoModel; \
from deepspeed.runtime.zero.stage3 import estimate_zero3_model_states_mem_needs_all_live; \
model = AutoModel.from_pretrained("bigscience/T0_3B"); \
estimate_zero3_model_states_mem_needs_all_live(model, num_gpus_per_node=2, num_nodes=1)'
[...]
Estimate


Memory Requirements

d memory needed for params, optim states and gradients for a:
HW: Setup with 1 node, 2 GPUs per node.
SW: Model with 2783M total params, 65M largest layer params.
  per CPU  |  per GPU |   Options
   70.00GB |   0.25GB | offload_param=cpu , offload_optimizer=cpu , zero_init=1
   70.00GB |   0.25GB | offload_param=cpu , offload_optimizer=cpu , zero_init=0
   62.23GB |   2.84GB | offload_param=none, offload_optimizer=cpu , zero_init=1
   62.23GB |   2.84GB | offload_param=none, offload_optimizer=cpu , zero_init=0
    0.74GB |  23.58GB | offload_param=none, offload_optimizer=none, zero_init=1
   31.11GB |  23.58GB | offload_param=none, offload_optimizer=none, zero_init=0
So here you’d want 2x 32GB GPUs or higher without offloading to CPU.
For full information please see memory estimato


Filing Issues

Here is how to file an issue so that we could quickly get to the bottom of the issue and help you to unblock your work.
In your report please always include:
the full Deepspeed config file in the report either the command line arguments if you were using the Trainer or
TrainingArguments arguments if you were scripting the Trainer setup yourself. Please do not
dump the TrainingArguments as it has dozens of entries that are irrelevant. Output of:   Copied python -c 'import torch; print(f"torch: {torch.__version__}")'
python -c 'import transformers; print(f"transformers: {transformers.__version__}")'
python -c 'import deepspeed; print(f"deepspeed: {deepspeed.__version__}")' If possible include a link to a Google Colab notebook that we can reproduce the problem with. You can use this
notebook as
a starting point. Unless it’s impossible please always use a standard dataset that we can use and not something cust


Filing Issues

om. If possible try to use one of the existing examples to reproduce the problem with.
Things to consider:
Deepspeed is often not the cause of the problem. Some of the filed issues proved to be Deepspeed-unrelated. That is once Deepspeed was removed from the setup, the
problem was still there. Therefore, if it’s not absolutely obvious it’s a DeepSpeed-related problem, as in you can see that there is an
exception and you can see that DeepSpeed modules are involved, first re-test your setup without DeepSpeed in it.
And only if the problem persists then do mentioned Deepspeed and supply all the required details. If it’s clear to you that the issue is in the DeepSpeed core and not the integration part, please file the Issue
directly with Deepspeed. If you aren’t sure, please do not worry,
either Issue tracker will do, we will figure it out once you posted it and redirect you to another Issue tracker if
need be


Troubleshooting

the deepspeed process gets killed at startup without a traceback
If the deepspeed process gets killed at launch time without a traceback, that usually means that the program tried
to allocate more CPU memory than your system has or your process is allowed to allocate and the OS kernel killed that
process. This is because your configuration file most likely has either offload_optimizer or offload_param or
both configured to offload to cpu. If you have NVMe, experiment with offloading to NVMe if you’re running under
ZeRO-3. Here is how you can estimate how much memory is needed for a specific model.
 training and/or eval/predict loss is NaN
This often happens when one takes a model pre-trained in bf16 mixed precision mode and tries to use it under


Troubleshooting

 fp16 (with or without mixed precision). Most models trained on TPU and often the ones released by Google are in this category (e.g. almost all t5-based models). Here the solution is to either use fp32 or bf16 if your hardware supports it (TPU, Ampere GPUs or newer).
The other problem may have to do with using fp16. When you configure this section:
  Copied {
    "fp16": {
        "enabled": "auto",
        "loss_scale": 0,
        "loss_scale_window": 1000,
        "initial_scale_power": 16,
        "hysteresis": 2,
        "min_loss_scale": 1
    }
}
and you see in your log that Deepspeed reports OVERFLOW! as follows:
  Copied 0%|


Troubleshooting

          | 0/189 [00:00<?, ?it/s]
 [deepscale] OVERFLOW! Rank 0 Skipping step. Attempted loss scale: 262144, reducing to 262144
  1%|▌                                                                                | 1/189 [00:00<01:26,  2.17it/s]
 [deepscale] OVERFLOW! Rank 0 Skipping step. Attempted loss scale: 262144, reducing to 131072.0
  1%|█▏
 [...]
 [deepscale] OVERFLOW! Rank 0 Skipping step. Attempted loss scale: 1, reducing to 1
 14%|████████████████▌                                                                                | 27/189 [00:14<01:13,  2.21it/s]
 [deepscale] OVERFLOW! Rank 0 Skipping step. Attempted loss scale: 1, reducing to 1
 15%|█████████████████▏


Troubleshooting

                                                                                | 28/189 [00:14<01:13,  2.18it/s]
 [deepscale] OVERFLOW! Rank 0 Skipping step. Attempted loss scale: 1, reducing to 1
 15%|█████████████████▊                                                                                | 29/189 [00:15<01:13,  2.18it/s]
 [deepscale] OVERFLOW! Rank 0 Skipping step. Attempted loss scale: 1, reducing to 1
[...]
that means that the Deepspeed loss scaler can’t figure out a scaling co-efficient that overcomes loss overflow.
(the log was massaged to be more readable here.)
In this case you usually need to raise the value of initial_scale_power. Setting it to "initial_scale_power": 32 will typically resolve the problem


Notes

DeepSpeed works with the PyTorch Trainer but not TF TFTrainer. While DeepSpeed has a pip installable PyPI package, it is highly recommended that it gets installed from source to best match your hardware and also if you need to enable
certain features, like 1-bit Adam, which aren’t available in the pypi distribution. You don’t have to use the Trainer to use DeepSpeed with 🤗 Transformers - you can use any model
with your own trainer, and you will have to adapt the latter according to the DeepSpeed integration instructions.


Non-Trainer Deepspeed Integration

The HfDeepSpeedConfig is used to integrate Deepspeed into the 🤗 Transformers core
functionality, when Trainer is not used. The only thing that it does is handling Deepspeed ZeRO-3 param gathering and automatically splitting the model onto multiple gpus during from_pretrained call. Everything else you have to do by yourself.
When using Trainer everything is automatically taken care of.
When not using Trainer, to efficiently deploy DeepSpeed ZeRO-3, you must instantiate the
HfDeepSpeedConfig object before instantiating the model and keep that object alive.
If you’re using Deepspeed ZeRO-1 or ZeRO-2 you don’t need to use HfDeepSpeedConfig at all.
For example for a pretrained model:
  Copied from transformers.integrations import HfDeepSpeedConfig
from transformers import AutoModel
import deepspeed
ds_config = {...}  # deepspeed config object or path to the file
# must run before instantiating the model to detect zero 3
dschf = HfDeepSp


Non-Trainer Deepspeed Integration

eedConfig(ds_config)  # keep this object alive
model = AutoModel.from_pretrained("gpt2")
engine = deepspeed.initialize(model=model, config_params=ds_config, ...)
or for non-pretrained model:
  Copied from transformers.integrations import HfDeepSpeedConfig
from transformers import AutoModel, AutoConfig
import deepspeed
ds_config = {...}  # deepspeed config object or path to the file
# must run before instantiating the model to detect zero 3
dschf = HfDeepSpeedConfig(ds_config)  # keep this object alive
config = AutoConfig.from_pretrained("gpt2")
model = AutoModel.from_config(config)
engine = deepspeed.initialize(model=model, config_params=ds_config, ...)
Please note that if you’re not using the Trainer integration, you’re completely on your own. Basically follow the documentation on the Deepspeed website. Also you have to configure explicitly the config file - you can’t use "auto" values and you will have to put real values instead.


HfDeepSpeedConfig

class transformers.integrations.HfDeepSpeedConfig  < source > ( config_file_or_dict  )   Parameters   config_file_or_dict (Union[str, Dict]) — path to DeepSpeed config file or dict.    This object contains a DeepSpeed configuration dictionary and can be quickly queried for things like zero stage. A weakref of this object is stored in the module’s globals to be able to access the config from areas where
things like the Trainer object is not available (e.g. from_pretrained and _get_resized_embeddings). Therefore
it’s important that this object remains alive while the program is still running. Trainer uses the HfTrainerDeepSpeedConfig subclass instead. That subclass has logic to sync the configuration
with values of TrainingArguments by replacing special placeholder values: "auto". Without this special logic
the DeepSpeed configuration is not modified in any way.


Custom DeepSpeed ZeRO Inference

Here is an example of how one could do DeepSpeed ZeRO Inference without using Trainer when one can’t fit a model onto a single GPU. The solution includes using additional GPUs or/and offloading GPU memory to CPU memory.
The important nuance to understand here is that the way ZeRO is designed you can process different inputs on different GPUs in parallel.
The example has copious notes and is self-documenting.
Make sure to:
disable CPU offload if you have enough GPU memory (since it slows things down) enable bf16 if you own an Ampere or a newer GPU to make things faster. If you don’t have that hardware you may enable fp16 as long as you don’t use any model that was pre-trained in bf16 mixed precision (such as most t5 models). These usually overflow in fp16 and you will see garbage as output.
  Copied #!/usr/bin/env python
# This script demonstrates how to use Deepspeed ZeRO in an inference mode


Custom DeepSpeed ZeRO Inference

 when one can't fit a model
# into a single GPU
#
# 1. Use 1 GPU with CPU offload
# 2. Or use multiple GPUs instead
#
# First you need to install deepspeed: pip install deepspeed
#
# Here we use a 3B "bigscience/T0_3B" model which needs about 15GB GPU RAM - so 1 largish or 2
# small GPUs can handle it. or 1 small GPU and a lot of CPU memory.
#
# To use a larger model like "bigscience/T0" which needs about 50GB, unless you have an 80GB GPU -
# you will need 2-4 gpus. And then you can adapt the script to handle more gpus if you want to
# process multiple inputs at once.
#
# The provided deepspeed config also activates CPU memory offloading, so chances are that if you
# have a lot of available CPU memory and you don't mind a slowdown you should be able to load a
# model that doesn't normally fit into a single GPU. If you have enough GPU memory the program will
# run faster if you don't want offl


Custom DeepSpeed ZeRO Inference

oad to CPU - so disable that section then.
#
# To deploy on 1 gpu:
#
# deepspeed --num_gpus 1 t0.py
# or:
# python -m torch.distributed.run --nproc_per_node=1 t0.py
#
# To deploy on 2 gpus:
#
# deepspeed --num_gpus 2 t0.py
# or:
# python -m torch.distributed.run --nproc_per_node=2 t0.py
from transformers import AutoTokenizer, AutoConfig, AutoModelForSeq2SeqLM
from transformers.integrations import HfDeepSpeedConfig
import deepspeed
import os
import torch
os.environ["TOKENIZERS_PARALLELISM"] = "false"  # To avoid warnings about parallelism in tokenizers
# distributed setup
local_rank = int(os.getenv("LOCAL_RANK", "0"))
world_size = int(os.getenv("WORLD_SIZE", "1"))
torch.cuda.set_device(local_rank)
deepspeed.init_distributed()
model_name = "bigscience/T0_3B"
config = AutoConfig.from_pretrained(model_name)
model_hidden_size = config.d_model
# batch size has to be divisible by world_size, but can


Custom DeepSpeed ZeRO Inference

 be bigger than world_size
train_batch_size = 1 * world_size
# ds_config notes
#
# - enable bf16 if you use Ampere or higher GPU - this will run in mixed precision and will be
# faster.
#
# - for older GPUs you can enable fp16, but it'll only work for non-bf16 pretrained models - e.g.
# all official t5 models are bf16-pretrained
#
# - set offload_param.device to "none" or completely remove the `offload_param` section if you don't
# - want CPU offload
#
# - if using `offload_param` you can manually finetune stage3_param_persistence_threshold to control
# - which params should remain on gpus - the larger the value the smaller the offload size
#
# For indepth info on Deepspeed config see
# https://huggingface.co/docs/transformers/main/main_classes/deepspeed
# keeping the same format as json for consistency, except it uses lower case for true/false
# fmt: off
ds_config = {
    "fp16": {
        "


Custom DeepSpeed ZeRO Inference

enabled": False
    },
    "bf16": {
        "enabled": False
    },
    "zero_optimization": {
        "stage": 3,
        "offload_param": {
            "device": "cpu",
            "pin_memory": True
        },
        "overlap_comm": True,
        "contiguous_gradients": True,
        "reduce_bucket_size": model_hidden_size * model_hidden_size,
        "stage3_prefetch_bucket_size": 0.9 * model_hidden_size * model_hidden_size,
        "stage3_param_persistence_threshold": 10 * model_hidden_size
    },
    "steps_per_print": 2000,
    "train_batch_size": train_batch_size,
    "train_micro_batch_size_per_gpu": 1,
    "wall_clock_breakdown": False
}
# fmt: on
# next line instructs transformers to partition the model directly over multiple gpus using
# deepspeed.zero.Init when model's `from_pretrained` method is called.
#
# **it has to be run before loading the model AutoModelForSeq2SeqLM.fro


Custom DeepSpeed ZeRO Inference

m_pretrained(model_name)**
#
# otherwise the model will first be loaded normally and only partitioned at forward time which is
# less efficient and when there is little CPU RAM may fail
dschf = HfDeepSpeedConfig(ds_config)  # keep this object alive
# now a model can be loaded.
model = AutoModelForSeq2SeqLM.from_pretrained(model_name)
# initialise Deepspeed ZeRO and store only the engine object
ds_engine = deepspeed.initialize(model=model, config_params=ds_config)[0]
ds_engine.module.eval()  # inference
# Deepspeed ZeRO can process unrelated inputs on each GPU. So for 2 gpus you process 2 inputs at once.
# If you use more GPUs adjust for more.
# And of course if you have just one input to process you then need to pass the same string to both gpus
# If you use only one GPU, then you will have only rank 0.
rank = torch.distributed.get_rank()
if rank == 0:
    text_in = "Is this review positive o


Custom DeepSpeed ZeRO Inference

r negative? Review: this is the best cast iron skillet you will ever buy"
elif rank == 1:
    text_in = "Is this review positive or negative? Review: this is the worst restaurant ever"
tokenizer = AutoTokenizer.from_pretrained(model_name)
inputs = tokenizer.encode(text_in, return_tensors="pt").to(device=local_rank)
with torch.no_grad():
    outputs = ds_engine.module.generate(inputs, synced_gpus=True)
text_out = tokenizer.decode(outputs[0], skip_special_tokens=True)
print(f"rank{rank}:\n   in={text_in}\n  out={text_out}")
Let’s save it as t0.py and run it:
  Copied $ deepspeed --num_gpus 2 t0.py
rank0:
   in=Is this review positive or negative? Review: this is the best cast iron skillet you will ever buy
  out=Positive
rank1:
   in=Is this review positive or negative? Review: this is the worst restaurant ever
  out=negative
This was a very basic example and you will want to adapt it to your n


generate nuances

When using multiple GPUs with ZeRO Stage-3, one has to synchronize the GPUs by calling generate(..., synced_gpus=True). If this is not done if one GPU finished generating before other GPUs the whole system will hang as the rest of the GPUs will not be able to received the shard of weights from the GPU that stopped generating.
Starting from transformers>=4.28, if synced_gpus isn’t explicitly specified, it’ll be set to True automatically if these conditions are detected. But you can still override the value of synced_gpus if need to.


Testing Deepspeed Integration

If you submit a PR that involves DeepSpeed integration please note our CircleCI PR CI setup has no GPUs, so we only run tests requiring gpus on a different CI nightly. Therefore if you get a green CI report in your PR it doesn’t mean DeepSpeed tests pass.
To run DeepSpeed tests, please run at least:
  Copied RUN_SLOW=1 pytest tests/deepspeed/test_deepspeed.py
If you changed any of the modeling or pytorch examples code, then run the model zoo tests as well. The following will run all DeepSpeed tests:
  Copied RUN_SLOW=1 pytest tests/deepspeed


Main DeepSpeed Resources

Project’s github Usage docs API docs Blog posts
Papers:
ZeRO: Memory Optimizations Toward Training Trillion Parameter Models ZeRO-Offload: Democratizing Billion-Scale Model Training ZeRO-Infinity: Breaking the GPU Memory Wall for Extreme Scale Deep Learning
Finally, please, remember that, HuggingFace Trainer only integrates DeepSpeed, therefore if you
have any problems or questions with regards to DeepSpeed usage, please, file an issue with DeepSpeed GitHub.


Exporting 🤗 Transformers models to ONNX

🤗 Transformers provides a transformers.onnx package that enables you to
convert model checkpoints to an ONNX graph by leveraging configuration objects.
See the guide on exporting 🤗 Transformers models for more
details.


ONNX Configurations

We provide three abstract classes that you should inherit from, depending on the
type of model architecture you wish to export:
Encoder-based models inherit from OnnxConfig Decoder-based models inherit from OnnxConfigWithPast Encoder-decoder models inherit from OnnxSeq2SeqConfigWithPast


OnnxConfig

class transformers.onnx.OnnxConfig  < source > ( config: PretrainedConfig task: str = 'default' patching_specs: typing.List[transformers.onnx.config.PatchingSpec] = None  )    Base class for ONNX exportable model describing metadata on how to export the model through the ONNX format.  flatten_output_collection_property  < source > ( name: str field: typing.Iterable[typing.Any]  ) → (Dict[str, Any])  Returns
(Dict[str, Any])

Outputs with flattened structure and key mapping this new structure.
  Flatten any potential nested structure expanding the name of the field with the index of the element within the
structure.  from_model_config  < source > ( config: PretrainedConfig task: str = 'default'  )    Instantiate a OnnxConfig for a specific model  generate_dummy_inputs  < source > ( prep


OnnxConfig

rocessor: typing.Union[ForwardRef('PreTrainedTokenizerBase'), ForwardRef('FeatureExtractionMixin'), ForwardRef('ImageProcessingMixin')] batch_size: int = -1 seq_length: int = -1 num_choices: int = -1 is_pair: bool = False framework: typing.Optional[transformers.utils.generic.TensorType] = None num_channels: int = 3 image_width: int = 40 image_height: int = 40 sampling_rate: int = 22050 time_duration: float = 5.0 frequency: int = 220 tokenizer: PreTrainedTokenizerBase = None  )   Parameters   batch_size (int, optional, defaults to -1) —
The batch size to export the model for (-1 means dynamic axis).   num_choices (int, optional, defaults to -1) —
The number of candidate answers provided for multiple choice task (-1 means dynamic axis).   seq_length (int, optional, defaults to -1) —
The seq


OnnxConfig

uence length to export the model for (-1 means dynamic axis).   is_pair (bool, optional, defaults to False) —
Indicate if the input is a pair (sentence 1, sentence 2)   framework (TensorType, optional, defaults to None) —
The framework (PyTorch or TensorFlow) that the tokenizer will generate tensors for.   num_channels (int, optional, defaults to 3) —
The number of channels of the generated images.   image_width (int, optional, defaults to 40) —
The width of the generated images.   image_height (int, optional, defaults to 40) —
The height of the generated images.   sampling_rate (int, optional defaults to 22050) —
The sampling rate for audio data generation.   time_duration (float, optional defaults to 5.0) —
Total seconds of sampling for audio data generation.   frequency (int, optional


OnnxConfig

defaults to 220) —
The desired natural frequency of generated audio.    Generate inputs to provide to the ONNX exporter for the specific framework  generate_dummy_inputs_onnxruntime  < source > ( reference_model_inputs: typing.Mapping[str, typing.Any]  ) → Mapping[str, Tensor]  Parameters   reference_model_inputs ([Mapping[str, Tensor]) —
Reference inputs for the model.   Returns
Mapping[str, Tensor]

The mapping holding the kwargs to provide to the model’s forward function
  Generate inputs for ONNX Runtime using the reference model inputs. Override this to run inference with seq2seq
models which have the encoder and decoder exported as separate ONNX files.  use_external_data_format  < source > ( num_parameters: int  )    Flag indicating if the model requires using external data forma


OnnxConfigWithPast

class transformers.onnx.OnnxConfigWithPast  < source > ( config: PretrainedConfig task: str = 'default' patching_specs: typing.List[transformers.onnx.config.PatchingSpec] = None use_past: bool = False  )     fill_with_past_key_values_  < source > ( inputs_or_outputs: typing.Mapping[str, typing.Mapping[int, str]] direction: str inverted_values_shape: bool = False  )    Fill the input_or_outputs mapping with past_key_values dynamic axes considering.  with_past  < source > ( config: PretrainedConfig task: str = 'default'  )    Instantiate a OnnxConfig with use_past attribute set to True


class transformers.onnx.OnnxSeq2SeqConfigWithPast  < source > ( config: PretrainedConfig task: str = 'default' patching_specs: typing.List[transformers.onnx.config.PatchingSpec] = None use_past: bool = False  )


ONNX Features

Each ONNX configuration is associated with a set of features that enable you
to export models for different types of topologies or tasks.


FeaturesManager

class transformers.onnx.FeaturesManager  < source > ( )     check_supported_model_or_raise  < source > ( model: typing.Union[ForwardRef('PreTrainedModel'), ForwardRef('TFPreTrainedModel')] feature: str = 'default'  )    Check whether or not the model has the requested features.  determine_framework  < source > ( model: str framework: str = None  )   Parameters   model (str) —
The name of the model to export.   framework (str, optional, defaults to None) —
The framework to use for the export. See above for priority if none provided.    Determines the framework to use for the export. The priority is in the following order: User input via framework. If local checkpoint is provided, use the same framework as the checkpoint. Available framework i


FeaturesManager

n environment, with priority given to PyTorch  get_config  < source > ( model_type: str feature: str  ) → OnnxConfig  Parameters   model_type (str) —
The model type to retrieve the config for.   feature (str) —
The feature to retrieve the config for.   Returns
OnnxConfig

config for the combination
  Gets the OnnxConfig for a model_type and feature combination.  get_model_class_for_feature  < source > ( feature: str framework: str = 'pt'  )   Parameters   feature (str) —
The feature required.   framework (str, optional, defaults to "pt") —
The framework to use for the export.    Attempts to retrieve an AutoModel class from a feature name.  get_model_from_feature  < source > ( feature: str model: str framework: str = None cache_dir: str =


FeaturesManager

None  )   Parameters   feature (str) —
The feature required.   model (str) —
The name of the model to export.   framework (str, optional, defaults to None) —
The framework to use for the export. See FeaturesManager.determine_framework for the priority should
none be provided.    Attempts to retrieve a model from a model’s name and the feature to be enabled.  get_supported_features_for_model_type  < source > ( model_type: str model_name: typing.Optional[str] = None  )   Parameters   model_type (str) —
The model type to retrieve the supported features for.   model_name (str, optional) —
The name attribute of the model object, only used for the exception message.    Tries to retrieve the feature -> OnnxConfig constructor map from the model type


Generation

Each framework has a generate method for text generation implemented in their respective GenerationMixin class:
PyTorch generate() is implemented in GenerationMixin. TensorFlow generate() is implemented in TFGenerationMixin. Flax/JAX generate() is implemented in FlaxGenerationMixin.
Regardless of your framework of choice, you can parameterize the generate method with a GenerationConfig
class instance. Please refer to this class for the complete list of generation parameters, which control the behavior
of the generation method.
To learn how to inspect a model’s generation configuration, what are the defaults, how to change the parameters ad hoc,
and how to create and save a customized generation configuration, refer to the
text generation strategies guide. The guide also explains how to use related features,
like token streaming.


GenerationConfig

class transformers.GenerationConfig  < source > ( **kwargs  )   Parameters that control the length of the output   max_length (int, optional, defaults to 20) —
The maximum length the generated tokens can have. Corresponds to the length of the input prompt +
max_new_tokens. Its effect is overridden by max_new_tokens, if also set.   max_new_tokens (int, optional) —
The maximum numbers of tokens to generate, ignoring the number of tokens in the prompt.   min_length (int, optional, defaults to 0) —
The minimum length of the sequence to be generated. Corresponds to the length of the input prompt +
min_new_tokens. Its effect is overridden by min_new_tokens, if also set.   min_new_tokens (int, optional) —
The minimum numbers of tokens to generate, ignoring the number of tokens in the prompt.   early_stopping (bool or str, optional, defaults to False) —
Controls the stopping condition for beam-based methods, like beam-search. It accepts the following values:
True, where t


GenerationConfig

he generation stops as soon as there are num_beams complete candidates; False, where an
heuristic is applied and the generation stops when is it very unlikely to find better candidates;
"never", where the beam search procedure only stops when there cannot be better candidates (canonical
beam search algorithm).   max_time(float, optional) —
The maximum amount of time you allow the computation to run for in seconds. generation will still finish
the current pass after allocated time has been passed.   Parameters that control the generation strategy used   do_sample (bool, optional, defaults to False) —
Whether or not to use sampling ; use greedy decoding otherwise.   num_beams (int, optional, defaults to 1) —
Number of beams for beam search. 1 means no beam search.   num_beam_groups (int, optional, defaults to 1) —
Number of groups to divide num_beams into in order to ensure diversity among different groups of beams.
this paper for more details.   penalty_alpha (floa


GenerationConfig

t, optional) —
The values balance the model confidence and the degeneration penalty in contrastive search decoding.   use_cache (bool, optional, defaults to True) —
Whether or not the model should use the past last key/values attentions (if applicable to the model) to
speed up decoding.   Parameters for manipulation of the model output logits   temperature (float, optional, defaults to 1.0) —
The value used to modulate the next token probabilities.   top_k (int, optional, defaults to 50) —
The number of highest probability vocabulary tokens to keep for top-k-filtering.   top_p (float, optional, defaults to 1.0) —
If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to
top_p or higher are kept for generation.   typical_p (float, optional, defaults to 1.0) —
Local typicality measures how similar the conditional probability of predicting a target token next is to
the expected conditional probability of predicting a random


GenerationConfig

token next, given the partial text already
generated. If set to float < 1, the smallest set of the most locally typical tokens with probabilities that
add up to typical_p or higher are kept for generation. See this
paper for more details.   epsilon_cutoff (float, optional, defaults to 0.0) —
If set to float strictly between 0 and 1, only tokens with a conditional probability greater than
epsilon_cutoff will be sampled. In the paper, suggested values range from 3e-4 to 9e-4, depending on the
size of the model. See Truncation Sampling as Language Model
Desmoothing for more details.   eta_cutoff (float, optional, defaults to 0.0) —
Eta sampling is a hybrid of locally typical sampling and epsilon sampling. If set to float strictly between
0 and 1, a token is only considered if it is greater than either eta_cutoff or sqrt(eta_cutoff) * exp(-entropy(softmax(next_token_logits))). The latter term is intuitively the expected next token
probability, scaled by sqrt(eta_cutof


GenerationConfig

f). In the paper, suggested values range from 3e-4 to 2e-3,
depending on the size of the model. See Truncation Sampling as Language Model
Desmoothing for more details.   diversity_penalty (float, optional, defaults to 0.0) —
This value is subtracted from a beam’s score if it generates a token same as any beam from other group at a
particular time. Note that diversity_penalty is only effective if group beam search is enabled.   repetition_penalty (float, optional, defaults to 1.0) —
The parameter for repetition penalty. 1.0 means no penalty. See this
paper for more details.   encoder_repetition_penalty (float, optional, defaults to 1.0) —
The paramater for encoder_repetition_penalty. An exponential penalty on sequences that are not in the
original input. 1.0 means no penalty.   length_penalty (float, optional, defaults to 1.0) —
Exponential penalty to the length that is used with beam-based generation. It is applied as an exponent to
the sequence length, which in t


GenerationConfig

urn is used to divide the score of the sequence. Since the score is the log
likelihood of the sequence (i.e. negative), length_penalty > 0.0 promotes longer sequences, while
length_penalty < 0.0 encourages shorter sequences.   no_repeat_ngram_size (int, optional, defaults to 0) —
If set to int > 0, all ngrams of that size can only occur once.   bad_words_ids(List[List[int]], optional) —
List of list of token ids that are not allowed to be generated. Check
NoBadWordsLogitsProcessor for further documentation and examples.   force_words_ids(List[List[int]] or List[List[List[int]]], optional) —
List of token ids that must be generated. If given a List[List[int]], this is treated as a simple list of
words that must be included, the opposite to bad_words_ids. If given List[List[List[int]]], this
triggers a disjunctive constraint, where one
can allow different forms of each word.   renormalize_logits (bool, optional, defaults to False) —
Whether to renormalize the logits


GenerationConfig

 after applying all the logits processors or warpers (including the custom
ones). It’s highly recommended to set this flag to True as the search algorithms suppose the score logits
are normalized but some logit processors or warpers break the normalization.   constraints (List[Constraint], optional) —
Custom constraints that can be added to the generation to ensure that the output will contain the use of
certain tokens as defined by Constraint objects, in the most sensible way possible.   forced_bos_token_id (int, optional, defaults to model.config.forced_bos_token_id) —
The id of the token to force as the first generated token after the decoder_start_token_id. Useful for
multilingual models like mBART where the first generated token needs to be the target
language token.   forced_eos_token_id (Union[int, List[int]], optional, defaults to model.config.forced_eos_token_id) —
The id of the token to force as the last generated token when max_length is reached. Option


GenerationConfig

ally, use a
list to set multiple end-of-sequence tokens.   remove_invalid_values (bool, optional, defaults to model.config.remove_invalid_values) —
Whether to remove possible nan and inf outputs of the model to prevent the generation method to crash.
Note that using remove_invalid_values can slow down generation.   exponential_decay_length_penalty (tuple(int, float), optional) —
This Tuple adds an exponentially increasing length penalty, after a certain amount of tokens have been
generated. The tuple shall consist of: (start_index, decay_factor) where start_index indicates where
penalty starts and decay_factor represents the factor of exponential decay   suppress_tokens  (List[int], optional) —
A list of tokens that will be suppressed at generation. The SupressTokens logit processor will set their
log probs to -inf so that they are not sampled.   begin_suppress_tokens  (List[int], optional) —
A list of tokens that will be suppressed at the beginning of the generat


GenerationConfig

ion. The SupressBeginTokens logit
processor will set their log probs to -inf so that they are not sampled.   forced_decoder_ids (List[List[int]], optional) —
A list of pairs of integers which indicates a mapping from generation indices to token indices that will be
forced before sampling. For example, [[1, 123]] means the second generated token will always be a token
of index 123.   sequence_bias (Dict[Tuple[int], float], optional)) —
Dictionary that maps a sequence of tokens to its bias term. Positive biases increase the odds of the
sequence being selected, while negative biases do the opposite. Check
SequenceBiasLogitsProcessor for further documentation and examples.   guidance_scale (float, optional) —
The guidance scale for classifier free guidance (CFG). CFG is enabled by setting guidance_scale > 1.
Higher guidance scale encourages the model to generate samples that are more closely linked to the input
prompt, usually at the expense of poorer quality.   low_m


GenerationConfig

emory (bool, optional) —
Switch to sequential topk for contrastive search to reduce peak memory. Used with contrastive search.   Parameters that define the output variables of `generate`   num_return_sequences(int, optional, defaults to 1) —
The number of independently computed returned sequences for each element in the batch.   output_attentions (bool, optional, defaults to False) —
Whether or not to return the attentions tensors of all attention layers. See attentions under returned
tensors for more details.   output_hidden_states (bool, optional, defaults to False) —
Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for
more details.   output_scores (bool, optional, defaults to False) —
Whether or not to return the prediction scores. See scores under returned tensors for more details.   return_dict_in_generate (bool, optional, defaults to False) —
Whether or not to return a ModelOutput instead of a plain tuple.


GenerationConfig

 Special tokens that can be used at generation time   pad_token_id (int, optional) —
The id of the padding token.   bos_token_id (int, optional) —
The id of the beginning-of-sequence token.   eos_token_id (Union[int, List[int]], optional) —
The id of the end-of-sequence token. Optionally, use a list to set multiple end-of-sequence tokens.   Generation parameters exclusive to encoder-decoder models   encoder_no_repeat_ngram_size (int, optional, defaults to 0) —
If set to int > 0, all ngrams of that size that occur in the encoder_input_ids cannot occur in the
decoder_input_ids.   decoder_start_token_id (int, optional) —
If an encoder-decoder model starts decoding with a different token than bos, the id of that token.   Wild card     Class that holds a configuration for a generation task. A generate call supports the following generation methods
for text-decoder, text-to-text, speech-to-text, and vision-to-text models: greedy decoding by calling greedy_search() if nu


GenerationConfig

m_beams=1 and
do_sample=False contrastive search by calling contrastive_search() if penalty_alpha>0.
and top_k>1 multinomial sampling by calling sample() if num_beams=1 and
do_sample=True beam-search decoding by calling beam_search() if num_beams>1 and
do_sample=False beam-search multinomial sampling by calling beam_sample() if
num_beams>1 and do_sample=True diverse beam-search decoding by calling group_beam_search(), if
num_beams>1 and num_beam_groups>1 constrained beam-search decoding by calling constrained_beam_search(), if
constraints!=None or force_words_ids!=None assisted decoding by calling assisted_decoding(), if
assistant_model is passed to .generate() You do not need to call any of the above methods directly. Pass custom parameter values to ‘.generate()‘. To learn
more about decoding strategies refer to the text generation strategies guide.  from_pretrained  < source > ( pretrained_model_name: typing.Union[str, os.PathLike] config_file_name: typing.Union


GenerationConfig

[str, os.PathLike, NoneType] = None cache_dir: typing.Union[str, os.PathLike, NoneType] = None force_download: bool = False local_files_only: bool = False token: typing.Union[str, bool, NoneType] = None revision: str = 'main' **kwargs  ) → GenerationConfig  Parameters   pretrained_model_name (str or os.PathLike) —
This can be either:
a string, the model id of a pretrained model configuration hosted inside a model repo on
huggingface.co. Valid model ids can be located at the root-level, like bert-base-uncased, or
namespaced under a user or organization name, like dbmdz/bert-base-german-cased.
a path to a directory containing a configuration file saved using the
save_pretrained() method, e.g., ./my_model_directory/.
   config_file_name (str or os.PathLike, optional, defaults to "generation_config.json") —
Name of the generation configuration JSON file to be loaded from pretrained_model_name.   cache_dir (str or os.PathLike, optional) —
Path to a directory in which a


GenerationConfig

 downloaded pretrained model configuration should be cached if the
standard cache should not be used.   force_download (bool, optional, defaults to False) —
Whether or not to force to (re-)download the configuration files and override the cached versions if
they exist.   resume_download (bool, optional, defaults to False) —
Whether or not to delete incompletely received file. Attempts to resume the download if such a file
exists.   proxies (Dict[str, str], optional) —
A dictionary of proxy servers to use by protocol or endpoint, e.g., {'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}. The proxies are used on each request.   token (str or bool, optional) —
The token to use as HTTP bearer authorization for remote files. If True, or not specified, will use
the token generated when running huggingface-cli login (stored in ~/.huggingface).   revision (str, optional, defaults to "main") —
The specific model version to use. It can be a branch name, a tag name,


GenerationConfig

or a commit id, since we use a
git-based system for storing models and other artifacts on huggingface.co, so revision can be any
identifier allowed by git.
To test a pull request you made on the Hub, you can pass `revision=“refs/pr/“.
   return_unused_kwargs (bool, optional, defaults to False) —
If False, then this function returns just the final configuration object.
If True, then this functions returns a Tuple(config, unused_kwargs) where unused_kwargs is a
dictionary consisting of the key/value pairs whose keys are not configuration attributes: i.e., the
part of kwargs which has not been used to update config and is otherwise ignored.   subfolder (str, optional, defaults to "") —
In case the relevant files are located inside a subfolder of the model repo on huggingface.co, you can
specify the folder name here.   kwargs (Dict[str, Any], optional) —
The values in kwargs of any keys which are configuration attributes will be used to override the loaded
values. Beh


GenerationConfig

avior concerning key/value pairs whose keys are not configuration attributes is controlled
by the return_unused_kwargs keyword parameter.   Returns
GenerationConfig

The configuration object instantiated from this pretrained model.
  Instantiate a GenerationConfig from a generation configuration file.  Examples:   Copied >>> from transformers import GenerationConfig
>>> # Download configuration from huggingface.co and cache.
>>> generation_config = GenerationConfig.from_pretrained("gpt2")
>>> # E.g. config was saved using *save_pretrained('./test/saved_model/')*
>>> generation_config.save_pretrained("./test/saved_model/")
>>> generation_config = GenerationConfig.from_pretrained("./test/saved_model/")
>>> # You can also specify configuration names to your generation configuration file
>>> generation_config.save_pretrained("./test/saved_model/", config_file_name="my_configuration.json")
>>> generation_config = GenerationConfig.from_pretrained("./test/saved_model/


GenerationConfig

", "my_configuration.json")
>>> # If you'd like to try a minor variation to an existing configuration, you can also pass generation
>>> # arguments to `.from_pretrained()`. Be mindful that typos and unused arguments will be ignored
>>> generation_config, unused_kwargs = GenerationConfig.from_pretrained(
...     "gpt2", top_k=1, foo=False, do_sample=True, return_unused_kwargs=True
... )
>>> generation_config.top_k
1
>>> unused_kwargs
{'foo': False}  from_model_config  < source > ( model_config: PretrainedConfig  ) → GenerationConfig  Parameters   model_config (PretrainedConfig) —
The model config that will be used to instantiate the generation config.   Returns
GenerationConfig

The configuration object instantiated from those parameters.
  Instantiates a GenerationConfig from a PretrainedConfig. This function is useful to convert legacy
PretrainedConfig objects, which may contain generation parameters, into a stand-alone GenerationConfig.  save_pretrained  < so


GenerationConfig

urce > ( save_directory: typing.Union[str, os.PathLike] config_file_name: typing.Union[str, os.PathLike, NoneType] = None push_to_hub: bool = False **kwargs  )   Parameters   save_directory (str or os.PathLike) —
Directory where the configuration JSON file will be saved (will be created if it does not exist).   config_file_name (str or os.PathLike, optional, defaults to "generation_config.json") —
Name of the generation configuration JSON file to be saved in save_directory.   push_to_hub (bool, optional, defaults to False) —
Whether or not to push your model to the Hugging Face model hub after saving it. You can specify the
repository you want to push to with repo_id (will default to the name of save_directory in your
namespace).   kwargs (Dict[str, Any], optional) —
Additional key word arguments passed along to the push_to_hub() method.    Save a generation configuration object to the directory save_directory, so that it can be re-loaded using the
from_pretrained


GenerationMixin

class transformers.GenerationMixin  < source > ( )    A class containing all functions for auto-regressive text generation, to be used as a mixin in PreTrainedModel. The class exposes generate(), which can be used for: greedy decoding by calling greedy_search() if num_beams=1 and
do_sample=False contrastive search by calling contrastive_search() if penalty_alpha>0 and
top_k>1 multinomial sampling by calling sample() if num_beams=1 and
do_sample=True beam-search decoding by calling beam_search() if num_beams>1 and
do_sample=False beam-search multinomial sampling by calling beam_sample() if num_beams>1
and do_sample=True diverse beam-search decoding by calling group_beam_search(), if num_beams>1
and num_beam_groups>1 constrained beam-search decoding by calling constrained_beam_search(), if
constraints!=None or force_words_ids!=None You do not need to call any of the above methods directly. Pass custom parameter values to ‘generate’ instead. To
learn more about decoding strate


GenerationMixin

gies refer to the text generation strategies guide.  generate  < source > ( inputs: typing.Optional[torch.Tensor] = None generation_config: typing.Optional[transformers.generation.configuration_utils.GenerationConfig] = None logits_processor: typing.Optional[transformers.generation.logits_process.LogitsProcessorList] = None stopping_criteria: typing.Optional[transformers.generation.stopping_criteria.StoppingCriteriaList] = None prefix_allowed_tokens_fn: typing.Union[typing.Callable[[int, torch.Tensor], typing.List[int]], NoneType] = None synced_gpus: typing.Optional[bool] = None assistant_model: typing.Optional[ForwardRef('PreTrainedModel')] = None streamer: typing.Optional[ForwardRef('BaseStreamer')] = None negative_prompt_ids: typing.Optional[torch.Tensor] = None negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None **kwargs  ) → ModelOutput or torch.LongTensor  Parameters   inputs (torch.Tensor of varying shape depending on the modality, optional) —
The se


GenerationMixin

quence used as a prompt for the generation or as model inputs to the encoder. If None the
method initializes it with bos_token_id and a batch size of 1. For decoder-only models inputs
should of in the format of input_ids. For encoder-decoder models inputs can represent any of
input_ids, input_values, input_features, or pixel_values.   generation_config (~generation.GenerationConfig, optional) —
The generation configuration to be used as base parametrization for the generation call. **kwargs
passed to generate matching the attributes of generation_config will override them. If
generation_config is not provided, the default will be used, which had the following loading
priority: 1) from the generation_config.json model file, if it exists; 2) from the model
configuration. Please note that unspecified parameters will inherit GenerationConfig’s
default values, whose documentation should be checked to parameterize generation.   logits_processor (LogitsProcessorList, optional) —
C


GenerationMixin

ustom logits processors that complement the default logits processors built from arguments and
generation config. If a logit processor is passed that is already created with the arguments or a
generation config an error is thrown. This feature is intended for advanced users.   stopping_criteria (StoppingCriteriaList, optional) —
Custom stopping criteria that complement the default stopping criteria built from arguments and a
generation config. If a stopping criteria is passed that is already created with the arguments or a
generation config an error is thrown. This feature is intended for advanced users.   prefix_allowed_tokens_fn (Callable[[int, torch.Tensor], List[int]], optional) —
If provided, this function constraints the beam search to allowed tokens only at each step. If not
provided no constraint is applied. This function takes 2 arguments: the batch ID batch_id and
input_ids. It has to return a list with the allowed tokens for the next generation step conditioned
o


GenerationMixin

n the batch ID batch_id and the previously generated tokens inputs_ids. This argument is useful
for constrained generation conditioned on the prefix, as described in Autoregressive Entity
Retrieval.   synced_gpus (bool, optional) —
Whether to continue running the while loop until max_length. Unless overridden this flag will be set to
True under DeepSpeed ZeRO Stage 3 multiple GPUs environment to avoid hanging if one GPU finished
generating before other GPUs. Otherwise it’ll be set to False.   assistant_model (PreTrainedModel, optional) —
An assistant model that can be used to accelerate generation. The assistant model must have the exact
same tokenizer. The acceleration is achieved when forecasting candidate tokens with the assistent model
is much faster than running generation with the model you’re calling generate from. As such, the
assistant model should be much smaller.   streamer (BaseStreamer, optional) —
Streamer object that will be used to stream the generated seque


GenerationMixin

nces. Generated tokens are passed
through streamer.put(token_ids) and the streamer is responsible for any further processing.   negative_prompt_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) —
The negative prompt needed for some processors such as CFG. The batch size must match the input batch
size. This is an experimental feature, subject to breaking API changes in future versions.   negative_prompt_attention_mask (torch.LongTensor of shape (batch_size, sequence_length), optional) —
Attention_mask for negative_prompt_ids.   kwargs (Dict[str, Any], optional) —
Ad hoc parametrization of generate_config and/or additional model-specific kwargs that will be
forwarded to the forward function of the model. If the model is an encoder-decoder model, encoder
specific kwargs should not be prefixed and decoder specific kwargs should be prefixed with decoder_.   Returns
ModelOutput or torch.LongTensor

A ModelOutput (if return_dict_in_generate=True
or when c


GenerationMixin

onfig.return_dict_in_generate=True) or a torch.FloatTensor.
If the model is not an encoder-decoder model (model.config.is_encoder_decoder=False), the possible
ModelOutput types are:
GreedySearchDecoderOnlyOutput,
SampleDecoderOnlyOutput,
BeamSearchDecoderOnlyOutput,
BeamSampleDecoderOnlyOutput
If the model is an encoder-decoder model (model.config.is_encoder_decoder=True), the possible
ModelOutput types are:
GreedySearchEncoderDecoderOutput,
SampleEncoderDecoderOutput,
BeamSearchEncoderDecoderOutput,
BeamSampleEncoderDecoderOutput
  Generates sequences of token ids for models with a language modeling head. Most generation-controlling parameters are set in generation_config which, if not passed, will be set to the
model’s default generation configuration. You can override any generation_config by passing the corresponding
parameters to generate(), e.g. .generate(inputs, num_beams=4, do_sample=True). For an overview of generation strategies and code examples, check out the fo


GenerationMixin

llowing
guide.  compute_transition_scores  < source > ( sequences: Tensor scores: typing.Tuple[torch.Tensor] beam_indices: typing.Optional[torch.Tensor] = None normalize_logits: bool = False  ) → torch.Tensor  Parameters   sequences (torch.LongTensor) —
The generated sequences. The second dimension (sequence_length) is either equal to max_length or
shorter if all batches finished early due to the eos_token_id.   scores (tuple(torch.FloatTensor)) —
Transition scores for each vocabulary token at each generation step. Beam transition scores consisting
of log probabilities of tokens conditioned on log softmax of previously generated tokens Tuple of
torch.FloatTensor with up to max_new_tokens elements (one element for each generated token), with
each tensor of shape (batch_size*num_beams, config.vocab_size).   beam_indices (torch.LongTensor, optional) —
Beam indices of generated token id at each generation step. torch.LongTensor of shape
(batch_size*num_return_sequences, sequenc


GenerationMixin

e_length). Only required if a num_beams>1 at
generate-time.   normalize_logits (bool, optional, defaults to False) —
Whether to normalize the logits (which, for legacy reasons, may be unnormalized).   Returns
torch.Tensor

A torch.Tensor of shape (batch_size*num_return_sequences, sequence_length) containing
the transition scores (logits)
  Computes the transition scores of sequences given the generation scores (and beam indices, if beam search was
used). This is a convenient method to quicky obtain the scores of the selected tokens at generation time.  Examples:   Copied >>> from transformers import GPT2Tokenizer, AutoModelForCausalLM
>>> import numpy as np
>>> tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
>>> model = AutoModelForCausalLM.from_pretrained("gpt2")
>>> tokenizer.pad_token_id = tokenizer.eos_token_id
>>> inputs = tokenizer(["Today is"], return_tensors="pt")
>>> # Example 1: Print the scores for each token generated with Greedy Search
>>> outputs = model.


GenerationMixin

generate(**inputs, max_new_tokens=5, return_dict_in_generate=True, output_scores=True)
>>> transition_scores = model.compute_transition_scores(
...     outputs.sequences, outputs.scores, normalize_logits=True
... )
>>> # input_length is the length of the input prompt for decoder-only models, like the GPT family, and 1 for
>>> # encoder-decoder models, like BART or T5.
>>> input_length = 1 if model.config.is_encoder_decoder else inputs.input_ids.shape[1]
>>> generated_tokens = outputs.sequences[:, input_length:]
>>> for tok, score in zip(generated_tokens[0], transition_scores[0]):
...     # | token | token string | logits | probability
...     print(f"| {tok:5d} | {tokenizer.decode(tok):8s} | {score.numpy():.3f} | {np.exp(score.numpy()):.2%}")
|   262 |  the     | -1.414 | 24.33%
|  1110 |  day     | -2.609 | 7.36%
|   618 |  when    | -2.010 | 13.40%
|   356 |  we      | -1.859 | 15.58%
|   460 |  can     | -2.508 | 8.14%
>>> # Example 2: Reconstruct the sequence scores fro


GenerationMixin

m Beam Search
>>> outputs = model.generate(
...     **inputs,
...     max_new_tokens=5,
...     num_beams=4,
...     num_return_sequences=4,
...     return_dict_in_generate=True,
...     output_scores=True,
... )
>>> transition_scores = model.compute_transition_scores(
...     outputs.sequences, outputs.scores, outputs.beam_indices, normalize_logits=False
... )
>>> # If you sum the generated tokens' scores and apply the length penalty, you'll get the sequence scores.
>>> # Tip: recomputing the scores is only guaranteed to match with `normalize_logits=False`. Depending on the
>>> # use case, you might want to recompute it with `normalize_logits=True`.
>>> output_length = input_length + np.sum(transition_scores.numpy() < 0, axis=1)
>>> length_penalty = model.generation_config.length_penalty
>>> reconstructed_scores = transition_scores.sum(axis=1) / (output_length**length_penalty)
>>> print(np.allclose(outputs.sequences_scores, reconstructed_scores))
True  greedy_search  < sou


GenerationMixin

rce > ( input_ids: LongTensor logits_processor: typing.Optional[transformers.generation.logits_process.LogitsProcessorList] = None stopping_criteria: typing.Optional[transformers.generation.stopping_criteria.StoppingCriteriaList] = None max_length: typing.Optional[int] = None pad_token_id: typing.Optional[int] = None eos_token_id: typing.Union[int, typing.List[int], NoneType] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None output_scores: typing.Optional[bool] = None return_dict_in_generate: typing.Optional[bool] = None synced_gpus: bool = False streamer: typing.Optional[ForwardRef('BaseStreamer')] = None **model_kwargs  )   Parameters   input_ids (torch.LongTensor of shape (batch_size, sequence_length)) —
The sequence used as a prompt for the generation.   logits_processor (LogitsProcessorList, optional) —
An instance of LogitsProcessorList. List of instances of class derived from LogitsProcessor
used to modify the p


GenerationMixin

rediction scores of the language modeling head applied at each generation step.   stopping_criteria (StoppingCriteriaList, optional) —
An instance of StoppingCriteriaList. List of instances of class derived from StoppingCriteria
used to tell if the generation loop should stop.   max_length (int, optional, defaults to 20) —
DEPRECATED. Use logits_processor or stopping_criteria directly to cap the number of generated
tokens. The maximum length of the sequence to be generated.   pad_token_id (int, optional) —
The id of the padding token.   eos_token_id (Union[int, List[int]], optional) —
The id of the end-of-sequence token. Optionally, use a list to set multiple end-of-sequence tokens.   output_attentions (bool, optional, defaults to False) —
Whether or not to return the attentions tensors of all attention layers. See attentions under
returned tensors for more details.   output_hidden_states (bool, optional, defaults to False) —
Whether or not to return the hidden states of al


GenerationMixin

l layers. See hidden_states under returned tensors
for more details.   output_scores (bool, optional, defaults to False) —
Whether or not to return the prediction scores. See scores under returned tensors for more details.   return_dict_in_generate (bool, optional, defaults to False) —
Whether or not to return a ModelOutput instead of a plain tuple.   synced_gpus (bool, optional, defaults to False) —
Whether to continue running the while loop until max_length (needed for ZeRO stage 3)   streamer (BaseStreamer, optional) —
Streamer object that will be used to stream the generated sequences. Generated tokens are passed
through streamer.put(token_ids) and the streamer is responsible for any further processing.
model_kwargs —
Additional model specific keyword arguments will be forwarded to the forward function of the model.
If model is an encoder-decoder model the kwargs should include encoder_outputs.    Generates sequences of token ids for models with a language modeling head


GenerationMixin

 using greedy decoding and can be
used for text-decoder, text-to-text, speech-to-text, and vision-to-text models. In most cases, you do not need to call greedy_search() directly. Use generate()
instead. For an overview of generation strategies and code examples, check the following
guide.  Examples:   Copied >>> from transformers import (
...     AutoTokenizer,
...     AutoModelForCausalLM,
...     LogitsProcessorList,
...     MinLengthLogitsProcessor,
...     StoppingCriteriaList,
...     MaxLengthCriteria,
... )
>>> tokenizer = AutoTokenizer.from_pretrained("gpt2")
>>> model = AutoModelForCausalLM.from_pretrained("gpt2")
>>> # set pad_token_id to eos_token_id because GPT2 does not have a PAD token
>>> model.generation_config.pad_token_id = model.generation_config.eos_token_id
>>> input_prompt = "It might be possible to"
>>> input_ids = tokenizer(input_prompt, return_tensors="pt").input_ids
>>> # instantiate logits processors
>>> logits_processor = LogitsProcessorList(
...


GenerationMixin

     [
...         MinLengthLogitsProcessor(10, eos_token_id=model.generation_config.eos_token_id),
...     ]
... )
>>> stopping_criteria = StoppingCriteriaList([MaxLengthCriteria(max_length=20)])
>>> outputs = model.greedy_search(
...     input_ids, logits_processor=logits_processor, stopping_criteria=stopping_criteria
... )
>>> tokenizer.batch_decode(outputs, skip_special_tokens=True)
["It might be possible to get a better understanding of the nature of the problem, but it's not"]  sample  < source > ( input_ids: LongTensor logits_processor: typing.Optional[transformers.generation.logits_process.LogitsProcessorList] = None stopping_criteria: typing.Optional[transformers.generation.stopping_criteria.StoppingCriteriaList] = None logits_warper: typing.Optional[transformers.generation.logits_process.LogitsProcessorList] = None max_length: typing.Optional[int] = None pad_token_id: typing.Optional[int] = None eos_token_id: typing.Union[int, typing.List[int], NoneType] = None ou


GenerationMixin

tput_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None output_scores: typing.Optional[bool] = None return_dict_in_generate: typing.Optional[bool] = None synced_gpus: bool = False streamer: typing.Optional[ForwardRef('BaseStreamer')] = None **model_kwargs  ) → SampleDecoderOnlyOutput, SampleEncoderDecoderOutput or torch.LongTensor  Parameters   input_ids (torch.LongTensor of shape (batch_size, sequence_length)) —
The sequence used as a prompt for the generation.   logits_processor (LogitsProcessorList, optional) —
An instance of LogitsProcessorList. List of instances of class derived from LogitsProcessor
used to modify the prediction scores of the language modeling head applied at each generation step.   stopping_criteria (StoppingCriteriaList, optional) —
An instance of StoppingCriteriaList. List of instances of class derived from StoppingCriteria
used to tell if the generation loop should stop.   logits_warper (LogitsProcessorList,


GenerationMixin

 optional) —
An instance of LogitsProcessorList. List of instances of class derived from LogitsWarper used
to warp the prediction score distribution of the language modeling head applied before multinomial
sampling at each generation step.   max_length (int, optional, defaults to 20) —
DEPRECATED. Use logits_processor or stopping_criteria directly to cap the number of generated
tokens. The maximum length of the sequence to be generated.   pad_token_id (int, optional) —
The id of the padding token.   eos_token_id (Union[int, List[int]], optional) —
The id of the end-of-sequence token. Optionally, use a list to set multiple end-of-sequence tokens.   output_attentions (bool, optional, defaults to False) —
Whether or not to return the attentions tensors of all attention layers. See attentions under
returned tensors for more details.   output_hidden_states (bool, optional, defaults to False) —
Whether or not to return the hidden states of all layers. See hidden_states under retu


GenerationMixin

rned tensors
for more details.   output_scores (bool, optional, defaults to False) —
Whether or not to return the prediction scores. See scores under returned tensors for more details.   return_dict_in_generate (bool, optional, defaults to False) —
Whether or not to return a ModelOutput instead of a plain tuple.   synced_gpus (bool, optional, defaults to False) —
Whether to continue running the while loop until max_length (needed for ZeRO stage 3)   streamer (BaseStreamer, optional) —
Streamer object that will be used to stream the generated sequences. Generated tokens are passed
through streamer.put(token_ids) and the streamer is responsible for any further processing.
model_kwargs —
Additional model specific kwargs will be forwarded to the forward function of the model. If model is
an encoder-decoder model the kwargs should include encoder_outputs.   Returns
SampleDecoderOnlyOutput, SampleEncoderDecoderOutput or torch.LongTensor

A torch.LongTensor containing the gener


GenerationMixin

ated tokens (default behaviour) or a
SampleDecoderOnlyOutput if model.config.is_encoder_decoder=False and
return_dict_in_generate=True or a SampleEncoderDecoderOutput if
model.config.is_encoder_decoder=True.
  Generates sequences of token ids for models with a language modeling head using multinomial sampling and
can be used for text-decoder, text-to-text, speech-to-text, and vision-to-text models. In most cases, you do not need to call sample() directly. Use generate() instead.
For an overview of generation strategies and code examples, check the following
guide.  Examples:   Copied >>> from transformers import (
...     AutoTokenizer,
...     AutoModelForCausalLM,
...     LogitsProcessorList,
...     MinLengthLogitsProcessor,
...     TopKLogitsWarper,
...     TemperatureLogitsWarper,
...     StoppingCriteriaList,
...     MaxLengthCriteria,
... )
>>> import torch
>>> tokenizer = AutoTokenizer.from_pretrained("gpt2")
>>> model = AutoModelForCausalLM.from_pretrained("gpt2")


GenerationMixin

>>> # set pad_token_id to eos_token_id because GPT2 does not have a EOS token
>>> model.config.pad_token_id = model.config.eos_token_id
>>> model.generation_config.pad_token_id = model.config.eos_token_id
>>> input_prompt = "Today is a beautiful day, and"
>>> input_ids = tokenizer(input_prompt, return_tensors="pt").input_ids
>>> # instantiate logits processors
>>> logits_processor = LogitsProcessorList(
...     [
...         MinLengthLogitsProcessor(15, eos_token_id=model.generation_config.eos_token_id),
...     ]
... )
>>> # instantiate logits processors
>>> logits_warper = LogitsProcessorList(
...     [
...         TopKLogitsWarper(50),
...         TemperatureLogitsWarper(0.7),
...     ]
... )
>>> stopping_criteria = StoppingCriteriaList([MaxLengthCriteria(max_length=20)])
>>> torch.manual_seed(0)
>>> outputs = model.sample(
...     input_ids,
...     logits_processor=logits_processor,
...     logits_warper=logits_warper,
...     stopping_criteria=stopping_criteria,
... )


GenerationMixin

>>> tokenizer.batch_decode(outputs, skip_special_tokens=True)
['Today is a beautiful day, and we must do everything possible to make it a day of celebration.']  beam_search  < source > ( input_ids: LongTensor beam_scorer: BeamScorer logits_processor: typing.Optional[transformers.generation.logits_process.LogitsProcessorList] = None stopping_criteria: typing.Optional[transformers.generation.stopping_criteria.StoppingCriteriaList] = None max_length: typing.Optional[int] = None pad_token_id: typing.Optional[int] = None eos_token_id: typing.Union[int, typing.List[int], NoneType] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None output_scores: typing.Optional[bool] = None return_dict_in_generate: typing.Optional[bool] = None synced_gpus: bool = False **model_kwargs  )   Parameters   input_ids (torch.LongTensor of shape (batch_size, sequence_length)) —
The sequence used as a prompt for the generation.   beam_scorer (BeamSco


GenerationMixin

rer) —
An derived instance of BeamScorer that defines how beam hypotheses are constructed, stored and
sorted during generation. For more information, the documentation of BeamScorer should be read.   logits_processor (LogitsProcessorList, optional) —
An instance of LogitsProcessorList. List of instances of class derived from LogitsProcessor
used to modify the prediction scores of the language modeling head applied at each generation step.   stopping_criteria (StoppingCriteriaList, optional) —
An instance of StoppingCriteriaList. List of instances of class derived from StoppingCriteria
used to tell if the generation loop should stop.   max_length (int, optional, defaults to 20) —
DEPRECATED. Use logits_processor or stopping_criteria directly to cap the number of generated
tokens. The maximum length of the sequence to be generated.   pad_token_id (int, optional) —
The id of the padding token.   eos_token_id (Union[int, List[int]], optional) —
The id of the end-of-sequence tok


GenerationMixin

en. Optionally, use a list to set multiple end-of-sequence tokens.   output_attentions (bool, optional, defaults to False) —
Whether or not to return the attentions tensors of all attention layers. See attentions under
returned tensors for more details.   output_hidden_states (bool, optional, defaults to False) —
Whether or not to return the hidden states of all layers. See hidden_states under returned tensors
for more details.   output_scores (bool, optional, defaults to False) —
Whether or not to return the prediction scores. See scores under returned tensors for more details.   return_dict_in_generate (bool, optional, defaults to False) —
Whether or not to return a ModelOutput instead of a plain tuple.   synced_gpus (bool, optional, defaults to False) —
Whether to continue running the while loop until max_length (needed for ZeRO stage 3)
model_kwargs —
Additional model specific kwargs will be forwarded to the forward function of the model. If model is
an encoder-decoder


GenerationMixin

model the kwargs should include encoder_outputs.    Generates sequences of token ids for models with a language modeling head using beam search decoding and
can be used for text-decoder, text-to-text, speech-to-text, and vision-to-text models. In most cases, you do not need to call beam_search() directly. Use generate()
instead. For an overview of generation strategies and code examples, check the following
guide.  Examples:   Copied >>> from transformers import (
...     AutoTokenizer,
...     AutoModelForSeq2SeqLM,
...     LogitsProcessorList,
...     MinLengthLogitsProcessor,
...     BeamSearchScorer,
... )
>>> import torch
>>> tokenizer = AutoTokenizer.from_pretrained("t5-base")
>>> model = AutoModelForSeq2SeqLM.from_pretrained("t5-base")
>>> encoder_input_str = "translate English to German: How old are you?"
>>> encoder_input_ids = tokenizer(encoder_input_str, return_tensors="pt").input_ids
>>> # lets run beam search using 3 beams
>>> num_beams = 3
>>> # define decoder


GenerationMixin

 start token ids
>>> input_ids = torch.ones((num_beams, 1), device=model.device, dtype=torch.long)
>>> input_ids = input_ids * model.config.decoder_start_token_id
>>> # add encoder_outputs to model keyword arguments
>>> model_kwargs = {
...     "encoder_outputs": model.get_encoder()(
...         encoder_input_ids.repeat_interleave(num_beams, dim=0), return_dict=True
...     )
... }
>>> # instantiate beam scorer
>>> beam_scorer = BeamSearchScorer(
...     batch_size=1,
...     num_beams=num_beams,
...     device=model.device,
... )
>>> # instantiate logits processors
>>> logits_processor = LogitsProcessorList(
...     [
...         MinLengthLogitsProcessor(5, eos_token_id=model.config.eos_token_id),
...     ]
... )
>>> outputs = model.beam_search(input_ids, beam_scorer, logits_processor=logits_processor, **model_kwargs)
>>> tokenizer.batch_decode(outputs, skip_special_tokens=True)
['Wie alt bist du?']  beam_sample  < source > ( input_ids: LongTensor beam_scorer: BeamScorer l


GenerationMixin

ogits_processor: typing.Optional[transformers.generation.logits_process.LogitsProcessorList] = None stopping_criteria: typing.Optional[transformers.generation.stopping_criteria.StoppingCriteriaList] = None logits_warper: typing.Optional[transformers.generation.logits_process.LogitsProcessorList] = None max_length: typing.Optional[int] = None pad_token_id: typing.Optional[int] = None eos_token_id: typing.Union[int, typing.List[int], NoneType] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None output_scores: typing.Optional[bool] = None return_dict_in_generate: typing.Optional[bool] = None synced_gpus: bool = False **model_kwargs  )   Parameters   input_ids (torch.LongTensor of shape (batch_size, sequence_length)) —
The sequence used as a prompt for the generation.   beam_scorer (BeamScorer) —
A derived instance of BeamScorer that defines how beam hypotheses are constructed, stored and
sorted during generation. For more i


GenerationMixin

nformation, the documentation of BeamScorer should be read.   logits_processor (LogitsProcessorList, optional) —
An instance of LogitsProcessorList. List of instances of class derived from LogitsProcessor
used to modify the prediction scores of the language modeling head applied at each generation step.   stopping_criteria (StoppingCriteriaList, optional) —
An instance of StoppingCriteriaList. List of instances of class derived from StoppingCriteria
used to tell if the generation loop should stop.   logits_warper (LogitsProcessorList, optional) —
An instance of LogitsProcessorList. List of instances of class derived from LogitsWarper used
to warp the prediction score distribution of the language modeling head applied before multinomial
sampling at each generation step.   max_length (int, optional, defaults to 20) —
DEPRECATED. Use logits_processor or stopping_criteria directly to cap the number of generated
tokens. The maximum length of the sequence to be generated.   pad_t