Buckets:
Trainer
Trainer クラスは、ほとんどの標準的なユースケースに対して、PyTorch で機能を完全にトレーニングするための API を提供します。これは、サンプル スクリプト のほとんどで使用されています。
Trainer をインスタンス化する前に、トレーニング中にカスタマイズのすべてのポイントにアクセスするために TrainingArguments を作成します。
この API は、複数の GPU/TPU での分散トレーニング、PyTorch のネイティブ AMP による混合精度をサポートします。
Trainer には、上記の機能をサポートする基本的なトレーニング ループが含まれています。カスタム動作を挿入するには、それらをサブクラス化し、次のメソッドをオーバーライドします。
- get_train_dataloader -- トレーニング データローダーを作成します。
- get_eval_dataloader -- 評価用データローダーを作成します。
- get_test_dataloader -- テスト データローダーを作成します。
- log -- トレーニングを監視しているさまざまなオブジェクトに関する情報をログに記録します。
- create_optimizer_and_scheduler -- オプティマイザと学習率スケジューラが渡されなかった場合にセットアップします。
初期化。
create_optimizerメソッドとcreate_schedulerメソッドをサブクラス化またはオーバーライドすることもできることに注意してください。 別々に。 - create_optimizer -- init で渡されなかった場合にオプティマイザーをセットアップします。
- create_scheduler -- init で渡されなかった場合、学習率スケジューラを設定します。
- compute_loss - トレーニング入力のバッチの損失を計算します。
- training_step -- トレーニング ステップを実行します。
- prediction_step -- 評価/テスト ステップを実行します。
- evaluate -- 評価ループを実行し、メトリクスを返します。
- predict -- テスト セットの予測 (ラベルが使用可能な場合はメトリクスも含む) を返します。
Trainer クラスは 🤗 Transformers モデル用に最適化されており、驚くべき動作をする可能性があります 他の機種で使用する場合。独自のモデルで使用する場合は、次の点を確認してください。
- モデルは常に ModelOutput のタプルまたはサブクラスを返します。
labels引数が指定され、その損失が最初の値として返される場合、モデルは損失を計算できます。 タプルの要素 (モデルがタプルを返す場合)- モデルは複数のラベル引数を受け入れることができます (TrainingArguments で
label_namesを使用して、その名前を Trainer に示します) が、それらのいずれにも"label"という名前を付ける必要はありません。
以下は、加重損失を使用するように Trainer をカスタマイズする方法の例です (不均衡なトレーニング セットがある場合に役立ちます)。
from torch import nn
from transformers import Trainer
class CustomTrainer(Trainer):
def compute_loss(self, model, inputs, return_outputs=False):
labels = inputs.pop("labels")
# forward pass
outputs = model(**inputs)
logits = outputs.get("logits")
# compute custom loss (suppose one has 3 labels with different weights)
loss_fct = nn.CrossEntropyLoss(weight=torch.tensor([1.0, 2.0, 3.0], device=model.device))
loss = loss_fct(logits.view(-1, self.model.config.num_labels), labels.view(-1))
return (loss, outputs) if return_outputs else loss
PyTorch Trainer のトレーニング ループの動作をカスタマイズするもう 1 つの方法は、トレーニング ループの状態を検査できる callbacks を使用することです (進行状況レポート、TensorBoard または他の ML プラットフォームでのログ記録など)。決定(早期停止など)。
Trainer[[transformers.Trainer]]
transformers.Trainer[[transformers.Trainer]]
Trainer is a simple but feature-complete training and eval loop for PyTorch, optimized for 🤗 Transformers.
Important attributes:
- model -- Always points to the core model. If using a transformers model, it will be a PreTrainedModel subclass.
- model_wrapped -- Always points to the most external model in case one or more other modules wrap the
original model. This is the model that should be used for the forward pass. For example, under
DeepSpeed, the inner model is wrapped inDeepSpeedand then again intorch.nn.DistributedDataParallel. If the inner model hasn't been wrapped, thenself.model_wrappedis the same asself.model. - is_model_parallel -- Whether or not a model has been switched to a model parallel mode (different from data parallelism, this means some of the model layers are split on different GPUs).
- place_model_on_device -- Whether or not to automatically place the model on the device. Defaults to
Trueunless model parallel, DeepSpeed, FSDP, full fp16/bf16 eval, or SageMaker MP is active. Can be overridden by subclassingTrainingArgumentsand overriding theplace_model_on_deviceproperty. - is_in_train -- Whether or not a model is currently running
train(e.g. whenevaluateis called while intrain)
add_callbacktransformers.Trainer.add_callbackhttps://github.com/huggingface/transformers/blob/main/src/transformers/trainer.py#L4373[{"name": "callback", "val": ": type[transformers.trainer_callback.TrainerCallback] | transformers.trainer_callback.TrainerCallback"}]- callback (type or [~transformers.TrainerCallback]) --
A TrainerCallback class or an instance of a TrainerCallback. In the
first case, will instantiate a member of that class.0
Add a callback to the current list of TrainerCallback.
Parameters:
model (PreTrainedModel or torch.nn.Module, optional) : The model to train, evaluate or use for predictions. If not provided, a model_init must be passed. Trainer is optimized to work with the PreTrainedModel provided by the library. You can still use your own models defined as torch.nn.Module as long as they work the same way as the 🤗 Transformers models.
args (TrainingArguments, optional) : The arguments to tweak for training. Will default to a basic instance of TrainingArguments with the output_dir set to a directory named tmp_trainer in the current directory if not provided.
data_collator (DataCollator, optional) : The function to use to form a batch from a list of elements of train_dataset or eval_dataset. Will default to default_data_collator() if no processing_class is provided, an instance of DataCollatorWithPadding otherwise if the processing_class is a feature extractor or tokenizer.
train_dataset (torch.utils.data.Dataset | torch.utils.data.IterableDataset | datasets.Dataset, optional) : The dataset to use for training. If it is a Dataset, columns not accepted by the model.forward() method are automatically removed. Note that if it's a torch.utils.data.IterableDataset with some randomization and you are training in a distributed fashion, your iterable dataset should either use a internal attribute generator that is a torch.Generator for the randomization that must be identical on all processes (and the Trainer will manually set the seed of this generator at each epoch) or have a set_epoch() method that internally sets the seed of the RNGs used.
eval_dataset (torch.utils.data.Dataset | dict[str, torch.utils.data.Dataset] | datasets.Dataset, optional) : The dataset to use for evaluation. If it is a Dataset, columns not accepted by the model.forward() method are automatically removed. If it is a dictionary, it will evaluate on each dataset prepending the dictionary key to the metric name.
processing_class (PreTrainedTokenizerBase or BaseImageProcessor or FeatureExtractionMixin or ProcessorMixin, optional) : Processing class used to process the data. If provided, will be used to automatically process the inputs for the model, and it will be saved along the model to make it easier to rerun an interrupted training or reuse the fine-tuned model.
model_init (Callable[[], PreTrainedModel], optional) : A function that instantiates the model to be used. If provided, each call to train() will start from a new instance of the model as given by this function. The function may have zero argument, or a single one containing the optuna/Ray Tune trial object, to be able to choose different architectures according to hyperparameters (such as layer count, sizes of inner layers, dropout probabilities etc).
compute_loss_func (Callable, optional) : A function that accepts the raw model outputs, labels, and the number of items in the entire accumulated batch (batch_size * gradient_accumulation_steps) and returns the loss. For example, see the default loss function used by Trainer.
compute_metrics (Callable[[EvalPrediction], Dict], optional) : The function that will be used to compute metrics at evaluation. Must take a EvalPrediction and return a dictionary string to metric values. Note When passing TrainingArgs with batch_eval_metrics set to True, your compute_metrics function must take a boolean compute_result argument. This will be triggered after the last eval batch to signal that the function needs to calculate and return the global summary statistics rather than accumulating the batch-level statistics
callbacks (List of TrainerCallback, optional) : A list of callbacks to customize the training loop. Will add those to the list of default callbacks detailed in here. If you want to remove one of the default callbacks used, use the Trainer.remove_callback() method.
optimizers (tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR], optional, defaults to (None, None)) : A tuple containing the optimizer and the scheduler to use. Will default to an instance of AdamW on your model and a scheduler given by get_linear_schedule_with_warmup() controlled by args.
optimizer_cls_and_kwargs (tuple[Type[torch.optim.Optimizer], dict[str, Any]], optional) : A tuple containing the optimizer class and keyword arguments to use. Overrides optim and optim_args in args. Incompatible with the optimizers argument. Unlike optimizers, this argument avoids the need to place model parameters on the correct devices before initializing the Trainer.
preprocess_logits_for_metrics (Callable[[torch.Tensor, torch.Tensor], torch.Tensor], optional) : A function that preprocess the logits right before caching them at each evaluation step. Must take two tensors, the logits and the labels, and return the logits once processed as desired. The modifications made by this function will be reflected in the predictions received by compute_metrics. Note that the labels (second parameter) will be None if the dataset does not have them.
autocast_smart_context_manager[[transformers.Trainer.autocast_smart_context_manager]]
A helper wrapper that creates an appropriate context manager for autocast while feeding it the desired
arguments, depending on the situation. We rely on accelerate for autocast, hence we do nothing here.
call_model_init[[transformers.Trainer.call_model_init]]
Invoke model_init to get a fresh model instance, optionally conditioned on a hyperparameter trial.
compute_loss[[transformers.Trainer.compute_loss]]
How the loss is computed by Trainer. By default, all models return the loss in the first element.
Subclass and override for custom behavior. If you are not using num_items_in_batch when computing your loss,
make sure to overwrite self.model_accepts_loss_kwargs to False. Otherwise, the loss calculation might be slightly inaccurate when performing gradient accumulation.
Parameters:
model (nn.Module) : The model to compute the loss for.
inputs (dict[str, torch.Tensor | Any]) : The input data for the model.
return_outputs (bool, optional, defaults to False) : Whether to return the model outputs along with the loss.
num_items_in_batch (Optional[torch.Tensor], optional) : The number of items in the batch. If not passed, the loss is computed using the default batch size reduction logic.
Returns:
The loss of the model along with its output if return_outputs was set to True
compute_loss_context_manager[[transformers.Trainer.compute_loss_context_manager]]
A helper wrapper to group together context managers.
create_accelerator_and_postprocess[[transformers.Trainer.create_accelerator_and_postprocess]]
Create the accelerator and perform post-creation setup (FSDP, DeepSpeed, etc.).
create_model_card[[transformers.Trainer.create_model_card]]
Creates a draft of a model card using the information available to the Trainer.
Parameters:
language (str, optional) : The language of the model (if applicable)
license (str, optional) : The license of the model. Will default to the license of the pretrained model used, if the original model given to the Trainer comes from a repo on the Hub.
tags (str or list[str], optional) : Some tags to be included in the metadata of the model card.
model_name (str, optional) : The name of the model.
finetuned_from (str, optional) : The name of the model used to fine-tune this one (if applicable). Will default to the name of the repo of the original model given to the Trainer (if it comes from the Hub).
tasks (str or list[str], optional) : One or several task identifiers, to be included in the metadata of the model card.
dataset_tags (str or list[str], optional) : One or several dataset tags, to be included in the metadata of the model card.
dataset (str or list[str], optional) : One or several dataset identifiers, to be included in the metadata of the model card.
dataset_args (str or list[str], optional) : One or several dataset arguments, to be included in the metadata of the model card.
create_optimizer[[transformers.Trainer.create_optimizer]]
Setup the optimizer.
We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the
Trainer's init through optimizers, or subclass and override this method in a subclass.
Returns:
torch.optim.Optimizer
The optimizer instance.
create_optimizer_and_scheduler[[transformers.Trainer.create_optimizer_and_scheduler]]
Setup the optimizer and the learning rate scheduler.
We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the
Trainer's init through optimizers, or subclass and override this method (or create_optimizer and/or
create_scheduler) in a subclass.
create_scheduler[[transformers.Trainer.create_scheduler]]
Setup the scheduler. The optimizer of the trainer must have been set up either before this method is called or passed as an argument.
Parameters:
num_training_steps (int) : The number of training steps to do.
Returns:
torch.optim.lr_scheduler.LRScheduler
The learning rate scheduler instance.
evaluate[[transformers.Trainer.evaluate]]
Run evaluation and returns metrics.
The calling script will be responsible for providing a method to compute metrics, as they are task-dependent
(pass it to the init compute_metrics argument).
You can also subclass and override this method to inject custom behavior.
Parameters:
eval_dataset (Dataset | dict[str, Dataset], optional) : Pass a dataset if you wish to override self.eval_dataset. If it is a Dataset, columns not accepted by the model.forward() method are automatically removed. If it is a dictionary, it will evaluate on each dataset, prepending the dictionary key to the metric name. Datasets must implement the __len__ method. If you pass a dictionary with names of datasets as keys and datasets as values, evaluate will run separate evaluations on each dataset. This can be useful to monitor how training affects other datasets or simply to get a more fine-grained evaluation. When used with load_best_model_at_end, make sure metric_for_best_model references exactly one of the datasets. If you, for example, pass in {"data1": data1, "data2": data2} for two datasets data1 and data2, you could specify metric_for_best_model="eval_data1_loss" for using the loss on data1 and metric_for_best_model="eval_data2_loss" for the loss on data2.
ignore_keys (list[str], optional) : A list of keys in the output of your model (if it is a dictionary) that should be ignored when gathering predictions.
metric_key_prefix (str, optional, defaults to "eval") : An optional prefix to be used as the metrics key prefix. For example the metrics "bleu" will be named "eval_bleu" if the prefix is "eval" (default)
Returns:
A dictionary containing the evaluation loss and the potential metrics computed from the predictions. The dictionary also contains the epoch number which comes from the training state.
evaluation_loop[[transformers.Trainer.evaluation_loop]]
Prediction/evaluation loop, shared by Trainer.evaluate() and Trainer.predict().
Works both with or without labels.
floating_point_ops[[transformers.Trainer.floating_point_ops]]
For models that inherit from PreTrainedModel, uses that method to compute the number of floating point operations for every backward + forward pass. If using another model, either implement such a method in the model or subclass and override this method.
Parameters:
inputs (dict[str, torch.Tensor | Any]) : The inputs and targets of the model.
Returns:
int
The number of floating-point operations.
get_batch_samples[[transformers.Trainer.get_batch_samples]]
Collects a specified number of batches from the epoch iterator and optionally counts the number of items in the batches to properly scale the loss.
get_cp_size[[transformers.Trainer.get_cp_size]]
Get the context parallel size
get_decay_parameter_names[[transformers.Trainer.get_decay_parameter_names]]
Get all parameter names that weight decay will be applied to.
This function filters out parameters in two ways:
- By layer type (instances of layers specified in ALL_LAYERNORM_LAYERS)
- By parameter name patterns (containing 'bias', or variation of 'norm')
get_eval_dataloader[[transformers.Trainer.get_eval_dataloader]]
Returns the evaluation ~torch.utils.data.DataLoader.
Subclass and override this method if you want to inject some custom behavior.
Parameters:
eval_dataset (str or torch.utils.data.Dataset, optional) : If a str, will use self.eval_dataset[eval_dataset] as the evaluation dataset. If a Dataset, will override self.eval_dataset and must implement __len__. If it is a Dataset, columns not accepted by the model.forward() method are automatically removed.
get_learning_rates[[transformers.Trainer.get_learning_rates]]
Returns the learning rate of each parameter from self.optimizer.
get_num_trainable_parameters[[transformers.Trainer.get_num_trainable_parameters]]
Get the number of trainable parameters.
get_optimizer_cls_and_kwargs[[transformers.Trainer.get_optimizer_cls_and_kwargs]]
Returns the optimizer class and optimizer parameters based on the training arguments.
Parameters:
args (transformers.training_args.TrainingArguments) : The training arguments for the training session.
model (PreTrainedModel, optional) : The model being trained. Required for some optimizers (GaLore, Apollo, LOMO).
Returns:
A tuple containing the optimizer class and a dictionary of optimizer keyword arguments.
get_optimizer_group[[transformers.Trainer.get_optimizer_group]]
Returns optimizer group for a parameter if given, else returns all optimizer groups for params.
Parameters:
param (str or torch.nn.parameter.Parameter, optional) : The parameter for which optimizer group needs to be returned.
get_sp_size[[transformers.Trainer.get_sp_size]]
Get the sequence parallel size
get_test_dataloader[[transformers.Trainer.get_test_dataloader]]
Returns the test ~torch.utils.data.DataLoader.
Subclass and override this method if you want to inject some custom behavior.
Parameters:
test_dataset (torch.utils.data.Dataset, optional) : The test dataset to use. If it is a Dataset, columns not accepted by the model.forward() method are automatically removed. It must implement __len__.
get_total_train_batch_size[[transformers.Trainer.get_total_train_batch_size]]
Calculates total batch size (micro_batch * grad_accum * dp_world_size).
Accounts for all parallelism dimensions: TP, CP, and SP.
Formula: dp_world_size = world_size // (tp_size * cp_size * sp_size)
Where:
- TP (Tensor Parallelism): Model layers split across GPUs
- CP (Context Parallelism): Sequences split using Ring Attention (FSDP2)
- SP (Sequence Parallelism): Sequences split using ALST/Ulysses (DeepSpeed)
All dimensions are separate and multiplicative: world_size = dp_size * tp_size * cp_size * sp_size
get_tp_size[[transformers.Trainer.get_tp_size]]
Get the tensor parallel size from either the model or DeepSpeed config.
get_train_dataloader[[transformers.Trainer.get_train_dataloader]]
Returns the training ~torch.utils.data.DataLoader.
Will use no sampler if train_dataset does not implement __len__, a random sampler (adapted to distributed
training if necessary) otherwise.
Subclass and override this method if you want to inject some custom behavior.
hyperparameter_search[[transformers.Trainer.hyperparameter_search]]
Launch a hyperparameter search using optuna or Ray Tune. The optimized quantity is determined
by compute_objective, which defaults to a function returning the evaluation loss when no metric is provided,
the sum of all metrics otherwise.
To use this method, you need to have provided a model_init when initializing your Trainer: we need to
reinitialize the model at each new run. This is incompatible with the optimizers argument, so you need to
subclass Trainer and override the method create_optimizer_and_scheduler() for custom
optimizer/scheduler.
Parameters:
hp_space (Callable[["optuna.Trial"], dict[str, float]], optional) : A function that defines the hyperparameter search space. Will default to default_hp_space_optuna() or default_hp_space_ray() depending on your backend.
compute_objective (Callable[[dict[str, float]], float], optional) : A function computing the objective to minimize or maximize from the metrics returned by the evaluate method. Will default to default_compute_objective().
n_trials (int, optional, defaults to 100) : The number of trial runs to test.
direction (str or list[str], optional, defaults to "minimize") : If it's single objective optimization, direction is str, can be "minimize" or "maximize", you should pick "minimize" when optimizing the validation loss, "maximize" when optimizing one or several metrics. If it's multi objectives optimization, direction is list[str], can be List of "minimize" and "maximize", you should pick "minimize" when optimizing the validation loss, "maximize" when optimizing one or several metrics.
backend (str or ~training_utils.HPSearchBackend, optional) : The backend to use for hyperparameter search. Will default to optuna or Ray Tune, depending on which one is installed. If all are installed, will default to optuna.
hp_name (Callable[["optuna.Trial"], str]], optional) : A function that defines the trial/run name. Will default to None.
kwargs (dict[str, Any], optional) : Additional keyword arguments for each backend: - optuna: parameters from optuna.study.create_study and also the parameters timeout, n_jobs and gc_after_trial from optuna.study.Study.optimize - ray: parameters from tune.run. If resources_per_trial is not set in the kwargs, it defaults to 1 CPU core and 1 GPU (if available). If progress_reporter is not set in the kwargs, ray.tune.CLIReporter is used.
Returns:
[trainer_utils.BestRunorlist[trainer_utils.BestRun]]
All the information about the best run or best
runs for multi-objective optimization. Experiment summary can be found in run_summary attribute for Ray
backend.
init_hf_repo[[transformers.Trainer.init_hf_repo]]
Initializes a git repo in self.args.hub_model_id.
is_local_process_zero[[transformers.Trainer.is_local_process_zero]]
Whether or not this process is the local (e.g., on one machine if training in a distributed fashion on several machines) main process.
is_world_process_zero[[transformers.Trainer.is_world_process_zero]]
Whether or not this process is the global main process (when training in a distributed fashion on several
machines, this is only going to be True for one process).
log[[transformers.Trainer.log]]
Log logs on the various objects watching training.
Subclass and override this method to inject custom behavior.
Parameters:
logs (dict[str, float]) : The values to log.
start_time (Optional[float]) : The start of training.
log_metrics[[transformers.Trainer.log_metrics]]
Log metrics in a specially formatted way.
Under distributed environment this is done only for a process with rank 0.
Notes on memory reports:
In order to get memory usage report you need to install psutil. You can do that with pip install psutil.
Now when this method is run, you will see a report that will include:
init_mem_cpu_alloc_delta = 1301MB
init_mem_cpu_peaked_delta = 154MB
init_mem_gpu_alloc_delta = 230MB
init_mem_gpu_peaked_delta = 0MB
train_mem_cpu_alloc_delta = 1345MB
train_mem_cpu_peaked_delta = 0MB
train_mem_gpu_alloc_delta = 693MB
train_mem_gpu_peaked_delta = 7MB
Understanding the reports:
- the first segment, e.g.,
train__, tells you which stage the metrics are for. Reports starting withinit_will be added to the first stage that gets run. So that if only evaluation is run, the memory usage for the__init__will be reported along with theeval_metrics. - the third segment, is either
cpuorgpu, tells you whether it's the general RAM or the gpu0 memory metric. *_alloc_delta- is the difference in the used/allocated memory counter between the end and the start of the stage - it can be negative if a function released more memory than it allocated.*_peaked_delta- is any extra memory that was consumed and then freed - relative to the current allocated memory counter - it is never negative. When you look at the metrics of any stage you add upalloc_delta+peaked_deltaand you know how much memory was needed to complete that stage.
The reporting happens only for process of rank 0 and gpu 0 (if there is a gpu). Typically this is enough since the main process does the bulk of work, but it could be not quite so if model parallel is used and then other GPUs may use a different amount of gpu memory. This is also not the same under DataParallel where gpu0 may require much more memory than the rest since it stores the gradient and optimizer states for all participating GPUs. Perhaps in the future these reports will evolve to measure those too.
The CPU RAM metric measures RSS (Resident Set Size) includes both the memory which is unique to the process and the memory shared with other processes. It is important to note that it does not include swapped out memory, so the reports could be imprecise.
The CPU peak memory is measured using a sampling thread. Due to python's GIL it may miss some of the peak memory if
that thread didn't get a chance to run when the highest memory was used. Therefore this report can be less than
reality. Using tracemalloc would have reported the exact peak memory, but it doesn't report memory allocations
outside of python. So if some C++ CUDA extension allocated its own memory it won't be reported. And therefore it
was dropped in favor of the memory sampling approach, which reads the current process memory usage.
The GPU allocated and peak memory reporting is done with torch.cuda.memory_allocated() and
torch.cuda.max_memory_allocated(). This metric reports only "deltas" for pytorch-specific allocations, as
torch.cuda memory management system doesn't track any memory allocated outside of pytorch. For example, the very
first cuda call typically loads CUDA kernels, which may take from 0.5 to 2GB of GPU memory.
Note that this tracker doesn't account for memory allocations outside of Trainer's __init__, train,
evaluate and predict calls.
Because evaluation calls may happen during train, we can't handle nested invocations because
torch.cuda.max_memory_allocated is a single counter, so if it gets reset by a nested eval call, train's tracker
will report incorrect info. If this pytorch issue gets resolved
it will be possible to change this class to be re-entrant. Until then we will only track the outer level of
train, evaluate and predict methods. Which means that if eval is called during train, it's the latter
that will account for its memory usage and that of the former.
This also means that if any other tool that is used along the Trainer calls
torch.cuda.reset_peak_memory_stats, the gpu peak memory stats could be invalid. And the Trainer will disrupt
the normal behavior of any such tools that rely on calling torch.cuda.reset_peak_memory_stats themselves.
For best performance you may want to consider turning the memory profiling off for production runs.
Parameters:
split (str) : Mode/split name: one of train, eval, test
metrics (dict[str, float]) : The metrics returned from train/evaluate/predictmetrics: metrics dict
metrics_format[[transformers.Trainer.metrics_format]]
Reformat Trainer metrics values to a human-readable format.
Parameters:
metrics (dict[str, float]) : The metrics returned from train/evaluate/predict
Returns:
metrics (dict[str, float])
The reformatted metrics
num_examples[[transformers.Trainer.num_examples]]
Helper to get number of samples in a ~torch.utils.data.DataLoader by accessing its dataset. When
dataloader.dataset does not exist or has no length, estimates as best it can
pop_callback[[transformers.Trainer.pop_callback]]
Remove a callback from the current list of TrainerCallback and returns it.
If the callback is not found, returns None (and no error is raised).
Parameters:
callback (type or [~transformers.TrainerCallback]) : A TrainerCallback class or an instance of a TrainerCallback. In the first case, will pop the first member of that class found in the list of callbacks.
Returns:
[TrainerCallback](/docs/transformers/main/ja/main_classes/callback#transformers.TrainerCallback)
The callback removed, if found.
predict[[transformers.Trainer.predict]]
Run prediction and returns predictions and potential metrics.
Depending on the dataset and your use case, your test dataset may contain labels. In that case, this method
will also return metrics, like in evaluate().
If your predictions or labels have different sequence length (for instance because you're doing dynamic padding in a token classification task) the predictions will be padded (on the right) to allow for concatenation into one array. The padding index is -100.
Returns: NamedTuple A namedtuple with the following keys:
- predictions (
np.ndarray): The predictions ontest_dataset. - label_ids (
np.ndarray, optional): The labels (if the dataset contained some). - metrics (
dict[str, float], optional): The potential dictionary of metrics (if the dataset contained labels).
Parameters:
test_dataset (Dataset) : Dataset to run the predictions on. If it is an datasets.Dataset, columns not accepted by the model.forward() method are automatically removed. Has to implement the method __len__
ignore_keys (list[str], optional) : A list of keys in the output of your model (if it is a dictionary) that should be ignored when gathering predictions.
metric_key_prefix (str, optional, defaults to "test") : An optional prefix to be used as the metrics key prefix. For example the metrics "bleu" will be named "test_bleu" if the prefix is "test" (default)
prediction_step[[transformers.Trainer.prediction_step]]
Perform an evaluation step on model using inputs.
Subclass and override to inject custom behavior.
Parameters:
model (nn.Module) : The model to evaluate.
inputs (dict[str, torch.Tensor | Any]) : The inputs and targets of the model. The dictionary will be unpacked before being fed to the model. Most models expect the targets under the argument labels. Check your model's documentation for all accepted arguments.
prediction_loss_only (bool) : Whether or not to return the loss only.
ignore_keys (list[str], optional) : A list of keys in the output of your model (if it is a dictionary) that should be ignored when gathering predictions.
Returns:
tuple[Optional[torch.Tensor], Optional[torch.Tensor], Optional[torch.Tensor]]
A tuple with the loss, logits and labels (each being optional).
push_to_hub[[transformers.Trainer.push_to_hub]]
Upload self.model and self.processing_class to the 🤗 model hub on the repo self.args.hub_model_id.
Parameters:
commit_message (str, optional, defaults to "End of training") : Message to commit while pushing.
blocking (bool, optional, defaults to True) : Whether the function should return only when the git push has finished.
token (str, optional, defaults to None) : Token with write permission to overwrite Trainer's original args.
revision (str, optional) : The git revision to commit from. Defaults to the head of the "main" branch.
kwargs (dict[str, Any], optional) : Additional keyword arguments passed along to create_model_card().
Returns:
The URL of the repository where the model was pushed if blocking=False, or a Future object tracking the
progress of the commit if blocking=True.
remove_callback[[transformers.Trainer.remove_callback]]
Remove a callback from the current list of TrainerCallback.
Parameters:
callback (type or [~transformers.TrainerCallback]) : A TrainerCallback class or an instance of a TrainerCallback. In the first case, will remove the first member of that class found in the list of callbacks.
save_metrics[[transformers.Trainer.save_metrics]]
Save metrics into a json file for that split, e.g. train_results.json.
Under distributed environment this is done only for a process with rank 0.
To understand the metrics please read the docstring of log_metrics(). The only difference is that raw unformatted numbers are saved in the current method.
Parameters:
split (str) : Mode/split name: one of train, eval, test, all
metrics (dict[str, float]) : The metrics returned from train/evaluate/predict
combined (bool, optional, defaults to True) : Creates combined metrics by updating all_results.json with metrics of this call
save_model[[transformers.Trainer.save_model]]
Will save the model, so you can reload it using from_pretrained().
Will only save from the main process.
save_state[[transformers.Trainer.save_state]]
Saves the Trainer state, since Trainer.save_model saves only the tokenizer with the model.
Under distributed environment this is done only for a process with rank 0.
set_initial_training_values[[transformers.Trainer.set_initial_training_values]]
Calculates and returns the following values:
num_train_epochsnum_update_steps_per_epochnum_examplesnum_train_samplestotal_train_batch_sizesteps_in_epoch(total batches per epoch)max_steps
store_flos[[transformers.Trainer.store_flos]]
Store the number of floating-point operations that went into the model.
train[[transformers.Trainer.train]]
Main training entry point.
Parameters:
resume_from_checkpoint (str or bool, optional) : If a str, local path to a saved checkpoint as saved by a previous instance of Trainer. If a bool and equals True, load the last checkpoint in args.output_dir as saved by a previous instance of Trainer. If present, training will resume from the model/optimizer/scheduler states loaded here.
trial (optuna.Trial or dict[str, Any], optional) : The trial run or the hyperparameter dictionary for hyperparameter search.
ignore_keys_for_eval (list[str], optional) : A list of keys in the output of your model (if it is a dictionary) that should be ignored when gathering predictions for evaluation during the training.
Returns:
TrainOutput
Object containing the global step count, training loss, and metrics.
training_step[[transformers.Trainer.training_step]]
Perform a training step on a batch of inputs.
Subclass and override to inject custom behavior.
Parameters:
model (nn.Module) : The model to train.
inputs (dict[str, torch.Tensor | Any]) : The inputs and targets of the model. The dictionary will be unpacked before being fed to the model. Most models expect the targets under the argument labels. Check your model's documentation for all accepted arguments.
Returns:
torch.Tensor
The tensor with training loss on this batch.
Seq2SeqTrainer[[transformers.Seq2SeqTrainer]]
transformers.Seq2SeqTrainer[[transformers.Seq2SeqTrainer]]
evaluatetransformers.Seq2SeqTrainer.evaluatehttps://github.com/huggingface/transformers/blob/main/src/transformers/trainer_seq2seq.py#L139[{"name": "eval_dataset", "val": ": torch.utils.data.dataset.Dataset | None = None"}, {"name": "ignore_keys", "val": ": list[str] | None = None"}, {"name": "metric_key_prefix", "val": ": str = 'eval'"}, {"name": "**gen_kwargs", "val": ""}]- eval_dataset (Dataset, optional) --
Pass a dataset if you wish to override self.eval_dataset. If it is an Dataset, columns
not accepted by the model.forward() method are automatically removed. It must implement the __len__
method.
- ignore_keys (
list[str], optional) -- A list of keys in the output of your model (if it is a dictionary) that should be ignored when gathering predictions. - metric_key_prefix (
str, optional, defaults to"eval") -- An optional prefix to be used as the metrics key prefix. For example the metrics "bleu" will be named "eval_bleu" if the prefix is"eval"(default) - max_length (
int, optional) -- The maximum target length to use when predicting with the generate method. - num_beams (
int, optional) -- Number of beams for beam search that will be used when predicting with the generate method. 1 means no beam search. - gen_kwargs --
Additional
generatespecific kwargs.0A dictionary containing the evaluation loss and the potential metrics computed from the predictions. The dictionary also contains the epoch number which comes from the training state.
Run evaluation and returns metrics.
The calling script will be responsible for providing a method to compute metrics, as they are task-dependent
(pass it to the init compute_metrics argument).
You can also subclass and override this method to inject custom behavior.
Parameters:
eval_dataset (Dataset, optional) : Pass a dataset if you wish to override self.eval_dataset. If it is an Dataset, columns not accepted by the model.forward() method are automatically removed. It must implement the __len__ method.
ignore_keys (list[str], optional) : A list of keys in the output of your model (if it is a dictionary) that should be ignored when gathering predictions.
metric_key_prefix (str, optional, defaults to "eval") : An optional prefix to be used as the metrics key prefix. For example the metrics "bleu" will be named "eval_bleu" if the prefix is "eval" (default)
max_length (int, optional) : The maximum target length to use when predicting with the generate method.
num_beams (int, optional) : Number of beams for beam search that will be used when predicting with the generate method. 1 means no beam search.
gen_kwargs : Additional generate specific kwargs.
Returns:
A dictionary containing the evaluation loss and the potential metrics computed from the predictions. The dictionary also contains the epoch number which comes from the training state.
predict[[transformers.Seq2SeqTrainer.predict]]
Run prediction and returns predictions and potential metrics.
Depending on the dataset and your use case, your test dataset may contain labels. In that case, this method
will also return metrics, like in evaluate().
If your predictions or labels have different sequence lengths (for instance because you're doing dynamic padding in a token classification task) the predictions will be padded (on the right) to allow for concatenation into one array. The padding index is -100.
Returns: NamedTuple A namedtuple with the following keys:
- predictions (
np.ndarray): The predictions ontest_dataset. - label_ids (
np.ndarray, optional): The labels (if the dataset contained some). - metrics (
dict[str, float], optional): The potential dictionary of metrics (if the dataset contained labels).
Parameters:
test_dataset (Dataset) : Dataset to run the predictions on. If it is a Dataset, columns not accepted by the model.forward() method are automatically removed. Has to implement the method __len__
ignore_keys (list[str], optional) : A list of keys in the output of your model (if it is a dictionary) that should be ignored when gathering predictions.
metric_key_prefix (str, optional, defaults to "eval") : An optional prefix to be used as the metrics key prefix. For example the metrics "bleu" will be named "eval_bleu" if the prefix is "eval" (default)
max_length (int, optional) : The maximum target length to use when predicting with the generate method.
num_beams (int, optional) : Number of beams for beam search that will be used when predicting with the generate method. 1 means no beam search.
gen_kwargs : Additional generate specific kwargs.
TrainingArguments[[transformers.TrainingArguments]]
transformers.TrainingArguments[[transformers.TrainingArguments]]
Configuration class for controlling all aspects of model training with the Trainer. TrainingArguments centralizes all hyperparameters, optimization settings, logging preferences, and infrastructure choices needed for training.
HfArgumentParser can turn this class into argparse arguments that can be specified on the command line.
get_process_log_leveltransformers.TrainingArguments.get_process_log_levelhttps://github.com/huggingface/transformers/blob/main/src/transformers/training_args.py#L1995[]
Returns the log level to be used depending on whether this process is the main process of node 0, main process of node non-0, or a non-main process.
For the main process the log level defaults to the logging level set (logging.WARNING if you didn't do
anything) unless overridden by log_level argument.
For the replica processes the log level defaults to logging.WARNING unless overridden by log_level_replica
argument.
The choice between the main and replica process settings is made according to the return value of should_log.
Parameters:
output_dir (str, optional, defaults to "trainer_output") : The output directory where the model predictions and checkpoints will be written.
get_warmup_steps[[transformers.TrainingArguments.get_warmup_steps]]
Get number of steps used for a linear warmup.
main_process_first[[transformers.TrainingArguments.main_process_first]]
A context manager for torch distributed environment where on needs to do something on the main process, while blocking replicas, and when it's finished releasing the replicas.
One such use is for datasets's map feature which to be efficient should be run once on the main process,
which upon completion saves a cached version of results and which then automatically gets loaded by the
replicas.
Parameters:
local (bool, optional, defaults to True) : if True first means process of rank 0 of each node if False first means process of rank 0 of node rank 0 In multi-node environment with a shared filesystem you most likely will want to use local=False so that only the main process of the first node will do the processing. If however, the filesystem is not shared, then the main process of each node will need to do the processing, which is the default behavior.
desc (str, optional, defaults to "work") : a work description to be used in debug logs
set_dataloader[[transformers.TrainingArguments.set_dataloader]]
A method that regroups all arguments linked to the dataloaders creation.
Example:
>>> from transformers import TrainingArguments
>>> args = TrainingArguments("working_dir")
>>> args = args.set_dataloader(train_batch_size=16, eval_batch_size=64)
>>> args.per_device_train_batch_size
16
Parameters:
drop_last (bool, optional, defaults to False) : Whether to drop the last incomplete batch (if the length of the dataset is not divisible by the batch size) or not.
num_workers (int, optional, defaults to 0) : Number of subprocesses to use for data loading (PyTorch only). 0 means that the data will be loaded in the main process.
pin_memory (bool, optional, defaults to True) : Whether you want to pin memory in data loaders or not. Will default to True.
persistent_workers (bool, optional, defaults to False) : If True, the data loader will not shut down the worker processes after a dataset has been consumed once. This allows to maintain the workers Dataset instances alive. Can potentially speed up training, but will increase RAM usage. Will default to False.
prefetch_factor (int, optional) : Number of batches loaded in advance by each worker. 2 means there will be a total of 2 * num_workers batches prefetched across all workers.
auto_find_batch_size (bool, optional, defaults to False) : Whether to find a batch size that will fit into memory automatically through exponential decay, avoiding CUDA Out-of-Memory errors. Requires accelerate to be installed (pip install accelerate)
ignore_data_skip (bool, optional, defaults to False) : When resuming training, whether or not to skip the epochs and batches to get the data loading at the same stage as in the previous training. If set to True, the training will begin faster (as that skipping step can take a long time) but will not yield the same results as the interrupted training would have.
sampler_seed (int, optional) : Random seed to be used with data samplers. If not set, random generators for data sampling will use the same seed as self.seed. This can be used to ensure reproducibility of data sampling, independent of the model seed.
set_evaluate[[transformers.TrainingArguments.set_evaluate]]
A method that regroups all arguments linked to evaluation.
Example:
>>> from transformers import TrainingArguments
>>> args = TrainingArguments("working_dir")
>>> args = args.set_evaluate(strategy="steps", steps=100)
>>> args.eval_steps
100
Parameters:
strategy (str or IntervalStrategy, optional, defaults to "no") : The evaluation strategy to adopt during training. Possible values are: - "no": No evaluation is done during training. - "steps": Evaluation is done (and logged) every steps. - "epoch": Evaluation is done at the end of each epoch. Setting a strategy different from "no" will set self.do_eval to True.
steps (int, optional, defaults to 500) : Number of update steps between two evaluations if strategy="steps".
batch_size (int optional, defaults to 8) : The batch size per device (GPU/TPU core/CPU...) used for evaluation.
accumulation_steps (int, optional) : Number of predictions steps to accumulate the output tensors for, before moving the results to the CPU. If left unset, the whole predictions are accumulated on GPU/TPU before being moved to the CPU (faster but requires more memory).
delay (float, optional) : Number of epochs or steps to wait for before the first evaluation can be performed, depending on the eval_strategy.
loss_only (bool, optional, defaults to False) : Ignores all outputs except the loss.
set_logging[[transformers.TrainingArguments.set_logging]]
A method that regroups all arguments linked to logging.
Example:
>>> from transformers import TrainingArguments
>>> args = TrainingArguments("working_dir")
>>> args = args.set_logging(strategy="steps", steps=100)
>>> args.logging_steps
100
Parameters:
strategy (str or IntervalStrategy, optional, defaults to "steps") : The logging strategy to adopt during training. Possible values are: - "no": No logging is done during training. - "epoch": Logging is done at the end of each epoch. - "steps": Logging is done every logging_steps.
steps (int, optional, defaults to 500) : Number of update steps between two logs if strategy="steps".
level (str, optional, defaults to "passive") : Logger log level to use on the main process. Possible choices are the log levels as strings: "debug", "info", "warning", "error" and "critical", plus a "passive" level which doesn't set anything and lets the application set the level.
report_to (str or list[str], optional, defaults to "none") : The list of integrations to report the results and logs to. Supported platforms are "azure_ml", "clearml", "codecarbon", "comet_ml", "dagshub", "dvclive", "flyte", "mlflow", "swanlab", "tensorboard", "trackio" and "wandb". Use "all" to report to all integrations installed, "none" for no integrations.
first_step (bool, optional, defaults to False) : Whether to log and evaluate the first global_step or not.
nan_inf_filter (bool, optional, defaults to True) : Whether to filter nan and inf losses for logging. If set to True the loss of every step that is nan or inf is filtered and the average loss of the current logging window is taken instead. nan_inf_filter only influences the logging of loss values, it does not change the behavior the gradient is computed or applied to the model.
on_each_node (bool, optional, defaults to True) : In multinode distributed training, whether to log using log_level once per node, or only on the main node.
replica_level (str, optional, defaults to "passive") : Logger log level to use on replicas. Same choices as log_level
set_lr_scheduler[[transformers.TrainingArguments.set_lr_scheduler]]
A method that regroups all arguments linked to the learning rate scheduler and its hyperparameters.
Example:
>>> from transformers import TrainingArguments
>>> args = TrainingArguments("working_dir")
>>> args = args.set_lr_scheduler(name="cosine", warmup_steps=0.05)
>>> args.warmup_steps
0.05
Parameters:
name (str or SchedulerType, optional, defaults to "linear") : The scheduler type to use. See the documentation of SchedulerType for all possible values.
num_epochs(float, optional, defaults to 3.0) : Total number of training epochs to perform (if not an integer, will perform the decimal part percents of the last epoch before stopping training).
max_steps (int, optional, defaults to -1) : If set to a positive number, the total number of training steps to perform. Overrides num_train_epochs. For a finite dataset, training is reiterated through the dataset (if all data is exhausted) until max_steps is reached.
warmup_steps (float, optional, defaults to 0) : Number of steps used for a linear warmup from 0 to learning_rate. Should be an integer or a float in range [0,1). If smaller than 1, will be interpreted as ratio of steps used for a linear warmup from 0 to learning_rate.
set_optimizer[[transformers.TrainingArguments.set_optimizer]]
A method that regroups all arguments linked to the optimizer and its hyperparameters.
Example:
>>> from transformers import TrainingArguments
>>> args = TrainingArguments("working_dir")
>>> args = args.set_optimizer(name="adamw_torch", beta1=0.8)
>>> args.optim
'adamw_torch'
Parameters:
name (str or training_args.OptimizerNames, optional, defaults to "adamw_torch") : The optimizer to use: "adamw_torch", "adamw_torch_fused", "adamw_anyprecision" or "adafactor".
learning_rate (float, optional, defaults to 5e-5) : The initial learning rate.
weight_decay (float, optional, defaults to 0) : The weight decay to apply (if not zero) to all layers except all bias and LayerNorm weights.
beta1 (float, optional, defaults to 0.9) : The beta1 hyperparameter for the adam optimizer or its variants.
beta2 (float, optional, defaults to 0.999) : The beta2 hyperparameter for the adam optimizer or its variants.
epsilon (float, optional, defaults to 1e-8) : The epsilon hyperparameter for the adam optimizer or its variants.
args (str, optional) : Optional arguments that are supplied to AnyPrecisionAdamW (only useful when optim="adamw_anyprecision").
set_push_to_hub[[transformers.TrainingArguments.set_push_to_hub]]
A method that regroups all arguments linked to synchronizing checkpoints with the Hub.
Calling this method will set self.push_to_hub to True, which means the output_dir will begin a git
directory synced with the repo (determined by model_id) and the content will be pushed each time a save is
triggered (depending on your self.save_strategy). Calling save_model() will also trigger a push.
Example:
>>> from transformers import TrainingArguments
>>> args = TrainingArguments("working_dir")
>>> args = args.set_push_to_hub("me/awesome-model")
>>> args.hub_model_id
'me/awesome-model'
Parameters:
model_id (str) : The name of the repository to keep in sync with the local output_dir. It can be a simple model ID in which case the model will be pushed in your namespace. Otherwise it should be the whole repository name, for instance "user_name/model", which allows you to push to an organization you are a member of with "organization_name/model".
strategy (str or HubStrategy, optional, defaults to "every_save") : Defines the scope of what is pushed to the Hub and when. Possible values are: - "end": push the model, its configuration, the processing_class e.g. tokenizer (if passed along to the Trainer) and a draft of a model card when the save_model() method is called. - "every_save": push the model, its configuration, the processing_class e.g. tokenizer (if passed along to the Trainer) and a draft of a model card each time there is a model save. The pushes are asynchronous to not block training, and in case the save are very frequent, a new push is only attempted if the previous one is finished. A last push is made with the final model at the end of training. - "checkpoint": like "every_save" but the latest checkpoint is also pushed in a subfolder named last-checkpoint, allowing you to resume training easily with trainer.train(resume_from_checkpoint="last-checkpoint"). - "all_checkpoints": like "checkpoint" but all checkpoints are pushed like they appear in the output folder (so you will get one checkpoint folder per folder in your final repository)
token (str, optional) : The token to use to push the model to the Hub. Will default to the token in the cache folder obtained with hf auth login.
private_repo (bool, optional, defaults to False) : Whether to make the repo private. If None (default), the repo will be public unless the organization's default is private. This value is ignored if the repo already exists.
always_push (bool, optional, defaults to False) : Unless this is True, the Trainer will skip pushing a checkpoint when the previous push is not finished.
revision (str, optional) : The revision to use when pushing to the Hub. Can be a branch name, a tag, or a commit hash.
set_save[[transformers.TrainingArguments.set_save]]
A method that regroups all arguments linked to checkpoint saving.
Example:
>>> from transformers import TrainingArguments
>>> args = TrainingArguments("working_dir")
>>> args = args.set_save(strategy="steps", steps=100)
>>> args.save_steps
100
Parameters:
strategy (str or IntervalStrategy, optional, defaults to "steps") : The checkpoint save strategy to adopt during training. Possible values are: - "no": No save is done during training. - "epoch": Save is done at the end of each epoch. - "steps": Save is done every save_steps.
steps (int, optional, defaults to 500) : Number of updates steps before two checkpoint saves if strategy="steps".
total_limit (int, optional) : If a value is passed, will limit the total amount of checkpoints. Deletes the older checkpoints in output_dir.
on_each_node (bool, optional, defaults to False) : When doing multi-node distributed training, whether to save models and checkpoints on each node, or only on the main one. This should not be activated when the different nodes use the same storage as the files will be saved with the same names for each node.
set_testing[[transformers.TrainingArguments.set_testing]]
A method that regroups all basic arguments linked to testing on a held-out dataset.
Calling this method will automatically set self.do_predict to True.
Example:
>>> from transformers import TrainingArguments
>>> args = TrainingArguments("working_dir")
>>> args = args.set_testing(batch_size=32)
>>> args.per_device_eval_batch_size
32
Parameters:
batch_size (int optional, defaults to 8) : The batch size per device (GPU/TPU core/CPU...) used for testing.
loss_only (bool, optional, defaults to False) : Ignores all outputs except the loss.
set_training[[transformers.TrainingArguments.set_training]]
A method that regroups all basic arguments linked to the training.
Calling this method will automatically set self.do_train to True.
Example:
>>> from transformers import TrainingArguments
>>> args = TrainingArguments("working_dir")
>>> args = args.set_training(learning_rate=1e-4, batch_size=32)
>>> args.learning_rate
1e-4
Parameters:
learning_rate (float, optional, defaults to 5e-5) : The initial learning rate for the optimizer.
batch_size (int optional, defaults to 8) : The batch size per device (GPU/TPU core/CPU...) used for training.
weight_decay (float, optional, defaults to 0) : The weight decay to apply (if not zero) to all layers except all bias and LayerNorm weights in the optimizer.
num_train_epochs(float, optional, defaults to 3.0) : Total number of training epochs to perform (if not an integer, will perform the decimal part percents of the last epoch before stopping training).
max_steps (int, optional, defaults to -1) : If set to a positive number, the total number of training steps to perform. Overrides num_train_epochs. For a finite dataset, training is reiterated through the dataset (if all data is exhausted) until max_steps is reached.
gradient_accumulation_steps (int, optional, defaults to 1) : Number of updates steps to accumulate the gradients for, before performing a backward/update pass. When using gradient accumulation, one step is counted as one step with backward pass. Therefore, logging, evaluation, save will be conducted every gradient_accumulation_steps * xxx_step training examples.
seed (int, optional, defaults to 42) : Random seed that will be set at the beginning of training. To ensure reproducibility across runs, use the ~Trainer.model_init function to instantiate the model if it has some randomly initialized parameters.
gradient_checkpointing (bool, optional, defaults to False) : If True, use gradient checkpointing to save memory at the expense of slower backward pass.
to_dict[[transformers.TrainingArguments.to_dict]]
Serializes this instance while replace Enum by their values (for JSON serialization support). It obfuscates
the token values by removing their value.
to_json_string[[transformers.TrainingArguments.to_json_string]]
Serializes this instance to a JSON string.
to_sanitized_dict[[transformers.TrainingArguments.to_sanitized_dict]]
Sanitized serialization to use with TensorBoard's hparams
Seq2SeqTrainingArguments[[transformers.Seq2SeqTrainingArguments]]
transformers.Seq2SeqTrainingArguments[[transformers.Seq2SeqTrainingArguments]]
Configuration class for controlling all aspects of model training with the Trainer. TrainingArguments centralizes all hyperparameters, optimization settings, logging preferences, and infrastructure choices needed for training.
HfArgumentParser can turn this class into argparse arguments that can be specified on the command line.
to_dicttransformers.Seq2SeqTrainingArguments.to_dicthttps://github.com/huggingface/transformers/blob/main/src/transformers/training_args_seq2seq.py#L84[]
Serializes this instance while replace Enum by their values and GenerationConfig by dictionaries (for JSON
serialization support). It obfuscates the token values by removing their value.
Parameters:
output_dir (str, optional, defaults to "trainer_output") : The output directory where the model predictions and checkpoints will be written.
Checkpoints
デフォルトでは、Trainer はすべてのチェックポイントを、
TrainingArguments を使用しています。これらは、xxx を含むcheckpoint-xxxという名前のサブフォルダーに保存されます。
それはトレーニングの段階でした。
チェックポイントからトレーニングを再開するには、次のいずれかを使用して Trainer.train() を呼び出します。
resume_from_checkpoint=Trueは最新のチェックポイントからトレーニングを再開しますresume_from_checkpoint=checkpoint_dirディレクトリ内の特定のチェックポイントからトレーニングを再開します 合格した。
さらに、push_to_hub=True を使用すると、モデル ハブにチェックポイントを簡単に保存できます。デフォルトでは、すべて
中間チェックポイントに保存されたモデルは別のコミットに保存されますが、オプティマイザーの状態は保存されません。適応できます
TrainingArguments の hub-strategy 値を次のいずれかにします。
"checkpoint": 最新のチェックポイントも last-checkpoint という名前のサブフォルダーにプッシュされます。trainer.train(resume_from_checkpoint="output_dir/last-checkpoint")を使用してトレーニングを簡単に再開します。"all_checkpoints": すべてのチェックポイントは、出力フォルダーに表示されるようにプッシュされます (したがって、1 つのチェックポイントが得られます) 最終リポジトリ内のフォルダーごとのチェックポイント フォルダー)
Logging
デフォルトでは、Trainer はメインプロセスに logging.INFO を使用し、レプリカがある場合には logging.WARNING を使用します。
これらのデフォルトは、TrainingArguments の 5 つの logging レベルのいずれかを使用するようにオーバーライドできます。
引数:
log_level- メインプロセス用log_level_replica- レプリカ用
さらに、TrainingArguments の log_on_each_node が False に設定されている場合、メイン ノードのみが
メイン プロセスのログ レベル設定を使用すると、他のすべてのノードはレプリカのログ レベル設定を使用します。
Trainer は、transformers のログ レベルをノードごとに個別に設定することに注意してください。
Trainer.__init__()。したがって、他の機能を利用する場合は、これをより早く設定することをお勧めします (次の例を参照)。
Trainer オブジェクトを作成する前の transformers 機能。
これをアプリケーションで使用する方法の例を次に示します。
[...]
logger = logging.getLogger(__name__)
# Setup logging
logging.basicConfig(
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
datefmt="%m/%d/%Y %H:%M:%S",
handlers=[logging.StreamHandler(sys.stdout)],
)
# set the main code and the modules it uses to the same log-level according to the node
log_level = training_args.get_process_log_level()
logger.setLevel(log_level)
datasets.utils.logging.set_verbosity(log_level)
transformers.utils.logging.set_verbosity(log_level)
trainer = Trainer(...)
そして、メイン ノードと他のすべてのノードで重複する可能性が高いものを出力しないように警告するだけを表示したい場合は、 警告: 次のように実行できます。
my_app.py ... --log_level warning --log_level_replica error
マルチノード環境で、各ノードのメインプロセスのログを繰り返したくない場合は、次のようにします。 上記を次のように変更します。
my_app.py ... --log_level warning --log_level_replica error --log_on_each_node 0
その後、最初のノードのメイン プロセスのみが「警告」レベルでログに記録され、メイン ノード上の他のすべてのプロセスはログに記録されます。 ノードと他のノード上のすべてのプロセスは「エラー」レベルでログに記録されます。
アプリケーションをできるだけ静かにする必要がある場合は、次のようにします。
my_app.py ... --log_level error --log_level_replica error --log_on_each_node 0
(マルチノード環境の場合は --log_on_each_node 0 を追加します)
Randomness
Trainer によって生成されたチェックポイントから再開する場合、すべての努力がその状態を復元するために行われます。 _python_、_numpy_、および pytorch の RNG 状態は、そのチェックポイントを保存した時点と同じ状態になります。 これにより、「停止して再開」というスタイルのトレーニングが、ノンストップトレーニングに可能な限り近づけられるはずです。
ただし、さまざまなデフォルトの非決定的な pytorch 設定により、これは完全に機能しない可能性があります。フルをご希望の場合は
決定論については、ランダム性のソースの制御 を参照してください。ドキュメントで説明されているように、これらの設定の一部は
物事を決定論的にするもの (例: torch.backends.cudnn.deterministic) は物事を遅くする可能性があるため、これは
デフォルトでは実行できませんが、必要に応じて自分で有効にすることができます。
Specific GPUs Selection
どの GPU をどのような順序で使用するかをプログラムに指示する方法について説明します。
DistributedDataParallel を使用して GPU のサブセットのみを使用する場合、使用する GPU の数を指定するだけです。 。たとえば、GPU が 4 つあるが、最初の 2 つを使用したい場合は、次のようにします。
torchrun --nproc_per_node=2 trainer-program.py ...
accelerate または deepspeed がインストールされている場合は、次を使用して同じことを達成することもできます。の一つ:
accelerate launch --num_processes 2 trainer-program.py ...
deepspeed --num_gpus 2 trainer-program.py ...
これらのランチャーを使用するために、Accelerate または Deepspeed 統合 機能を使用する必要はありません。
これまでは、プログラムに使用する GPU の数を指示できました。次に、特定の GPU を選択し、その順序を制御する方法について説明します。
次の環境変数は、使用する GPU とその順序を制御するのに役立ちます。
CUDA_VISIBLE_DEVICES
複数の GPU があり、そのうちの 1 つまたはいくつかの GPU だけを使用したい場合は、環境変数 CUDA_VISIBLE_DEVICES を使用する GPU のリストに設定します。
たとえば、4 つの GPU (0、1、2、3) があるとします。物理 GPU 0 と 2 のみで実行するには、次のようにします。
CUDA_VISIBLE_DEVICES=0,2 torchrun trainer-program.py ...
したがって、pytorch は 2 つの GPU のみを認識し、物理 GPU 0 と 2 はそれぞれ cuda:0 と cuda:1 にマッピングされます。
順序を変更することもできます。
CUDA_VISIBLE_DEVICES=2,0 torchrun trainer-program.py ...
ここでは、物理 GPU 0 と 2 がそれぞれcuda:1とcuda:0にマッピングされています。
上記の例はすべて DistributedDataParallel 使用パターンのものですが、同じ方法が DataParallel でも機能します。
CUDA_VISIBLE_DEVICES=2,0 python trainer-program.py ...
GPU のない環境をエミュレートするには、次のようにこの環境変数を空の値に設定するだけです。
CUDA_VISIBLE_DEVICES= python trainer-program.py ...
他の環境変数と同様に、これらをコマンド ラインに追加する代わりに、次のようにエクスポートすることもできます。
export CUDA_VISIBLE_DEVICES=0,2
torchrun trainer-program.py ...
ただし、この方法では、以前に環境変数を設定したことを忘れて、なぜ間違った GPU が使用されているのか理解できない可能性があるため、混乱を招く可能性があります。したがって、このセクションのほとんどの例で示されているように、同じコマンド ラインで特定の実行に対してのみ環境変数を設定するのが一般的です。
CUDA_DEVICE_ORDER
物理デバイスの順序を制御する追加の環境変数 CUDA_DEVICE_ORDER があります。選択肢は次の 2 つです。
- PCIe バス ID 順 (
nvidia-smiの順序と一致) - これがデフォルトです。
export CUDA_DEVICE_ORDER=PCI_BUS_ID
- GPU コンピューティング能力順に並べる
export CUDA_DEVICE_ORDER=FASTEST_FIRST
ほとんどの場合、この環境変数を気にする必要はありませんが、古い GPU と新しい GPU が物理的に挿入されているため、遅い古いカードが遅くなっているように見えるような偏ったセットアップを行っている場合には、非常に役立ちます。初め。これを解決する 1 つの方法は、カードを交換することです。ただし、カードを交換できない場合 (デバイスの冷却が影響を受けた場合など)、CUDA_DEVICE_ORDER=FASTEST_FIRSTを設定すると、常に新しい高速カードが最初に配置されます。ただし、nvidia-smiは依然として PCIe の順序でレポートするため、多少混乱するでしょう。
順序を入れ替えるもう 1 つの解決策は、以下を使用することです。
export CUDA_VISIBLE_DEVICES=1,0
この例では 2 つの GPU だけを使用していますが、もちろん、コンピューターに搭載されている数の GPU にも同じことが当てはまります。
また、この環境変数を設定する場合は、~/.bashrc ファイルまたはその他の起動設定ファイルに設定して、忘れるのが最善です。
Trainer Integrations
Trainer は、トレーニングを劇的に改善する可能性のあるライブラリをサポートするように拡張されました。 時間とはるかに大きなモデルに適合します。
現在、サードパーティのソリューション DeepSpeed および PyTorch FSDP をサポートしています。論文 ZeRO: メモリの最適化兆パラメータ モデルのトレーニングに向けて、Samyam Rajbhandari、Jeff Rasley、Olatunji Ruwase、Yuxiong He 著。
この提供されるサポートは、この記事の執筆時点では新しくて実験的なものです。 DeepSpeed と PyTorch FSDP のサポートはアクティブであり、それに関する問題は歓迎しますが、FairScale 統合は PyTorch メインに統合されているため、もうサポートしていません (PyTorch FSDP 統合)
CUDA Extension Installation Notes
この記事の執筆時点では、Deepspeed を使用するには、CUDA C++ コードをコンパイルする必要があります。
すべてのインストールの問題は、Deepspeed の対応する GitHub の問題を通じて対処する必要がありますが、ビルド中に発生する可能性のある一般的な問題がいくつかあります。 CUDA 拡張機能を構築する必要がある PyTorch 拡張機能。
したがって、次の操作を実行中に CUDA 関連のビルドの問題が発生した場合は、次のとおりです。
pip install deepspeed
まず次の注意事項をお読みください。
これらのノートでは、pytorch が CUDA 10.2 でビルドされた場合に何をすべきかの例を示します。あなたの状況が次のような場合
異なる場合は、バージョン番号を目的のバージョンに調整することを忘れないでください。
Possible problem #1
Pytorch には独自の CUDA ツールキットが付属していますが、これら 2 つのプロジェクトをビルドするには、同一バージョンの CUDA が必要です。 システム全体にインストールされます。
たとえば、Python 環境に cudatoolkit==10.2 を指定して pytorch をインストールした場合は、次のものも必要です。
CUDA 10.2 がシステム全体にインストールされました。
正確な場所はシステムによって異なる場合がありますが、多くのシステムでは/usr/local/cuda-10.2が最も一般的な場所です。
Unix システム。 CUDA が正しく設定され、PATH環境変数に追加されると、
次のようにしてインストール場所を指定します。
which nvcc
CUDA がシステム全体にインストールされていない場合は、最初にインストールしてください。お気に入りを使用して手順を見つけることができます 検索エンジン。たとえば、Ubuntu を使用している場合は、ubuntu cuda 10.2 install を検索するとよいでしょう。
Possible problem #2
もう 1 つの考えられる一般的な問題は、システム全体に複数の CUDA ツールキットがインストールされている可能性があることです。たとえばあなた がある可能性があり:
/usr/local/cuda-10.2
/usr/local/cuda-11.0
この状況では、PATH および LD_LIBRARY_PATH 環境変数に以下が含まれていることを確認する必要があります。
目的の CUDA バージョンへの正しいパス。通常、パッケージ インストーラーは、これらに、
最後のバージョンがインストールされました。適切なパッケージが見つからないためにパッケージのビルドが失敗するという問題が発生した場合は、
CUDA バージョンがシステム全体にインストールされているにもかかわらず、前述の 2 つを調整する必要があることを意味します
環境変数。
まず、その内容を見てみましょう。
echo $PATH
echo $LD_LIBRARY_PATH
それで、中に何が入っているかがわかります。
LD_LIBRARY_PATH が空である可能性があります。
PATH は実行可能ファイルが存在する場所をリストし、LD_LIBRARY_PATH は共有ライブラリの場所を示します。
探すことです。どちらの場合も、前のエントリが後のエントリより優先されます。 : は複数を区切るために使用されます
エントリ。
ここで、ビルド プログラムに特定の CUDA ツールキットの場所を指示するには、最初にリストされる希望のパスを挿入します。 やっていること:
export PATH=/usr/local/cuda-10.2/bin:$PATH
export LD_LIBRARY_PATH=/usr/local/cuda-10.2/lib64:$LD_LIBRARY_PATH
既存の値を上書きするのではなく、先頭に追加することに注意してください。
もちろん、必要に応じてバージョン番号やフルパスを調整します。割り当てたディレクトリが実際に機能することを確認してください
存在する。 lib64 サブディレクトリは、libcudart.so などのさまざまな CUDA .so オブジェクトが存在する場所です。
システムでは別の名前が付けられますが、現実を反映するように調整してください。
Possible problem #3
一部の古い CUDA バージョンは、新しいコンパイラでのビルドを拒否する場合があります。たとえば、あなたはgcc-9を持っていますが、それが必要です
gcc-7。
それにはさまざまな方法があります。
最新の CUDA ツールキットをインストールできる場合は、通常、新しいコンパイラがサポートされているはずです。
あるいは、既に所有しているコンパイラに加えて、下位バージョンのコンパイラをインストールすることもできます。 すでに存在しますが、デフォルトではないため、ビルドシステムはそれを認識できません。 「gcc-7」がインストールされているが、 ビルドシステムが見つからないというメッセージを表示する場合は、次の方法で解決できる可能性があります。
sudo ln -s /usr/bin/gcc-7 /usr/local/cuda-10.2/bin/gcc
sudo ln -s /usr/bin/g++-7 /usr/local/cuda-10.2/bin/g++
ここでは、/usr/local/cuda-10.2/bin/gcc から gcc-7 へのシンボリックリンクを作成しています。
/usr/local/cuda-10.2/bin/ は PATH 環境変数内にある必要があります (前の問題の解決策を参照)。
gcc-7 (および g++7) が見つかるはずで、ビルドは成功します。
いつものように、状況に合わせて例のパスを編集してください。
PyTorch Fully Sharded Data parallel
より大きなバッチ サイズで巨大なモデルのトレーニングを高速化するには、完全にシャード化されたデータ並列モデルを使用できます。 このタイプのデータ並列パラダイムでは、オプティマイザーの状態、勾配、パラメーターをシャーディングすることで、より多くのデータと大規模なモデルをフィッティングできます。 この機能とその利点の詳細については、完全シャーディング データ並列ブログ をご覧ください。 最新の PyTorch の Fully Sharded Data Parallel (FSDP) トレーニング機能を統合しました。 必要なのは、設定を通じて有効にすることだけです。
FSDP サポートに必要な PyTorch バージョン: PyTorch Nightly (リリース後にこれを読んだ場合は 1.12.0) FSDP を有効にしたモデルの保存は、最近の修正でのみ利用できるためです。
使用法:
配布されたランチャーが追加されていることを確認してください まだ使用していない場合は、
-m torch.distributed.launch --nproc_per_node=NUMBER_OF_GPUS_YOU_HAVEを使用します。シャーディング戦略:
- FULL_SHARD : データ並列ワーカー/GPU にわたるシャード オプティマイザーの状態 + 勾配 + モデル パラメーター。
このためには、コマンドライン引数に
--fsdp full_shardを追加します。 - SHARD_GRAD_OP : シャード オプティマイザーの状態 + データ並列ワーカー/GPU 全体の勾配。
このためには、コマンドライン引数に
--fsdp shard_grad_opを追加します。 - NO_SHARD : シャーディングなし。このためには、コマンドライン引数に
--fsdp no_shardを追加します。
- FULL_SHARD : データ並列ワーカー/GPU にわたるシャード オプティマイザーの状態 + 勾配 + モデル パラメーター。
このためには、コマンドライン引数に
パラメータと勾配を CPU にオフロードするには、 コマンドライン引数に
--fsdp "full_shard offload"または--fsdp "shard_grad_op offload"を追加します。default_auto_wrap_policyを使用して FSDP でレイヤーを自動的に再帰的にラップするには、 コマンドライン引数に--fsdp "full_shard auto_wrap"または--fsdp "shard_grad_op auto_wrap"を追加します。CPU オフロードと自動ラッピングの両方を有効にするには、 コマンドライン引数に
--fsdp "full_shard offload auto_wrap"または--fsdp "shard_grad_op offload auto_wrap"を追加します。残りの FSDP 構成は、
--fsdp_config <path_to_fsdp_config.json>を介して渡されます。それは、次のいずれかの場所です。 FSDP json 構成ファイル (例:fsdp_config.json)、またはすでにロードされている json ファイルをdictとして使用します。- 自動ラッピングが有効な場合は、トランスベースの自動ラップ ポリシーまたはサイズ ベースの自動ラップ ポリシーを使用できます。
- トランスフォーマーベースの自動ラップポリシーの場合、構成ファイルで
fsdp_transformer_layer_cls_to_wrapを指定することをお勧めします。指定しない場合、使用可能な場合、デフォルト値はmodel._no_split_modulesになります。 これは、ラップするトランスフォーマー層クラス名のリスト (大文字と小文字を区別) を指定します (例:BertLayer、GPTJBlock、T5Block...)。 重みを共有するサブモジュール (埋め込み層など) が異なる FSDP ラップされたユニットにならないようにする必要があるため、これは重要です。 このポリシーを使用すると、マルチヘッド アテンションとそれに続くいくつかの MLP レイヤーを含むブロックごとにラッピングが発生します。 共有埋め込みを含む残りの層は、同じ最も外側の FSDP ユニットにラップされるのが便利です。 したがって、トランスベースのモデルにはこれを使用してください。 - サイズベースの自動ラップポリシーの場合は、設定ファイルに
fsdp_min_num_paramsを追加してください。 自動ラッピングのための FSDP のパラメータの最小数を指定します。
- トランスフォーマーベースの自動ラップポリシーの場合、構成ファイルで
- 設定ファイルで
fsdp_backward_prefetchを指定できるようになりました。次のパラメータのセットをいつプリフェッチするかを制御します。backward_preとbackward_posが利用可能なオプションです。 詳細については、torch.distributed.fsdp.full_sharded_data_Parallel.BackwardPrefetchを参照してください。 - 設定ファイルで
fsdp_forward_prefetchを指定できるようになりました。次のパラメータのセットをいつプリフェッチするかを制御します。Trueの場合、FSDP はフォワード パスでの実行中に、次に来るオールギャザーを明示的にプリフェッチします。 - 設定ファイルで
limit_all_gathersを指定できるようになりました。Trueの場合、FSDP は CPU スレッドを明示的に同期して、実行中のオールギャザが多すぎるのを防ぎます。 activation_checkpointingを設定ファイルで指定できるようになりました。Trueの場合、FSDP アクティベーション チェックポイントは、FSDP のアクティベーションをクリアすることでメモリ使用量を削減する手法です。 特定のレイヤーを処理し、バックワード パス中にそれらを再計算します。事実上、これは余分な計算時間を犠牲にします メモリ使用量を削減します。
- 自動ラッピングが有効な場合は、トランスベースの自動ラップ ポリシーまたはサイズ ベースの自動ラップ ポリシーを使用できます。
注意すべき注意点がいくつかあります
- これは
generateと互換性がないため、--predict_with_generateとも互換性がありません すべての seq2seq/clm スクリプト (翻訳/要約/clm など)。 問題 #21667 を参照してください。
PyTorch/XLA Fully Sharded Data parallel
TPU ユーザーの皆様に朗報です。 PyTorch/XLA は FSDP をサポートするようになりました。 最新の Fully Sharded Data Parallel (FSDP) トレーニングがすべてサポートされています。 詳細については、FSDP を使用した Cloud TPU での PyTorch モデルのスケーリング および PyTorch/XLA 実装 を参照してください。 FSDP の 必要なのは、設定を通じて有効にすることだけです。
FSDP サポートに必要な PyTorch/XLA バージョン: >=2.0
使用法:
--fsdp "full shard" を、--fsdp_config <path_to_fsdp_config.json> に加えられる次の変更とともに渡します。
- PyTorch/XLA FSDP を有効にするには、
xlaをTrueに設定する必要があります。 xla_fsdp_settings値は、XLA FSDP ラッピング パラメータを格納する辞書です。 オプションの完全なリストについては、こちら。xla_fsdp_grad_ckpt。Trueの場合、ネストされた XLA FSDP でラップされた各レイヤー上で勾配チェックポイントを使用します。 この設定は、xla フラグが true に設定されており、自動ラッピング ポリシーが指定されている場合にのみ使用できます。fsdp_min_num_paramsまたはfsdp_transformer_layer_cls_to_wrap。- トランスフォーマー ベースの自動ラップ ポリシーまたはサイズ ベースの自動ラップ ポリシーのいずれかを使用できます。
- トランスフォーマーベースの自動ラップポリシーの場合、構成ファイルで
fsdp_transformer_layer_cls_to_wrapを指定することをお勧めします。指定しない場合、使用可能な場合、デフォルト値はmodel._no_split_modulesになります。 これは、ラップするトランスフォーマー層クラス名のリスト (大文字と小文字を区別) を指定します (例:BertLayer、GPTJBlock、T5Block...)。 重みを共有するサブモジュール (埋め込み層など) が異なる FSDP ラップされたユニットにならないようにする必要があるため、これは重要です。 このポリシーを使用すると、マルチヘッド アテンションとそれに続くいくつかの MLP レイヤーを含むブロックごとにラッピングが発生します。 共有埋め込みを含む残りの層は、同じ最も外側の FSDP ユニットにラップされるのが便利です。 したがって、トランスベースのモデルにはこれを使用してください。 - サイズベースの自動ラップポリシーの場合は、設定ファイルに
fsdp_min_num_paramsを追加してください。 自動ラッピングのための FSDP のパラメータの最小数を指定します。
- トランスフォーマーベースの自動ラップポリシーの場合、構成ファイルで
Using Trainer for accelerated PyTorch Training on Mac
PyTorch v1.12 リリースにより、開発者と研究者は Apple シリコン GPU を利用してモデル トレーニングを大幅に高速化できます。
これにより、プロトタイピングや微調整などの機械学習ワークフローを Mac 上でローカルで実行できるようになります。
PyTorch のバックエンドとしての Apple の Metal Performance Shaders (MPS) はこれを可能にし、新しい "mps" デバイス経由で使用できます。
これにより、計算グラフとプリミティブが MPS Graph フレームワークと MPS によって提供される調整されたカーネルにマッピングされます。
詳細については、公式ドキュメント Mac での Accelerated PyTorch Training の紹介 を参照してください。
および MPS バックエンド。
MacOS マシンに PyTorch >= 1.13 (執筆時点ではナイトリー バージョン) をインストールすることを強くお勧めします。 トランスベースのモデルのモデルの正確性とパフォーマンスの向上に関連する主要な修正が行われています。 詳細については、https://github.com/pytorch/pytorch/issues/82707 を参照してください。
Apple Silicon チップを使用したトレーニングと推論の利点
- ユーザーがローカルで大規模なネットワークやバッチ サイズをトレーニングできるようにします
- ユニファイド メモリ アーキテクチャにより、データ取得の遅延が短縮され、GPU がメモリ ストア全体に直接アクセスできるようになります。 したがって、エンドツーエンドのパフォーマンスが向上します。
- クラウドベースの開発に関連するコストや追加のローカル GPU の必要性を削減します。
前提条件: mps サポートを備えたトーチをインストールするには、 この素晴らしいメディア記事 GPU アクセラレーションが M1 Mac の PyTorch に登場 に従ってください。 。
使用法:
mps デバイスは、cuda デバイスが使用される方法と同様に利用可能な場合、デフォルトで使用されます。
したがって、ユーザーによるアクションは必要ありません。
たとえば、以下のコマンドを使用して、Apple Silicon GPU を使用して公式の Glue テキスト分類タスクを (ルート フォルダーから) 実行できます。
export TASK_NAME=mrpc
python examples/pytorch/text-classification/run_glue.py \
--model_name_or_path google-bert/bert-base-cased \
--task_name $TASK_NAME \
--do_train \
--do_eval \
--max_seq_length 128 \
--per_device_train_batch_size 32 \
--learning_rate 2e-5 \
--num_train_epochs 3 \
--output_dir /tmp/$TASK_NAME/ \
注意すべきいくつかの注意事項
- 一部の PyTorch 操作は mps に実装されていないため、エラーがスローされます。
これを回避する 1 つの方法は、環境変数
PYTORCH_ENABLE_MPS_FALLBACK=1を設定することです。 これらの操作では CPU にフォールバックします。ただし、それでも UserWarning がスローされます。 - 分散セットアップ
glooおよびncclは、mpsデバイスでは動作しません。 これは、現在「mps」デバイス タイプの単一 GPU のみを使用できることを意味します。
最後に、覚えておいてください。 🤗 Trainer は MPS バックエンドのみを統合するため、
MPS バックエンドの使用に関して問題や質問がある場合は、
PyTorch GitHub に問題を提出してください。
Using Accelerate Launcher with Trainer
加速してトレーナーにパワーを与えましょう。ユーザーが期待することに関しては、次のとおりです。
- トレーナー引数に対して FSDP、DeepSpeed などのトレーナー インテレーションを変更せずに使用し続けることができます。
- トレーナーで Accelerate Launcher を使用できるようになりました (推奨)。
トレーナーで Accelerate Launcher を使用する手順:
- 🤗 Accelerate がインストールされていることを確認してください。Accelerate がないと
Trainerを使用することはできません。そうでない場合は、pip install accelerateしてください。 Accelerate のバージョンを更新する必要がある場合もあります:pip install activate --upgrade accelerate configを実行し、アンケートに記入します。以下は加速設定の例です。 a. DDP マルチノード マルチ GPU 構成:compute_environment: LOCAL_MACHINE distributed_type: MULTI_GPU downcast_bf16: 'no' gpu_ids: all machine_rank: 0 #change rank as per the node main_process_ip: 192.168.20.1 main_process_port: 9898 main_training_function: main mixed_precision: fp16 num_machines: 2 num_processes: 8 rdzv_backend: static same_network: true tpu_env: [] tpu_use_cluster: false tpu_use_sudo: false use_cpu: false
b. FSDP config:
yaml compute_environment: LOCAL_MACHINE distributed_type: FSDP downcast_bf16: 'no' fsdp_config: fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP fsdp_backward_prefetch_policy: BACKWARD_PRE fsdp_forward_prefetch: true fsdp_offload_params: false fsdp_sharding_strategy: 1 fsdp_state_dict_type: FULL_STATE_DICT fsdp_sync_module_states: true fsdp_transformer_layer_cls_to_wrap: BertLayer fsdp_use_orig_params: true machine_rank: 0 main_training_function: main mixed_precision: bf16 num_machines: 1 num_processes: 2 rdzv_backend: static same_network: true tpu_env: [] tpu_use_cluster: false tpu_use_sudo: false use_cpu: false
c.ファイルを指す DeepSpeed 構成:
yaml compute_environment: LOCAL_MACHINE deepspeed_config: deepspeed_config_file: /home/user/configs/ds_zero3_config.json zero3_init_flag: true distributed_type: DEEPSPEED downcast_bf16: 'no' machine_rank: 0 main_training_function: main num_machines: 1 num_processes: 4 rdzv_backend: static same_network: true tpu_env: [] tpu_use_cluster: false tpu_use_sudo: false use_cpu: false
d.加速プラグインを使用した DeepSpeed 構成:
```yaml
compute_environment: LOCAL_MACHINE
deepspeed_config:
gradient_accumulation_steps: 1
gradient_clipping: 0.7
offload_optimizer_device: cpu
offload_param_device: cpu
zero3_init_flag: true
zero_stage: 2
distributed_type: DEEPSPEED
downcast_bf16: 'no'
machine_rank: 0
main_training_function: main
mixed_precision: bf16
num_machines: 1
num_processes: 4
rdzv_backend: static
same_network: true
tpu_env: []
tpu_use_cluster: false
tpu_use_sudo: false
use_cpu: false
```
- 加速設定またはランチャー引数によって上記で処理された引数以外の引数を使用して、トレーナー スクリプトを実行します。
以下は、上記の FSDP 構成で
accelerate launcherを使用してrun_glue.pyを実行する例です。
cd transformers
accelerate launch \
./examples/pytorch/text-classification/run_glue.py \
--model_name_or_path google-bert/bert-base-cased \
--task_name $TASK_NAME \
--do_train \
--do_eval \
--max_seq_length 128 \
--per_device_train_batch_size 16 \
--learning_rate 5e-5 \
--num_train_epochs 3 \
--output_dir /tmp/$TASK_NAME/ \
accelerate launchするための cmd 引数を直接使用することもできます。上の例は次のようにマッピングされます。
cd transformers
accelerate launch --num_processes=2 \
--use_fsdp \
--mixed_precision=bf16 \
--fsdp_auto_wrap_policy=TRANSFORMER_BASED_WRAP \
--fsdp_transformer_layer_cls_to_wrap="BertLayer" \
--fsdp_sharding_strategy=1 \
--fsdp_state_dict_type=FULL_STATE_DICT \
./examples/pytorch/text-classification/run_glue.py
--model_name_or_path google-bert/bert-base-cased \
--task_name $TASK_NAME \
--do_train \
--do_eval \
--max_seq_length 128 \
--per_device_train_batch_size 16 \
--learning_rate 5e-5 \
--num_train_epochs 3 \
--output_dir /tmp/$TASK_NAME/ \
詳細については、🤗 Accelerate CLI ガイドを参照してください: 🤗 Accelerate スクリプトの起動。
移動されたセクション:
[ DeepSpeed | Installation | Deployment with multiple GPUs | Deployment with one GPU | Deployment in Notebooks | Configuration | Passing Configuration | Shared Configuration | ZeRO | ZeRO-2 Config | ZeRO-3 Config | NVMe Support | ZeRO-2 vs ZeRO-3 Performance | ZeRO-2 Example | ZeRO-3 Example | Optimizer | Scheduler | fp32 Precision | Automatic Mixed Precision | Batch Size | Gradient Accumulation | Gradient Clipping | Getting The Model Weights Out ]
Xet Storage Details
- Size:
- 112 kB
- Xet hash:
- 20d4162c3a386f5b5a1cee4de68eea277797bc580effe1bdc1da4c15fcbc336b
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.