From f6a7aaf121641da12efa16fd9cd385ccbde59b93 Mon Sep 17 00:00:00 2001 From: TimoImhof <62378375+TimoImhof@users.noreply.github.com> Date: Fri, 31 Mar 2023 15:58:04 +0200 Subject: [PATCH] Update doc chapter "Getting Started" (#527) --- adapter_docs/installation.md | 4 +-- adapter_docs/quickstart.md | 60 ++++++++++++++++++++---------------- adapter_docs/training.md | 38 +++++++++++------------ 3 files changed, 54 insertions(+), 48 deletions(-) diff --git a/adapter_docs/installation.md b/adapter_docs/installation.md index 53ad93aed6..da6359e85f 100644 --- a/adapter_docs/installation.md +++ b/adapter_docs/installation.md @@ -6,8 +6,8 @@ It currently supports Python 3.8+ and PyTorch 1.12.1+. You will have to [install ```{eval-rst} .. important:: ``adapter-transformers`` is a direct fork of ``transformers``. - This means our package includes all the awesome features of HuggingFace's original package plus the adapter implementation. - As both packages share the same namespace, they ideally should not installed in the same environment. + This means our package includes all the awesome features of HuggingFace's original package, plus the adapter implementation. + As both packages share the same namespace, they ideally should not be installed in the same environment. ``` ## Using pip diff --git a/adapter_docs/quickstart.md b/adapter_docs/quickstart.md index fb4010dd84..17f7f0b5ca 100644 --- a/adapter_docs/quickstart.md +++ b/adapter_docs/quickstart.md @@ -10,7 +10,7 @@ storing (`save_adapter()`) and deletion (`delete_adapter()`) are added to the mo .. note:: This document focuses on the adapter-related functionalities added by *adapter-transformers*. For a more general overview of the *transformers* library, visit - `the 'Usage' section in Huggingface's documentation `_. + `the 'Usage' section in HuggingFace's documentation `_. ``` ## Quick Tour: Using a pre-trained adapter for inference @@ -24,41 +24,43 @@ We use BERT in this example, so we first load a pre-trained `BertTokenizer` to e `bert-base-uncased` checkpoint from HuggingFace's Model Hub using the [`BertAdapterModel`](transformers.adapters.BertAdapterModel) class: ```python +import os + import torch from transformers import BertTokenizer -from transformers.adapters import BertAdapterModel +from transformers.adapters import BertAdapterModel, AutoAdapterModel -# Load pre-trained BERT tokenizer from Huggingface. +# Load pre-trained BERT tokenizer from HuggingFace tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') -# An input sentence. +# An input sentence sentence = "It's also, clearly, great fun." -# Tokenize the input sentence and create a PyTorch input tensor. +# Tokenize the input sentence and create a PyTorch input tensor input_data = tokenizer(sentence, return_tensors="pt") -# Load pre-trained BERT model from HuggingFace Hub. -# The `BertAdapterModel` class is specifically designed for working with adapters. -# It can be used with different prediction heads. +# Load pre-trained BERT model from HuggingFace Hub +# The `BertAdapterModel` class is specifically designed for working with adapters +# It can be used with different prediction heads model = BertAdapterModel.from_pretrained('bert-base-uncased') ``` Having loaded the model, we now add a pre-trained task adapter that is useful to our task from AdapterHub. -As we're doing sentiment classification, we use [an adapter trained on the SST-2 dataset](https://adapterhub.ml/adapters/ukp/bert-base-uncased_sentiment_sst-2_pfeiffer/) in this case. +In this case, for sentiment classification, we thus use [an adapter trained on the SST-2 dataset](https://adapterhub.ml/adapters/ukp/bert-base-uncased_sentiment_sst-2_pfeiffer/). The task prediction head loaded together with the adapter gives us a class label for our sentence: ```python -# load pre-trained task adapter from Adapter Hub -# this method call will also load a pre-trained classification head for the adapter task -adapter_name = model.load_adapter('sst-2@ukp', config='pfeiffer') +# Load pre-trained task adapter from Adapter Hub +# This method call will also load a pre-trained classification head for the adapter task +adapter_name = model.load_adapter("sentiment/sst-2@ukp", config='pfeiffer') -# activate the adapter we just loaded, so that it is used in every forward pass +# Activate the adapter we just loaded, so that it is used in every forward pass model.set_active_adapters(adapter_name) -# predict output tensor +# Predict output tensor outputs = model(**input_data) -# retrieve the predicted class label +# Retrieve the predicted class label predicted = torch.argmax(outputs[0]).item() assert predicted == 1 ``` @@ -66,25 +68,29 @@ assert predicted == 1 To save our pre-trained model and adapters, we can easily store and reload them as follows: ```python -# save model -model.save_pretrained('./path/to/model/directory/') -# save adapter -model.save_adapter('./path/to/adapter/directory/', 'sst-2') - -# load model -model = AutoAdapterModel.from_pretrained('./path/to/model/directory/') -model.load_adapter('./path/to/adapter/directory/') +# For the sake of this demonstration an example path for loading and storing is given below +example_path = os.path.join(os.getcwd(), "adapter-quickstart") + +# Save model +model.save_pretrained(example_path) +# Save adapter +model.save_adapter(example_path, adapter_name) + +# Load model, similar to HuggingFace's AutoModel class, +# you can also use AutoAdapterModel instead of BertAdapterModel +model = AutoAdapterModel.from_pretrained(example_path) +model.load_adapter(example_path) ``` Similar to how the weights of the full model are saved, the `save_adapter()` will create a file for saving the adapter weights and a file for saving the adapter configuration in the specified directory. -Finally, if we have finished working with adapters, we can restore the base Transformer in its original form by deactivating and deleting the adapter: +Finally, if we have finished working with adapters, we can restore the base Transformer to its original form by deactivating and deleting the adapter: ```python -# deactivate all adapters +# Deactivate all adapters model.set_active_adapters(None) -# delete the added adapter -model.delete_adapter('sst-2') +# Delete the added adapter +model.delete_adapter(adapter_name) ``` ## Quick Tour: Adapter training diff --git a/adapter_docs/training.md b/adapter_docs/training.md index fe75e7697c..ce4c9aaa70 100644 --- a/adapter_docs/training.md +++ b/adapter_docs/training.md @@ -1,7 +1,7 @@ # Adapter Training This section describes some examples of training adapter methods for different scenarios. We focus on integrating adapter methods into existing training scripts for Transformer models. -All presented scripts are only slightly modified from the original [examples from HuggingFace Transformers](https://huggingface.co/transformers/examples.html). +All presented scripts are only slightly modified from the original [examples from HuggingFace Transformers](https://github.com/huggingface/transformers/tree/main/examples/pytorch#examples). To run the scripts, make sure you have the latest version of the repository and have installed some additional requirements: ``` @@ -13,14 +13,14 @@ pip install -r ./examples/pytorch//requirements.txt ## Train a Task Adapter -Training a task adapter module on a dataset only requires minor modifications from training the full model. +Training a task adapter module on a dataset only requires minor modifications compared to training the entire model. Suppose we have an existing script for training a Transformer model. In the following, we will use HuggingFace's [run_glue.py](https://github.com/Adapter-Hub/adapter-transformers/blob/master/examples/pytorch/text-classification/run_glue.py) example script for training on the GLUE benchmark. We go through all required changes step by step: ### Step A - Parse `AdapterArguments` -The [`AdapterArguments`](transformers.adapters.training.AdapterArguments) class integrated into adapter-transformers provides a set of command-line options useful for training adapters. +The [`AdapterArguments`](transformers.adapters.training.AdapterArguments) class integrated into `adapter-transformers` provides a set of command-line options useful for training adapters. These include options such as `--train_adapter` for activating adapter training and `--load_adapter` for loading adapters from checkpoints. Thus, the first step of integrating adapters is to add these arguments to the line where `HfArgumentParser` is instantiated: @@ -43,17 +43,17 @@ model = AutoAdapterModel.from_pretrained( model.add_classification_head(data_args.task_name, num_labels=num_labels) ``` -Note that this change is entirely optional and training will also work with the original model class. -Learn more about the benefits of AdapterModel classes [here](prediction_heads.md) +Note that this change is optional and training will also work with the original model class. +Learn more about the benefits of AdapterModel classes [here](prediction_heads.md). ### Step C - Setup adapter methods ```{eval-rst} .. tip:: - In the following, we show how to setup adapters manually. In most cases, you can use the built-in ``setup_adapter_training()`` method to perform this job automatically. Just add a statement similar to this anywhere between model instantiation and training start in your script: ``setup_adapter_training(model, adapter_args, task_name)`` + In the following, we show how to set up adapters manually. In most cases, you can use the built-in ``setup_adapter_training()`` method to perform this job automatically. Just add a statement similar to this anywhere between model instantiation and training start in your script: ``setup_adapter_training(model, adapter_args, task_name)`` ``` -Compared to fine-tuning the full model, there is only this one significant adaptation we have to make: adding an adapter setup and activating it. +Compared to fine-tuning the entire model, we have to make only one significant adaptation: adding an adapter setup and activating it. ```python # task adapter - only add if not existing @@ -69,14 +69,14 @@ model.train_adapter(task_name) ```{eval-rst} .. important:: The most crucial step when training an adapter module is to freeze all weights in the model except for those of the - adapter. In the previous snippet, this is achieved by calling the ``train_adapter()`` method which disables training + adapter. In the previous snippet, this is achieved by calling the ``train_adapter()`` method, which disables training of all weights outside the task adapter. In case you want to unfreeze all model weights later on, you can use ``freeze_model(False)``. ``` Besides this, we only have to make sure that the task adapter and prediction head are activated so that they are used in every forward pass. To specify the adapter modules to use, we can use the `model.set_active_adapters()` method and pass the adapter setup. If you only use a single adapter, you can simply pass the name of the adapter. For more information -on complex setups checkout the [Composition Blocks](https://docs.adapterhub.ml/adapter_composition.html). +on complex setups, checkout the [Composition Blocks](https://docs.adapterhub.ml/adapter_composition.html). ```python model.set_active_adapters(task_name) @@ -84,18 +84,18 @@ model.set_active_adapters(task_name) ### Step D - Switch to `AdapterTrainer` class -Finally, we switch the `Trainer` class built into Transformers for adapter-transformers' [`AdapterTrainer`](transformers.adapters.AdapterTrainer) class that is optimized for training adapter methods. +Finally, we exchange the `Trainer` class built into Transformers for adapter-transformers' [`AdapterTrainer`](transformers.adapters.AdapterTrainer) class that is optimized for training adapter methods. See [below for more information](#adaptertrainer). Technically, this change is not required as no changes to the training loop are required for training adapters. -However, `AdapterTrainer` e.g. provides better support for checkpointing and reloading adapter weights. +However, `AdapterTrainer` e.g., provides better support for checkpointing and reloading adapter weights. ### Step E - Start training The rest of the training procedure does not require any further changes in code. You can find the full version of the modified training script for GLUE at [run_glue.py](https://github.com/Adapter-Hub/adapter-transformers/blob/master/examples/pytorch/text-classification/run_glue.py) in the `examples` folder of our repository. -We also adapted [various other example scripts](https://github.com/Adapter-Hub/adapter-transformers/tree/master/examples/pytorch) (e.g. `run_glue.py`, `run_multiple_choice.py`, `run_squad.py`, ...) to support adapter training. +We also adapted [various other example scripts](https://github.com/Adapter-Hub/adapter-transformers/tree/master/examples/pytorch) (e.g., `run_glue.py`, `run_multiple_choice.py`, `run_squad.py`, ...) to support adapter training. To start adapter training on a GLUE task, you can run something similar to: @@ -117,16 +117,16 @@ python run_glue.py \ --adapter_config pfeiffer ``` -The important flag here is `--train_adapter` which switches from fine-tuning the full model to training an adapter module for the given GLUE task. +The important flag here is `--train_adapter`, which switches from fine-tuning the entire model to training an adapter module for the given GLUE task. ```{eval-rst} .. tip:: - Adapter weights are usually initialized randomly. That is why we require a higher learning rate. We have found that a default adapter learning rate of ``1e-4`` works well for most settings. + Adapter weights are usually initialized randomly, which is why we require a higher learning rate. We have found that a default adapter learning rate of ``1e-4`` works well for most settings. ``` ```{eval-rst} .. tip:: - Depending on your data set size you might also need to train longer than usual. To avoid overfitting you can evaluating the adapters after each epoch on the development set and only save the best model. + Depending on your data set size, you might also need to train longer than usual. To avoid overfitting, you can evaluate the adapters after each epoch on the development set and only save the best model. ``` ## Train a Language Adapter @@ -160,12 +160,12 @@ You can adapt this script to train AdapterFusion with different pre-trained adap ```{eval-rst} .. important:: - AdapterFusion on a target task is trained in a second training stage, after independently training adapters on individual tasks. + AdapterFusion on a target task is trained in a second training stage after independently training adapters on individual tasks. When setting up a fusion architecture on your model, make sure to load the pre-trained adapter modules to be fused using ``model.load_adapter()`` before adding a fusion layer. For more on AdapterFusion, also refer to `Pfeiffer et al., 2020 `_. ``` -To start fusion training on SST-2 as target task, you can run something like the following: +To start fusion training on SST-2 as the target task, you can run something like the following: ``` export GLUE_DIR=/path/to/glue @@ -188,9 +188,9 @@ python run_fusion_glue.py \ ## AdapterTrainer -Similar to the `Trainer` class provided by HuggingFace, adapter-transformers provides an `AdapterTrainer` class. This class is only +Similar to the `Trainer` class provided by HuggingFace, `adapter-transformers` provides an `AdapterTrainer` class. This class is only intended for training adapters. The `Trainer` class should still be used to fully fine-tune models. To train adapters with the `AdapterTrainer` -class, simply initialize it the same way you would initialize the `Trainer` class e.g.: +class, simply initialize it the same way you would initialize the `Trainer` class, e.g.: ```python model.add_adapter(task_name)