We've released our memory-efficient finetuning algorithm LISA, check out [Paper][User Guide] for more details!

lmflow.pipeline.utils.raft_trainer#

Module Contents#

Classes#

RaftTrainer

Trainer is a simple but feature-complete training and eval loop for PyTorch, optimized for 🤗 Transformers.

Attributes#

is_torch_greater_or_equal_than_1_10

is_torch_less_than_1_11

_is_native_cpu_amp_available

DEFAULT_CALLBACKS

DEFAULT_PROGRESS_CALLBACK

DEFAULT_PROGRESS_CALLBACK

IS_SAGEMAKER_MP_POST_1_10

skip_first_batches

logger

TRAINING_ARGS_NAME

TRAINER_STATE_NAME

OPTIMIZER_NAME

SCHEDULER_NAME

SCALER_NAME

lmflow.pipeline.utils.raft_trainer.is_torch_greater_or_equal_than_1_10[source]#
lmflow.pipeline.utils.raft_trainer.is_torch_less_than_1_11[source]#
lmflow.pipeline.utils.raft_trainer._is_native_cpu_amp_available[source]#
lmflow.pipeline.utils.raft_trainer.DEFAULT_CALLBACKS[source]#
lmflow.pipeline.utils.raft_trainer.DEFAULT_PROGRESS_CALLBACK[source]#
lmflow.pipeline.utils.raft_trainer.DEFAULT_PROGRESS_CALLBACK[source]#
lmflow.pipeline.utils.raft_trainer.IS_SAGEMAKER_MP_POST_1_10[source]#
lmflow.pipeline.utils.raft_trainer.skip_first_batches[source]#
lmflow.pipeline.utils.raft_trainer.logger[source]#
lmflow.pipeline.utils.raft_trainer.TRAINING_ARGS_NAME = 'training_args.bin'[source]#
lmflow.pipeline.utils.raft_trainer.TRAINER_STATE_NAME = 'trainer_state.json'[source]#
lmflow.pipeline.utils.raft_trainer.OPTIMIZER_NAME = 'optimizer.pt'[source]#
lmflow.pipeline.utils.raft_trainer.SCHEDULER_NAME = 'scheduler.pt'[source]#
lmflow.pipeline.utils.raft_trainer.SCALER_NAME = 'scaler.pt'[source]#
class lmflow.pipeline.utils.raft_trainer.RaftTrainer(model: transformers.modeling_utils.PreTrainedModel | torch.nn.Module = None, args: transformers.training_args.TrainingArguments = None, data_collator: transformers.data.data_collator.DataCollator | None = None, train_dataset: torch.utils.data.Dataset | None = None, eval_dataset: torch.utils.data.Dataset | Dict[str, torch.utils.data.Dataset] | None = None, tokenizer: transformers.tokenization_utils_base.PreTrainedTokenizerBase | None = None, model_init: Callable[[], transformers.modeling_utils.PreTrainedModel] | None = None, compute_metrics: Callable[[transformers.trainer_utils.EvalPrediction], Dict] | None = None, callbacks: List[transformers.trainer_callback.TrainerCallback] | None = None, optimizers: Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None), preprocess_logits_for_metrics: Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | None = None)[source]#

Trainer is a simple but feature-complete training and eval loop for PyTorch, optimized for 🤗 Transformers. Args:

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

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 tokenizer is provided, an instance of [DataCollatorWithPadding] otherwise.

train_dataset (torch.utils.data.Dataset or torch.utils.data.IterableDataset, optional):

