text
stringlengths
2
11.8k
Take a look at the Create a custom architecture guide for more information about building custom configurations. Trainer - a PyTorch optimized training loop All models are a standard torch.nn.Module so you can use them in any typical training loop. While you can write your own training loop, πŸ€— Transformers provides a [Trainer] class for PyTorch, which contains the basic training loop and adds additional functionality for features like distributed training, mixed precision, and more. Depending on your task, you'll typically pass the following parameters to [Trainer]:
You'll start with a [PreTrainedModel] or a torch.nn.Module: from transformers import AutoModelForSequenceClassification model = AutoModelForSequenceClassification.from_pretrained("distilbert/distilbert-base-uncased") [TrainingArguments] contains the model hyperparameters you can change like learning rate, batch size, and the number of epochs to train for. The default values are used if you don't specify any training arguments:
from transformers import TrainingArguments training_args = TrainingArguments( output_dir="path/to/save/folder/", learning_rate=2e-5, per_device_train_batch_size=8, per_device_eval_batch_size=8, num_train_epochs=2, ) Load a preprocessing class like a tokenizer, image processor, feature extractor, or processor: from transformers import AutoTokenizer tokenizer = AutoTokenizer.from_pretrained("distilbert/distilbert-base-uncased") Load a dataset:
from transformers import AutoTokenizer tokenizer = AutoTokenizer.from_pretrained("distilbert/distilbert-base-uncased") Load a dataset: from datasets import load_dataset dataset = load_dataset("rotten_tomatoes") # doctest: +IGNORE_RESULT Create a function to tokenize the dataset: def tokenize_dataset(dataset): return tokenizer(dataset["text"]) Then apply it over the entire dataset with [~datasets.Dataset.map]: dataset = dataset.map(tokenize_dataset, batched=True)
Then apply it over the entire dataset with [~datasets.Dataset.map]: dataset = dataset.map(tokenize_dataset, batched=True) A [DataCollatorWithPadding] to create a batch of examples from your dataset: from transformers import DataCollatorWithPadding data_collator = DataCollatorWithPadding(tokenizer=tokenizer) Now gather all these classes in [Trainer]:
from transformers import DataCollatorWithPadding data_collator = DataCollatorWithPadding(tokenizer=tokenizer) Now gather all these classes in [Trainer]: from transformers import Trainer trainer = Trainer( model=model, args=training_args, train_dataset=dataset["train"], eval_dataset=dataset["test"], tokenizer=tokenizer, data_collator=data_collator, ) # doctest: +SKIP When you're ready, call [~Trainer.train] to start training: trainer.train() # doctest: +SKIP
When you're ready, call [~Trainer.train] to start training: trainer.train() # doctest: +SKIP For tasks - like translation or summarization - that use a sequence-to-sequence model, use the [Seq2SeqTrainer] and [Seq2SeqTrainingArguments] classes instead.
You can customize the training loop behavior by subclassing the methods inside [Trainer]. This allows you to customize features such as the loss function, optimizer, and scheduler. Take a look at the [Trainer] reference for which methods can be subclassed. The other way to customize the training loop is by using Callbacks. You can use callbacks to integrate with other libraries and inspect the training loop to report on progress or stop the training early. Callbacks do not modify anything in the training loop itself. To customize something like the loss function, you need to subclass the [Trainer] instead. Train with TensorFlow All models are a standard tf.keras.Model so they can be trained in TensorFlow with the Keras API. πŸ€— Transformers provides the [~TFPreTrainedModel.prepare_tf_dataset] method to easily load your dataset as a tf.data.Dataset so you can start training right away with Keras' compile and fit methods.
You'll start with a [TFPreTrainedModel] or a tf.keras.Model: from transformers import TFAutoModelForSequenceClassification model = TFAutoModelForSequenceClassification.from_pretrained("distilbert/distilbert-base-uncased") Load a preprocessing class like a tokenizer, image processor, feature extractor, or processor: from transformers import AutoTokenizer tokenizer = AutoTokenizer.from_pretrained("distilbert/distilbert-base-uncased") Create a function to tokenize the dataset:
from transformers import AutoTokenizer tokenizer = AutoTokenizer.from_pretrained("distilbert/distilbert-base-uncased") Create a function to tokenize the dataset: def tokenize_dataset(dataset): return tokenizer(dataset["text"]) # doctest: +SKIP Apply the tokenizer over the entire dataset with [~datasets.Dataset.map] and then pass the dataset and tokenizer to [~TFPreTrainedModel.prepare_tf_dataset]. You can also change the batch size and shuffle the dataset here if you'd like:
dataset = dataset.map(tokenize_dataset) # doctest: +SKIP tf_dataset = model.prepare_tf_dataset( dataset["train"], batch_size=16, shuffle=True, tokenizer=tokenizer ) # doctest: +SKIP When you're ready, you can call compile and fit to start training. Note that Transformers models all have a default task-relevant loss function, so you don't need to specify one unless you want to:
When you're ready, you can call compile and fit to start training. Note that Transformers models all have a default task-relevant loss function, so you don't need to specify one unless you want to: from tensorflow.keras.optimizers import Adam model.compile(optimizer=Adam(3e-5)) # No loss argument! model.fit(tf_dataset) # doctest: +SKIP
What's next? Now that you've completed the πŸ€— Transformers quick tour, check out our guides and learn how to do more specific things like writing a custom model, fine-tuning a model for a task, and how to train a model with a script. If you're interested in learning more about πŸ€— Transformers core concepts, grab a cup of coffee and take a look at our Conceptual Guides!
Trainer The [Trainer] is a complete training and evaluation loop for PyTorch models implemented in the Transformers library. You only need to pass it the necessary pieces for training (model, tokenizer, dataset, evaluation function, training hyperparameters, etc.), and the [Trainer] class takes care of the rest. This makes it easier to start training faster without manually writing your own training loop. But at the same time, [Trainer] is very customizable and offers a ton of training options so you can tailor it to your exact training needs.
In addition to the [Trainer] class, Transformers also provides a [Seq2SeqTrainer] class for sequence-to-sequence tasks like translation or summarization. There is also the [~trl.SFTTrainer] class from the TRL library which wraps the [Trainer] class and is optimized for training language models like Llama-2 and Mistral with autoregressive techniques. [~trl.SFTTrainer] also supports features like sequence packing, LoRA, quantization, and DeepSpeed for efficiently scaling to any model size.
Feel free to check out the API reference for these other [Trainer]-type classes to learn more about when to use which one. In general, [Trainer] is the most versatile option and is appropriate for a broad spectrum of tasks. [Seq2SeqTrainer] is designed for sequence-to-sequence tasks and [~trl.SFTTrainer] is designed for training language models.
Before you start, make sure Accelerate - a library for enabling and running PyTorch training across distributed environments - is installed. ```bash pip install accelerate upgrade pip install accelerate --upgrade This guide provides an overview of the [Trainer] class. Basic usage [Trainer] includes all the code you'll find in a basic training loop:
This guide provides an overview of the [Trainer] class. Basic usage [Trainer] includes all the code you'll find in a basic training loop: perform a training step to calculate the loss calculate the gradients with the [~accelerate.Accelerator.backward] method update the weights based on the gradients repeat this process until you've reached a predetermined number of epochs
The [Trainer] class abstracts all of this code away so you don't have to worry about manually writing a training loop every time or if you're just getting started with PyTorch and training. You only need to provide the essential components required for training, such as a model and a dataset, and the [Trainer] class handles everything else. If you want to specify any training options or hyperparameters, you can find them in the [TrainingArguments] class. For example, let's define where to save the model in output_dir and push the model to the Hub after training with push_to_hub=True.
from transformers import TrainingArguments training_args = TrainingArguments( output_dir="your-model", learning_rate=2e-5, per_device_train_batch_size=16, per_device_eval_batch_size=16, num_train_epochs=2, weight_decay=0.01, evaluation_strategy="epoch", save_strategy="epoch", load_best_model_at_end=True, push_to_hub=True, )
Pass training_args to the [Trainer] along with a model, dataset, something to preprocess the dataset with (depending on your data type it could be a tokenizer, feature extractor or image processor), a data collator, and a function to compute the metrics you want to track during training. Finally, call [~Trainer.train] to start training!
from transformers import Trainer trainer = Trainer( model=model, args=training_args, train_dataset=dataset["train"], eval_dataset=dataset["test"], tokenizer=tokenizer, data_collator=data_collator, compute_metrics=compute_metrics, ) trainer.train()
Checkpoints The [Trainer] class saves your model checkpoints to the directory specified in the output_dir parameter of [TrainingArguments]. You'll find the checkpoints saved in a checkpoint-000 subfolder where the numbers at the end correspond to the training step. Saving checkpoints are useful for resuming training later.
resume from latest checkpoint trainer.train(resume_from_checkpoint=True) resume from specific checkpoint saved in output directory trainer.train(resume_from_checkpoint="your-model/checkpoint-1000") You can save your checkpoints (the optimizer state is not saved by default) to the Hub by setting push_to_hub=True in [TrainingArguments] to commit and push them. Other options for deciding how your checkpoints are saved are set up in the hub_strategy parameter:
hub_strategy="checkpoint" pushes the latest checkpoint to a subfolder named "last-checkpoint" from which you can resume training hub_strategy="all_checkpoints" pushes all checkpoints to the directory defined in output_dir (you'll see one checkpoint per folder in your model repository)
When you resume training from a checkpoint, the [Trainer] tries to keep the Python, NumPy, and PyTorch RNG states the same as they were when the checkpoint was saved. But because PyTorch has various non-deterministic default settings, the RNG states aren't guaranteed to be the same. If you want to enable full determinism, take a look at the Controlling sources of randomness guide to learn what you can enable to make your training fully deterministic. Keep in mind though that by making certain settings deterministic, training may be slower. Customize the Trainer While the [Trainer] class is designed to be accessible and easy-to-use, it also offers a lot of customizability for more adventurous users. Many of the [Trainer]'s method can be subclassed and overridden to support the functionality you want, without having to rewrite the entire training loop from scratch to accommodate it. These methods include:
[~Trainer.get_train_dataloader] creates a training DataLoader [~Trainer.get_eval_dataloader] creates an evaluation DataLoader [~Trainer.get_test_dataloader] creates a test DataLoader [~Trainer.log] logs information on the various objects that watch training [~Trainer.create_optimizer_and_scheduler] creates an optimizer and learning rate scheduler if they weren't passed in the __init__; these can also be separately customized with [~Trainer.create_optimizer] and [~Trainer.create_scheduler] respectively [~Trainer.compute_loss] computes the loss on a batch of training inputs [~Trainer.training_step] performs the training step [~Trainer.prediction_step] performs the prediction and test step [~Trainer.evaluate] evaluates the model and returns the evaluation metrics [~Trainer.predict] makes predictions (with metrics if labels are available) on the test set
For example, if you want to customize the [~Trainer.compute_loss] method to use a weighted loss instead.
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 for 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
Callbacks Another option for customizing the [Trainer] is to use callbacks. Callbacks don't change anything in the training loop. They inspect the training loop state and then execute some action (early stopping, logging results, etc.) depending on the state. In other words, a callback can't be used to implement something like a custom loss function and you'll need to subclass and override the [~Trainer.compute_loss] method for that. For example, if you want to add an early stopping callback to the training loop after 10 steps.
from transformers import TrainerCallback class EarlyStoppingCallback(TrainerCallback): def init(self, num_steps=10): self.num_steps = num_steps def on_step_end(self, args, state, control, **kwargs): if state.global_step >= self.num_steps: return {"should_training_stop": True} else: return {} Then pass it to the [Trainer]'s callback parameter.
Then pass it to the [Trainer]'s callback parameter. from transformers import Trainer trainer = Trainer( model=model, args=training_args, train_dataset=dataset["train"], eval_dataset=dataset["test"], tokenizer=tokenizer, data_collator=data_collator, compute_metrics=compute_metrics, callback=[EarlyStoppingCallback()], ) Logging Check out the logging API reference for more information about the different logging levels.
The [Trainer] is set to logging.INFO by default which reports errors, warnings, and other basic information. A [Trainer] replica - in distributed environments - is set to logging.WARNING which only reports errors and warnings. You can change the logging level with the log_level and log_level_replica parameters in [TrainingArguments]. To configure the log level setting for each node, use the log_on_each_node parameter to determine whether to use the log level on each node or only on the main node.
[Trainer] sets the log level separately for each node in the [Trainer.__init__] method, so you may want to consider setting this sooner if you're using other Transformers functionalities before creating the [Trainer] object. For example, to set your main code and modules to use the same log level according to each node:
For example, to set your main code and modules to use the same log level according to each node: logger = logging.getLogger(name) logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", handlers=[logging.StreamHandler(sys.stdout)], ) 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()
Use different combinations of log_level and log_level_replica to configure what gets logged on each of the nodes. my_app.py --log_level warning --log_level_replica error Add the log_on_each_node 0 parameter for multi-node environments. ```bash my_app.py --log_level warning --log_level_replica error --log_on_each_node 0 set to only report errors my_app.py --log_level error --log_level_replica error --log_on_each_node 0
NEFTune NEFTune is a technique that can improve performance by adding noise to the embedding vectors during training. To enable it in [Trainer], set the neftune_noise_alpha parameter in [TrainingArguments] to control how much noise is added. from transformers import TrainingArguments, Trainer training_args = TrainingArguments(, neftune_noise_alpha=0.1) trainer = Trainer(, args=training_args)
from transformers import TrainingArguments, Trainer training_args = TrainingArguments(, neftune_noise_alpha=0.1) trainer = Trainer(, args=training_args) NEFTune is disabled after training to restore the original embedding layer to avoid any unexpected behavior. Accelerate and Trainer The [Trainer] class is powered by Accelerate, a library for easily training PyTorch models in distributed environments with support for integrations such as FullyShardedDataParallel (FSDP) and DeepSpeed.
Learn more about FSDP sharding strategies, CPU offloading, and more with the [Trainer] in the Fully Sharded Data Parallel guide. To use Accelerate with [Trainer], run the accelerate.config command to set up training for your training environment. This command creates a config_file.yaml that'll be used when you launch your training script. For example, some example configurations you can setup are:
yml 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
yml 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
yml 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
yml 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
The accelerate_launch command is the recommended way to launch your training script on a distributed system with Accelerate and [Trainer] with the parameters specified in config_file.yaml. This file is saved to the Accelerate cache folder and automatically loaded when you run accelerate_launch. For example, to run the run_glue.py training script with the FSDP configuration:
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/ \ --overwrite_output_dir You could also specify the parameters from the config_file.yaml file directly in the command line:
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/ \ --overwrite_output_dir Check out the Launching your Accelerate scripts tutorial to learn more about accelerate_launch and custom configurations.
Train with a script Along with the πŸ€— Transformers notebooks, there are also example scripts demonstrating how to train a model for a task with PyTorch, TensorFlow, or JAX/Flax. You will also find scripts we've used in our research projects and legacy examples which are mostly community contributed. These scripts are not actively maintained and require a specific version of πŸ€— Transformers that will most likely be incompatible with the latest version of the library. The example scripts are not expected to work out-of-the-box on every problem, and you may need to adapt the script to the problem you're trying to solve. To help you with this, most of the scripts fully expose how data is preprocessed, allowing you to edit it as necessary for your use case. For any feature you'd like to implement in an example script, please discuss it on the forum or in an issue before submitting a Pull Request. While we welcome bug fixes, it is unlikely we will merge a Pull Request that adds more functionality at the cost of readability. This guide will show you how to run an example summarization training script in PyTorch and TensorFlow. All examples are expected to work with both frameworks unless otherwise specified. Setup To successfully run the latest version of the example scripts, you have to install πŸ€— Transformers from source in a new virtual environment:
git clone https://github.com/huggingface/transformers cd transformers pip install . For older versions of the example scripts, click on the toggle below: Examples for older versions of πŸ€— Transformers v4.5.1 v4.4.2 v4.3.3 v4.2.2 v4.1.1 v4.0.1 v3.5.1 v3.4.0 v3.3.1 v3.2.0 v3.1.0 v3.0.2 v2.11.0 v2.10.0 v2.9.1 v2.8.0 v2.7.0 v2.6.0 v2.5.1 v2.4.0 v2.3.0 v2.2.0 v2.1.1 v2.0.0 v1.2.0 v1.1.0 v1.0.0 Then switch your current clone of πŸ€— Transformers to a specific version, like v3.5.1 for example:
Then switch your current clone of πŸ€— Transformers to a specific version, like v3.5.1 for example: git checkout tags/v3.5.1 After you've setup the correct library version, navigate to the example folder of your choice and install the example specific requirements: pip install -r requirements.txt Run a script
pip install -r requirements.txt Run a script The example script downloads and preprocesses a dataset from the πŸ€— Datasets library. Then the script fine-tunes a dataset with the Trainer on an architecture that supports summarization. The following example shows how to fine-tune T5-small on the CNN/DailyMail dataset. The T5 model requires an additional source_prefix argument due to how it was trained. This prompt lets T5 know this is a summarization task.
python examples/pytorch/summarization/run_summarization.py \ --model_name_or_path google-t5/t5-small \ --do_train \ --do_eval \ --dataset_name cnn_dailymail \ --dataset_config "3.0.0" \ --source_prefix "summarize: " \ --output_dir /tmp/tst-summarization \ --per_device_train_batch_size=4 \ --per_device_eval_batch_size=4 \ --overwrite_output_dir \ --predict_with_generate
The example script downloads and preprocesses a dataset from the πŸ€— Datasets library. Then the script fine-tunes a dataset using Keras on an architecture that supports summarization. The following example shows how to fine-tune T5-small on the CNN/DailyMail dataset. The T5 model requires an additional source_prefix argument due to how it was trained. This prompt lets T5 know this is a summarization task.
python examples/tensorflow/summarization/run_summarization.py \ --model_name_or_path google-t5/t5-small \ --dataset_name cnn_dailymail \ --dataset_config "3.0.0" \ --output_dir /tmp/tst-summarization \ --per_device_train_batch_size 8 \ --per_device_eval_batch_size 16 \ --num_train_epochs 3 \ --do_train \ --do_eval
Distributed training and mixed precision The Trainer supports distributed training and mixed precision, which means you can also use it in a script. To enable both of these features: Add the fp16 argument to enable mixed precision. Set the number of GPUs to use with the nproc_per_node argument.
torchrun \ --nproc_per_node 8 pytorch/summarization/run_summarization.py \ --fp16 \ --model_name_or_path google-t5/t5-small \ --do_train \ --do_eval \ --dataset_name cnn_dailymail \ --dataset_config "3.0.0" \ --source_prefix "summarize: " \ --output_dir /tmp/tst-summarization \ --per_device_train_batch_size=4 \ --per_device_eval_batch_size=4 \ --overwrite_output_dir \ --predict_with_generate TensorFlow scripts utilize a MirroredStrategy for distributed training, and you don't need to add any additional arguments to the training script. The TensorFlow script will use multiple GPUs by default if they are available. Run a script on a TPU
Tensor Processing Units (TPUs) are specifically designed to accelerate performance. PyTorch supports TPUs with the XLA deep learning compiler (see here for more details). To use a TPU, launch the xla_spawn.py script and use the num_cores argument to set the number of TPU cores you want to use.
python xla_spawn.py --num_cores 8 \ summarization/run_summarization.py \ --model_name_or_path google-t5/t5-small \ --do_train \ --do_eval \ --dataset_name cnn_dailymail \ --dataset_config "3.0.0" \ --source_prefix "summarize: " \ --output_dir /tmp/tst-summarization \ --per_device_train_batch_size=4 \ --per_device_eval_batch_size=4 \ --overwrite_output_dir \ --predict_with_generate
Tensor Processing Units (TPUs) are specifically designed to accelerate performance. TensorFlow scripts utilize a TPUStrategy for training on TPUs. To use a TPU, pass the name of the TPU resource to the tpu argument.
python run_summarization.py \ --tpu name_of_tpu_resource \ --model_name_or_path google-t5/t5-small \ --dataset_name cnn_dailymail \ --dataset_config "3.0.0" \ --output_dir /tmp/tst-summarization \ --per_device_train_batch_size 8 \ --per_device_eval_batch_size 16 \ --num_train_epochs 3 \ --do_train \ --do_eval
Run a script with πŸ€— Accelerate πŸ€— Accelerate is a PyTorch-only library that offers a unified method for training a model on several types of setups (CPU-only, multiple GPUs, TPUs) while maintaining complete visibility into the PyTorch training loop. Make sure you have πŸ€— Accelerate installed if you don't already have it: Note: As Accelerate is rapidly developing, the git version of accelerate must be installed to run the scripts pip install git+https://github.com/huggingface/accelerate
Note: As Accelerate is rapidly developing, the git version of accelerate must be installed to run the scripts pip install git+https://github.com/huggingface/accelerate Instead of the run_summarization.py script, you need to use the run_summarization_no_trainer.py script. πŸ€— Accelerate supported scripts will have a task_no_trainer.py file in the folder. Begin by running the following command to create and save a configuration file:
accelerate config Test your setup to make sure it is configured correctly: accelerate test Now you are ready to launch the training:
accelerate test Now you are ready to launch the training: accelerate launch run_summarization_no_trainer.py \ --model_name_or_path google-t5/t5-small \ --dataset_name cnn_dailymail \ --dataset_config "3.0.0" \ --source_prefix "summarize: " \ --output_dir ~/tmp/tst-summarization Use a custom dataset The summarization script supports custom datasets as long as they are a CSV or JSON Line file. When you use your own dataset, you need to specify several additional arguments:
train_file and validation_file specify the path to your training and validation files. text_column is the input text to summarize. summary_column is the target text to output. A summarization script using a custom dataset would look like this:
python examples/pytorch/summarization/run_summarization.py \ --model_name_or_path google-t5/t5-small \ --do_train \ --do_eval \ --train_file path_to_csv_or_jsonlines_file \ --validation_file path_to_csv_or_jsonlines_file \ --text_column text_column_name \ --summary_column summary_column_name \ --source_prefix "summarize: " \ --output_dir /tmp/tst-summarization \ --overwrite_output_dir \ --per_device_train_batch_size=4 \ --per_device_eval_batch_size=4 \ --predict_with_generate Test a script It is often a good idea to run your script on a smaller number of dataset examples to ensure everything works as expected before committing to an entire dataset which may take hours to complete. Use the following arguments to truncate the dataset to a maximum number of samples:
max_train_samples max_eval_samples max_predict_samples
python examples/pytorch/summarization/run_summarization.py \ --model_name_or_path google-t5/t5-small \ --max_train_samples 50 \ --max_eval_samples 50 \ --max_predict_samples 50 \ --do_train \ --do_eval \ --dataset_name cnn_dailymail \ --dataset_config "3.0.0" \ --source_prefix "summarize: " \ --output_dir /tmp/tst-summarization \ --per_device_train_batch_size=4 \ --per_device_eval_batch_size=4 \ --overwrite_output_dir \ --predict_with_generate Not all example scripts support the max_predict_samples argument. If you aren't sure whether your script supports this argument, add the -h argument to check:
examples/pytorch/summarization/run_summarization.py -h Resume training from checkpoint Another helpful option to enable is resuming training from a previous checkpoint. This will ensure you can pick up where you left off without starting over if your training gets interrupted. There are two methods to resume training from a checkpoint. The first method uses the output_dir previous_output_dir argument to resume training from the latest checkpoint stored in output_dir. In this case, you should remove overwrite_output_dir:
python examples/pytorch/summarization/run_summarization.py --model_name_or_path google-t5/t5-small \ --do_train \ --do_eval \ --dataset_name cnn_dailymail \ --dataset_config "3.0.0" \ --source_prefix "summarize: " \ --output_dir /tmp/tst-summarization \ --per_device_train_batch_size=4 \ --per_device_eval_batch_size=4 \ --output_dir previous_output_dir \ --predict_with_generate The second method uses the resume_from_checkpoint path_to_specific_checkpoint argument to resume training from a specific checkpoint folder.
python examples/pytorch/summarization/run_summarization.py --model_name_or_path google-t5/t5-small \ --do_train \ --do_eval \ --dataset_name cnn_dailymail \ --dataset_config "3.0.0" \ --source_prefix "summarize: " \ --output_dir /tmp/tst-summarization \ --per_device_train_batch_size=4 \ --per_device_eval_batch_size=4 \ --overwrite_output_dir \ --resume_from_checkpoint path_to_specific_checkpoint \ --predict_with_generate Share your model All scripts can upload your final model to the Model Hub. Make sure you are logged into Hugging Face before you begin:
huggingface-cli login Then add the push_to_hub argument to the script. This argument will create a repository with your Hugging Face username and the folder name specified in output_dir. To give your repository a specific name, use the push_to_hub_model_id argument to add it. The repository will be automatically listed under your namespace. The following example shows how to upload a model with a specific repository name:
python examples/pytorch/summarization/run_summarization.py --model_name_or_path google-t5/t5-small \ --do_train \ --do_eval \ --dataset_name cnn_dailymail \ --dataset_config "3.0.0" \ --source_prefix "summarize: " \ --push_to_hub \ --push_to_hub_model_id finetuned-t5-cnn_dailymail \ --output_dir /tmp/tst-summarization \ --per_device_train_batch_size=4 \ --per_device_eval_batch_size=4 \ --overwrite_output_dir \ --predict_with_generate
Building custom models The πŸ€— Transformers library is designed to be easily extensible. Every model is fully coded in a given subfolder of the repository with no abstraction, so you can easily copy a modeling file and tweak it to your needs. If you are writing a brand new model, it might be easier to start from scratch. In this tutorial, we will show you how to write a custom model and its configuration so it can be used inside Transformers, and how you can share it with the community (with the code it relies on) so that anyone can use it, even if it's not present in the πŸ€— Transformers library. We'll see how to build upon transformers and extend the framework with your hooks and custom code. We will illustrate all of this on a ResNet model, by wrapping the ResNet class of the timm library into a [PreTrainedModel]. Writing a custom configuration Before we dive into the model, let's first write its configuration. The configuration of a model is an object that will contain all the necessary information to build the model. As we will see in the next section, the model can only take a config to be initialized, so we really need that object to be as complete as possible.
Models in the transformers library itself generally follow the convention that they accept a config object in their __init__ method, and then pass the whole config to sub-layers in the model, rather than breaking the config object into multiple arguments that are all passed individually to sub-layers. Writing your model in this style results in simpler code with a clear "source of truth" for any hyperparameters, and also makes it easier to reuse code from other models in transformers.
In our example, we will take a couple of arguments of the ResNet class that we might want to tweak. Different configurations will then give us the different types of ResNets that are possible. We then just store those arguments, after checking the validity of a few of them. thon from transformers import PretrainedConfig from typing import List class ResnetConfig(PretrainedConfig): model_type = "resnet" def __init__( self, block_type="bottleneck", layers: List[int] = [3, 4, 6, 3], num_classes: int = 1000, input_channels: int = 3, cardinality: int = 1, base_width: int = 64, stem_width: int = 64, stem_type: str = "", avg_down: bool = False, **kwargs, ): if block_type not in ["basic", "bottleneck"]: raise ValueError(f"`block_type` must be 'basic' or bottleneck', got {block_type}.") if stem_type not in ["", "deep", "deep-tiered"]: raise ValueError(f"`stem_type` must be '', 'deep' or 'deep-tiered', got {stem_type}.")
self.block_type = block_type self.layers = layers self.num_classes = num_classes self.input_channels = input_channels self.cardinality = cardinality self.base_width = base_width self.stem_width = stem_width self.stem_type = stem_type self.avg_down = avg_down super().__init__(**kwargs)
The three important things to remember when writing you own configuration are the following: - you have to inherit from PretrainedConfig, - the __init__ of your PretrainedConfig must accept any kwargs, - those kwargs need to be passed to the superclass __init__. The inheritance is to make sure you get all the functionality from the πŸ€— Transformers library, while the two other constraints come from the fact a PretrainedConfig has more fields than the ones you are setting. When reloading a config with the from_pretrained method, those fields need to be accepted by your config and then sent to the superclass. Defining a model_type for your configuration (here model_type="resnet") is not mandatory, unless you want to register your model with the auto classes (see last section). With this done, you can easily create and save your configuration like you would do with any other model config of the library. Here is how we can create a resnet50d config and save it: py resnet50d_config = ResnetConfig(block_type="bottleneck", stem_width=32, stem_type="deep", avg_down=True) resnet50d_config.save_pretrained("custom-resnet") This will save a file named config.json inside the folder custom-resnet. You can then reload your config with the from_pretrained method: py resnet50d_config = ResnetConfig.from_pretrained("custom-resnet") You can also use any other method of the [PretrainedConfig] class, like [~PretrainedConfig.push_to_hub] to directly upload your config to the Hub. Writing a custom model Now that we have our ResNet configuration, we can go on writing the model. We will actually write two: one that extracts the hidden features from a batch of images (like [BertModel]) and one that is suitable for image classification (like [BertForSequenceClassification]). As we mentioned before, we'll only write a loose wrapper of the model to keep it simple for this example. The only thing we need to do before writing this class is a map between the block types and actual block classes. Then the model is defined from the configuration by passing everything to the ResNet class:
from transformers import PreTrainedModel from timm.models.resnet import BasicBlock, Bottleneck, ResNet from .configuration_resnet import ResnetConfig BLOCK_MAPPING = {"basic": BasicBlock, "bottleneck": Bottleneck} class ResnetModel(PreTrainedModel): config_class = ResnetConfig def __init__(self, config): super().__init__(config) block_layer = BLOCK_MAPPING[config.block_type] self.model = ResNet( block_layer, config.layers, num_classes=config.num_classes, in_chans=config.input_channels, cardinality=config.cardinality, base_width=config.base_width, stem_width=config.stem_width, stem_type=config.stem_type, avg_down=config.avg_down, )
def forward(self, tensor): return self.model.forward_features(tensor) For the model that will classify images, we just change the forward method:
import torch class ResnetModelForImageClassification(PreTrainedModel): config_class = ResnetConfig def __init__(self, config): super().__init__(config) block_layer = BLOCK_MAPPING[config.block_type] self.model = ResNet( block_layer, config.layers, num_classes=config.num_classes, in_chans=config.input_channels, cardinality=config.cardinality, base_width=config.base_width, stem_width=config.stem_width, stem_type=config.stem_type, avg_down=config.avg_down, )
def forward(self, tensor, labels=None): logits = self.model(tensor) if labels is not None: loss = torch.nn.cross_entropy(logits, labels) return {"loss": loss, "logits": logits} return {"logits": logits}
In both cases, notice how we inherit from PreTrainedModel and call the superclass initialization with the config (a bit like when you write a regular torch.nn.Module). The line that sets the config_class is not mandatory, unless you want to register your model with the auto classes (see last section). If your model is very similar to a model inside the library, you can re-use the same configuration as this model.
You can have your model return anything you want, but returning a dictionary like we did for ResnetModelForImageClassification, with the loss included when labels are passed, will make your model directly usable inside the [Trainer] class. Using another output format is fine as long as you are planning on using your own training loop or another library for training. Now that we have our model class, let's create one: py resnet50d = ResnetModelForImageClassification(resnet50d_config) Again, you can use any of the methods of [PreTrainedModel], like [~PreTrainedModel.save_pretrained] or [~PreTrainedModel.push_to_hub]. We will use the second in the next section, and see how to push the model weights with the code of our model. But first, let's load some pretrained weights inside our model. In your own use case, you will probably be training your custom model on your own data. To go fast for this tutorial, we will use the pretrained version of the resnet50d. Since our model is just a wrapper around it, it's going to be easy to transfer those weights:
import timm pretrained_model = timm.create_model("resnet50d", pretrained=True) resnet50d.model.load_state_dict(pretrained_model.state_dict())
Now let's see how to make sure that when we do [~PreTrainedModel.save_pretrained] or [~PreTrainedModel.push_to_hub], the code of the model is saved. Registering a model with custom code to the auto classes If you are writing a library that extends πŸ€— Transformers, you may want to extend the auto classes to include your own model. This is different from pushing the code to the Hub in the sense that users will need to import your library to get the custom models (contrarily to automatically downloading the model code from the Hub). As long as your config has a model_type attribute that is different from existing model types, and that your model classes have the right config_class attributes, you can just add them to the auto classes like this:
from transformers import AutoConfig, AutoModel, AutoModelForImageClassification AutoConfig.register("resnet", ResnetConfig) AutoModel.register(ResnetConfig, ResnetModel) AutoModelForImageClassification.register(ResnetConfig, ResnetModelForImageClassification)
Note that the first argument used when registering your custom config to [AutoConfig] needs to match the model_type of your custom config, and the first argument used when registering your custom models to any auto model class needs to match the config_class of those models. Sending the code to the Hub This API is experimental and may have some slight breaking changes in the next releases.
First, make sure your model is fully defined in a .py file. It can rely on relative imports to some other files as long as all the files are in the same directory (we don't support submodules for this feature yet). For our example, we'll define a modeling_resnet.py file and a configuration_resnet.py file in a folder of the current working directory named resnet_model. The configuration file contains the code for ResnetConfig and the modeling file contains the code of ResnetModel and ResnetModelForImageClassification. . └── resnet_model β”œβ”€β”€ __init__.py β”œβ”€β”€ configuration_resnet.py └── modeling_resnet.py The __init__.py can be empty, it's just there so that Python detects resnet_model can be use as a module.
If copying a modeling files from the library, you will need to replace all the relative imports at the top of the file to import from the transformers package.
Note that you can re-use (or subclass) an existing configuration/model. To share your model with the community, follow those steps: first import the ResNet model and config from the newly created files: py from resnet_model.configuration_resnet import ResnetConfig from resnet_model.modeling_resnet import ResnetModel, ResnetModelForImageClassification Then you have to tell the library you want to copy the code files of those objects when using the save_pretrained method and properly register them with a given Auto class (especially for models), just run: py ResnetConfig.register_for_auto_class() ResnetModel.register_for_auto_class("AutoModel") ResnetModelForImageClassification.register_for_auto_class("AutoModelForImageClassification") Note that there is no need to specify an auto class for the configuration (there is only one auto class for them, [AutoConfig]) but it's different for models. Your custom model could be suitable for many different tasks, so you have to specify which one of the auto classes is the correct one for your model.
Use register_for_auto_class() if you want the code files to be copied. If you instead prefer to use code on the Hub from another repo, you don't need to call it. In cases where there's more than one auto class, you can modify the config.json directly using the following structure: json "auto_map": { "AutoConfig": "<your-repo-name>--<config-name>", "AutoModel": "<your-repo-name>--<config-name>", "AutoModelFor<Task>": "<your-repo-name>--<config-name>", },
Next, let's create the config and models as we did before: resnet50d_config = ResnetConfig(block_type="bottleneck", stem_width=32, stem_type="deep", avg_down=True) resnet50d = ResnetModelForImageClassification(resnet50d_config) pretrained_model = timm.create_model("resnet50d", pretrained=True) resnet50d.model.load_state_dict(pretrained_model.state_dict()) Now to send the model to the Hub, make sure you are logged in. Either run in your terminal: huggingface-cli login or from a notebook:
Now to send the model to the Hub, make sure you are logged in. Either run in your terminal: huggingface-cli login or from a notebook: from huggingface_hub import notebook_login notebook_login()
You can then push to your own namespace (or an organization you are a member of) like this: py resnet50d.push_to_hub("custom-resnet50d") On top of the modeling weights and the configuration in json format, this also copied the modeling and configuration .py files in the folder custom-resnet50d and uploaded the result to the Hub. You can check the result in this model repo. See the sharing tutorial for more information on the push to Hub method. Using a model with custom code You can use any configuration, model or tokenizer with custom code files in its repository with the auto-classes and the from_pretrained method. All files and code uploaded to the Hub are scanned for malware (refer to the Hub security documentation for more information), but you should still review the model code and author to avoid executing malicious code on your machine. Set trust_remote_code=True to use a model with custom code:
from transformers import AutoModelForImageClassification model = AutoModelForImageClassification.from_pretrained("sgugger/custom-resnet50d", trust_remote_code=True)
It is also strongly encouraged to pass a commit hash as a revision to make sure the author of the models did not update the code with some malicious new lines (unless you fully trust the authors of the models). py commit_hash = "ed94a7c6247d8aedce4647f00f20de6875b5b292" model = AutoModelForImageClassification.from_pretrained( "sgugger/custom-resnet50d", trust_remote_code=True, revision=commit_hash ) Note that when browsing the commit history of the model repo on the Hub, there is a button to easily copy the commit hash of any commit.
Load pretrained instances with an AutoClass With so many different Transformer architectures, it can be challenging to create one for your checkpoint. As a part of πŸ€— Transformers core philosophy to make the library easy, simple and flexible to use, an AutoClass automatically infers and loads the correct architecture from a given checkpoint. The from_pretrained() method lets you quickly load a pretrained model for any architecture so you don't have to devote time and resources to train a model from scratch. Producing this type of checkpoint-agnostic code means if your code works for one checkpoint, it will work with another checkpoint - as long as it was trained for a similar task - even if the architecture is different.
Remember, architecture refers to the skeleton of the model and checkpoints are the weights for a given architecture. For example, BERT is an architecture, while google-bert/bert-base-uncased is a checkpoint. Model is a general term that can mean either architecture or checkpoint. In this tutorial, learn to: Load a pretrained tokenizer. Load a pretrained image processor Load a pretrained feature extractor. Load a pretrained processor. Load a pretrained model. Load a model as a backbone.
Load a pretrained tokenizer. Load a pretrained image processor Load a pretrained feature extractor. Load a pretrained processor. Load a pretrained model. Load a model as a backbone. AutoTokenizer Nearly every NLP task begins with a tokenizer. A tokenizer converts your input into a format that can be processed by the model. Load a tokenizer with [AutoTokenizer.from_pretrained]: from transformers import AutoTokenizer tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
from transformers import AutoTokenizer tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased") Then tokenize your input as shown below: sequence = "In a hole in the ground there lived a hobbit." print(tokenizer(sequence)) {'input_ids': [101, 1999, 1037, 4920, 1999, 1996, 2598, 2045, 2973, 1037, 7570, 10322, 4183, 1012, 102], 'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}