The dataset to use for training. If it is a [~datasets.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 (Union[torch.utils.data.Dataset, Dict[str, torch.utils.data.Dataset]), optional):

The dataset to use for evaluation. If it is a [~datasets.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.

tokenizer ([PreTrainedTokenizerBase], optional):

The tokenizer used to preprocess the data. If provided, will be used to automatically pad the inputs to the maximum length when batching inputs, 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 [~Trainer.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/SigOpt trial object, to be able to choose different architectures according to hyper parameters (such as layer count, sizes of inner layers, dropout probabilities etc).

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.

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](callback). 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): 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.

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.

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 in DeepSpeed and then again in torch.nn.DistributedDataParallel. If the inner model hasn’t been wrapped, then self.model_wrapped is the same as self.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 - it will be set to False if model parallel or deepspeed is used, or if the default TrainingArguments.place_model_on_device is overridden to return False .

  • is_in_train – Whether or not a model is currently running train (e.g. when evaluate is called while in train)

add_callback(callback)[source]#

Add a callback to the current list of [~transformer.TrainerCallback]. Args:

callback (type or [~transformer.TrainerCallback]):

A [~transformer.TrainerCallback] class or an instance of a [~transformer.TrainerCallback]. In the first case, will instantiate a member of that class.

pop_callback(callback)[source]#

Remove a callback from the current list of [~transformer.TrainerCallback] and returns it. If the callback is not found, returns None (and no error is raised). Args:

callback (type or [~transformer.TrainerCallback]):

A [~transformer.TrainerCallback] class or an instance of a [~transformer.TrainerCallback]. In the first case, will pop the first member of that class found in the list of callbacks.

Returns:

[~transformer.TrainerCallback]: The callback removed, if found.

remove_callback(callback)[source]#

Remove a callback from the current list of [~transformer.TrainerCallback]. Args:

callback (type or [~transformer.TrainerCallback]):

A [~transformer.TrainerCallback] class or an instance of a [~transformer.TrainerCallback]. In the first case, will remove the first member of that class found in the list of callbacks.

_move_model_to_device(model, device)[source]#
_set_signature_columns_if_needed()[source]#
_remove_unused_columns(dataset: datasets.Dataset, description: str | None = None)[source]#
_get_collator_with_removed_columns(data_collator: Callable, description: str | None = None) Callable[source]#

Wrap the data collator in a callable removing unused columns.

_get_train_sampler() torch.utils.data.Sampler | None[source]#
get_train_dataloader() torch.utils.data.DataLoader[source]#

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.

_get_eval_sampler(eval_dataset: torch.utils.data.Dataset) torch.utils.data.Sampler | None[source]#
get_eval_dataloader(eval_dataset: torch.utils.data.Dataset | None = None) torch.utils.data.DataLoader[source]#

Returns the evaluation [~torch.utils.data.DataLoader]. Subclass and override this method if you want to inject some custom behavior. Args:

eval_dataset (torch.utils.data.Dataset, optional):

If provided, will override self.eval_dataset. If it is a [~datasets.Dataset], columns not accepted by the model.forward() method are automatically removed. It must implement __len__.

get_test_dataloader(test_dataset: torch.utils.data.Dataset) torch.utils.data.DataLoader[source]#

Returns the test [~torch.utils.data.DataLoader]. Subclass and override this method if you want to inject some custom behavior. Args:

test_dataset (torch.utils.data.Dataset, optional):

The test dataset to use. If it is a [~datasets.Dataset], columns not accepted by the model.forward() method are automatically removed. It must implement __len__.

create_optimizer_and_scheduler(num_training_steps: int)[source]#

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_optimizer()[source]#

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.

static get_optimizer_cls_and_kwargs(args: transformers.training_args.TrainingArguments) Tuple[Any, Any][source]#

Returns the optimizer class and optimizer parameters based on the training arguments. Args:

args (transformers.training_args.TrainingArguments):

The training arguments for the training session.

create_scheduler(num_training_steps: int, optimizer: torch.optim.Optimizer = None)[source]#

Setup the scheduler. The optimizer of the trainer must have been set up either before this method is called or passed as an argument. Args:

num_training_steps (int): The number of training steps to do.

num_examples(dataloader: torch.utils.data.DataLoader) int[source]#

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

_hp_search_setup(trial: optuna.Trial | Dict[str, Any])[source]#

HP search setup code

_tune_save_checkpoint()[source]#
call_model_init(trial=None)[source]#
torch_jit_model_eval(model, dataloader, training=False)[source]#
ipex_optimize_model(model, training=False, dtype=torch.float32)[source]#
_wrap_model(model, training=True, dataloader=None)[source]#
train(resume_from_checkpoint: str | bool | None = None, trial: optuna.Trial | Dict[str, Any] = None, ignore_keys_for_eval: List[str] | None = None, is_first_time=False, **kwargs)[source]#

Main training entry point. Args:

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.

kwargs:

Additional keyword arguments used to hide deprecated arguments

_one_train(batch_size=None, args=None, resume_from_checkpoint=None, trial=None, ignore_keys_for_eval=None)[source]#
_inner_training_loop(batch_size=None, args=None, resume_from_checkpoint=None, trial=None, ignore_keys_for_eval=None)[source]#

0 This function serves to train one time 1 Update the self.train_dataset before calling this function

_get_output_dir(trial)[source]#
_load_from_checkpoint(resume_from_checkpoint, model=None)[source]#
_load_best_model()[source]#
_issue_warnings_after_load(load_result)[source]#
_maybe_log_save_evaluate(tr_loss, model, trial, epoch, ignore_keys_for_eval)[source]#
_load_rng_state(checkpoint)[source]#
_save_checkpoint(model, trial, metrics=None)[source]#
_load_optimizer_and_scheduler(checkpoint)[source]#

If optimizer and scheduler states exist, load them.

Launch an hyperparameter search using optuna or Ray Tune or SigOpt. 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. <Tip warning={true}> 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 [~Trainer.create_optimizer_and_scheduler] for custom optimizer/scheduler. </Tip> Args:

hp_space (Callable[[“optuna.Trial”], Dict[str, float]], optional):

A function that defines the hyperparameter search space. Will default to [~trainer_utils.default_hp_space_optuna] or [~trainer_utils.default_hp_space_ray] or [~trainer_utils.default_hp_space_sigopt] 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 [~trainer_utils.default_compute_objective].

n_trials (int, optional, defaults to 100):

The number of trial runs to test.

direction (str, optional, defaults to “minimize”):

Whether to optimize greater or lower objects. Can be “minimize” or “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 or SigOpt, 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 passed along to optuna.create_study or ray.tune.run. For more information see: - the documentation of

Returns:

[trainer_utils.BestRun]: All the information about the best run. Experiment summary can be found in run_summary attribute for Ray backend.

log(logs: Dict[str, float]) None[source]#

Log logs on the various objects watching training. Subclass and override this method to inject custom behavior. Args:

logs (Dict[str, float]):

The values to log.

_prepare_input(data: torch.Tensor | Any) torch.Tensor | Any[source]#

Prepares one data before feeding it to the model, be it a tensor or a nested list/dictionary of tensors.

_prepare_inputs(inputs: Dict[str, torch.Tensor | Any]) Dict[str, torch.Tensor | Any][source]#

Prepare inputs before feeding them to the model, converting them to tensors if they are not already and handling potential state.

compute_loss_context_manager()[source]#

A helper wrapper to group together context managers.

autocast_smart_context_manager(cache_enabled: bool | None = True)[source]#

A helper wrapper that creates an appropriate context manager for autocast while feeding it the desired arguments, depending on the situation.

training_step(model: torch.nn.Module, inputs: Dict[str, torch.Tensor | Any]) torch.Tensor[source]#

Perform a training step on a batch of inputs. Subclass and override to inject custom behavior. Args:

model (nn.Module):

The model to train.

inputs (Dict[str, Union[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.

Return:

torch.Tensor: The tensor with training loss on this batch.

compute_loss(model, inputs, return_outputs=False)[source]#

How the loss is computed by Trainer. By default, all models return the loss in the first element. Subclass and override for custom behavior.

is_local_process_zero() bool[source]#

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() bool[source]#

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

save_model(output_dir: str | None = None, _internal_call: bool = False)[source]#

Will save the model, so you can reload it using from_pretrained(). Will only save from the main process.

_save_tpu(output_dir: str | None = None)[source]#
_save(output_dir: str | None = None, state_dict=None)[source]#
store_flos()[source]#
_sorted_checkpoints(output_dir=None, checkpoint_prefix=PREFIX_CHECKPOINT_DIR, use_mtime=False) List[str][source]#
_rotate_checkpoints(use_mtime=False, output_dir=None) None[source]#
evaluate(eval_dataset: torch.utils.data.Dataset | None = None, ignore_keys: List[str] | None = None, metric_key_prefix: str = 'eval') Dict[str, float][source]#

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. Args:

eval_dataset (Dataset, optional):

Pass a dataset if you wish to override self.eval_dataset. If it is a [~datasets.Dataset], columns not accepted by the model.forward() method are automatically removed. It must implement the __len__ method.

ignore_keys (Lst[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.

predict(test_dataset: torch.utils.data.Dataset, ignore_keys: List[str] | None = None, metric_key_prefix: str = 'test') transformers.trainer_utils.PredictionOutput[source]#

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(). Args:

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 (Lst[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)

<Tip> 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. </Tip> Returns: NamedTuple A namedtuple with the following keys:

  • predictions (np.ndarray): The predictions on test_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).

evaluation_loop(dataloader: torch.utils.data.DataLoader, description: str, prediction_loss_only: bool | None = None, ignore_keys: List[str] | None = None, metric_key_prefix: str = 'eval') transformers.trainer_utils.EvalLoopOutput[source]#

Prediction/evaluation loop, shared by Trainer.evaluate() and Trainer.predict(). Works both with or without labels.

_nested_gather(tensors, name=None)[source]#

Gather value of tensors (tensor or list/tuple of nested tensors) and convert them to numpy before concatenating them to gathered

_pad_across_processes(tensor, pad_index=-100)[source]#

Recursively pad the tensors in a nested list/tuple/dictionary of tensors from all devices to the same size so they can safely be gathered.

prediction_step(model: torch.nn.Module, inputs: Dict[str, torch.Tensor | Any], prediction_loss_only: bool, ignore_keys: List[str] | None = None) Tuple[torch.Tensor | None, torch.Tensor | None, torch.Tensor | None][source]#

Perform an evaluation step on model using inputs. Subclass and override to inject custom behavior. Args:

model (nn.Module):

The model to evaluate.

inputs (Dict[str, Union[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 (Lst[str], optional):

A list of keys in the output of your model (if it is a dictionary) that should be ignored when gathering predictions.

Return:

Tuple[Optional[torch.Tensor], Optional[torch.Tensor], Optional[torch.Tensor]]: A tuple with the loss, logits and labels (each being optional).

floating_point_ops(inputs: Dict[str, torch.Tensor | Any])[source]#

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. Args:

inputs (Dict[str, Union[torch.Tensor, Any]]):

The inputs and targets of the model.

Returns:

int: The number of floating-point operations.

init_git_repo(at_init: bool = False)[source]#

Initializes a git repo in self.args.hub_model_id. Args:

at_init (bool, optional, defaults to False):

Whether this function is called before any training or not. If self.args.overwrite_output_dir is True and at_init is True, the path to the repo (which is self.args.output_dir) might be wiped out.

create_model_card(language: str | None = None, license: str | None = None, tags: str | List[str] | None = None, model_name: str | None = None, finetuned_from: str | None = None, tasks: str | List[str] | None = None, dataset_tags: str | List[str] | None = None, dataset: str | List[str] | None = None, dataset_args: str | List[str] | None = None)[source]#

Creates a draft of a model card using the information available to the Trainer. Args:

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.

_push_from_checkpoint(checkpoint_folder)[source]#
push_to_hub(commit_message: str | None = 'End of training', blocking: bool = True, **kwargs) str[source]#

Upload self.model and self.tokenizer 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.

kwargs:

Additional keyword arguments passed along to [~Trainer.create_model_card].

Returns:

The url of the commit of your model in the given repository if blocking=False, a tuple with the url of the commit and an object to track the progress of the commit if blocking=True

prediction_loop(dataloader: torch.utils.data.DataLoader, description: str, prediction_loss_only: bool | None = None, ignore_keys: List[str] | None = None, metric_key_prefix: str = 'eval') transformers.trainer_utils.EvalLoopOutput[source]#

Prediction/evaluation loop, shared by Trainer.evaluate() and Trainer.predict(). Works both with or without labels.

_gather_and_numpify(tensors, name)[source]#

Gather value of tensors (tensor or list/tuple of nested tensors) and convert them to numpy before concatenating them to gathered

_add_sm_patterns_to_gitignore() None[source]#

Add SageMaker Checkpointing patterns to .gitignore file.