| 1 |
# Copyright 2021 The HuggingFace Inc. team. All rights reserved. |
| 2 |
# |
| 3 |
# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
# you may not use this file except in compliance with the License. |
| 5 |
# You may obtain a copy of the License at |
| 6 |
# |
| 7 |
# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
# |
| 9 |
# Unless required by applicable law or agreed to in writing, software |
| 10 |
# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
# See the License for the specific language governing permissions and |
| 13 |
# limitations under the License. |
| 14 |
import argparse |
| 15 |
import os |
| 16 |
|
| 17 |
import evaluate |
| 18 |
import torch |
| 19 |
from datasets import load_dataset |
| 20 |
from torch.optim import AdamW |
| 21 |
from torch.utils.data import DataLoader |
| 22 |
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed |
| 23 |
|
| 24 |
from accelerate import Accelerator, DistributedType |
| 25 |
|
| 26 |
|
| 27 |
######################################################################## |
| 28 |
# This is a fully working simple example to use Accelerate, |
| 29 |
# specifically showcasing the experiment tracking capability, |
| 30 |
# and builds off the `nlp_example.py` script. |
| 31 |
# |
| 32 |
# This example trains a Bert base model on GLUE MRPC |
| 33 |
# in any of the following settings (with the same script): |
| 34 |
# - single CPU or single GPU |
| 35 |
# - multi GPUS (using PyTorch distributed mode) |
| 36 |
# - (multi) TPUs |
| 37 |
# - fp16 (mixed-precision) or fp32 (normal precision) |
| 38 |
# |
| 39 |
# To help focus on the differences in the code, building `DataLoaders` |
| 40 |
# was refactored into its own function. |
| 41 |
# New additions from the base script can be found quickly by |
| 42 |
# looking for the # New Code # tags |
| 43 |
# |
| 44 |
# To run it in each of these various modes, follow the instructions |
| 45 |
# in the readme for examples: |
| 46 |
# https://github.com/huggingface/accelerate/tree/main/examples |
| 47 |
# |
| 48 |
######################################################################## |
| 49 |
|
| 50 |
MAX_GPU_BATCH_SIZE = 16 |
| 51 |
EVAL_BATCH_SIZE = 32 |
| 52 |
|
| 53 |
|
| 54 |
def get_dataloaders(accelerator: Accelerator, batch_size: int = 16): |
| 55 |
""" |
| 56 |
Creates a set of `DataLoader`s for the `glue` dataset, |
| 57 |
using "bert-base-cased" as the tokenizer. |
| 58 |
|
| 59 |
Args: |
| 60 |
accelerator (`Accelerator`): |
| 61 |
An `Accelerator` object |
| 62 |
batch_size (`int`, *optional*): |
| 63 |
The batch size for the train and validation DataLoaders. |
| 64 |
""" |
| 65 |
tokenizer = AutoTokenizer.from_pretrained("bert-base-cased") |
| 66 |
datasets = load_dataset("nyu-mll/glue", "mrpc") |
| 67 |
|
| 68 |
def tokenize_function(examples): |
| 69 |
# max_length=None => use the model max length (it's actually the default) |
| 70 |
outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None) |
| 71 |
return outputs |
| 72 |
|
| 73 |
# Apply the method we just defined to all the examples in all the splits of the dataset |
| 74 |
# starting with the main process first: |
| 75 |
with accelerator.main_process_first(): |
| 76 |
tokenized_datasets = datasets.map( |
| 77 |
tokenize_function, |
| 78 |
batched=True, |
| 79 |
remove_columns=["idx", "sentence1", "sentence2"], |
| 80 |
) |
| 81 |
|
| 82 |
# We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the |
| 83 |
# transformers library |
| 84 |
tokenized_datasets = tokenized_datasets.rename_column("label", "labels") |
| 85 |
|
| 86 |
def collate_fn(examples): |
| 87 |
# On TPU it's best to pad everything to the same length or training will be very slow. |
| 88 |
max_length = 128 if accelerator.distributed_type == DistributedType.XLA else None |
| 89 |
# When using mixed precision we want round multiples of 8/16 |
| 90 |
if accelerator.mixed_precision == "fp8": |
| 91 |
pad_to_multiple_of = 16 |
| 92 |
elif accelerator.mixed_precision != "no": |
| 93 |
pad_to_multiple_of = 8 |
| 94 |
else: |
| 95 |
pad_to_multiple_of = None |
| 96 |
|
| 97 |
return tokenizer.pad( |
| 98 |
examples, |
| 99 |
padding="longest", |
| 100 |
max_length=max_length, |
| 101 |
pad_to_multiple_of=pad_to_multiple_of, |
| 102 |
return_tensors="pt", |
| 103 |
) |
| 104 |
|
| 105 |
# Instantiate dataloaders. |
| 106 |
train_dataloader = DataLoader( |
| 107 |
tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size |
| 108 |
) |
| 109 |
eval_dataloader = DataLoader( |
| 110 |
tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE |
| 111 |
) |
| 112 |
|
| 113 |
return train_dataloader, eval_dataloader |
| 114 |
|
| 115 |
|
| 116 |
# For testing only |
| 117 |
if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": |
| 118 |
from accelerate.test_utils.training import mocked_dataloaders |
| 119 |
|
| 120 |
get_dataloaders = mocked_dataloaders # noqa: F811 |
| 121 |
|
| 122 |
|
| 123 |
def training_function(config, args): |
| 124 |
# For testing only |
| 125 |
if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": |
| 126 |
config["num_epochs"] = 2 |
| 127 |
# Initialize Accelerator |
| 128 |
|
| 129 |
# New Code # |
| 130 |
# We pass in "all" to `log_with` to grab all available trackers in the environment |
| 131 |
# Note: If using a custom `Tracker` class, should be passed in here such as: |
| 132 |
# >>> log_with = ["all", MyCustomTrackerClassInstance()] |
| 133 |
if args.with_tracking: |
| 134 |
accelerator = Accelerator( |
| 135 |
cpu=args.cpu, mixed_precision=args.mixed_precision, log_with="all", project_dir=args.project_dir |
| 136 |
) |
| 137 |
else: |
| 138 |
accelerator = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision) |
| 139 |
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs |
| 140 |
lr = config["lr"] |
| 141 |
num_epochs = int(config["num_epochs"]) |
| 142 |
seed = int(config["seed"]) |
| 143 |
batch_size = int(config["batch_size"]) |
| 144 |
set_seed(seed) |
| 145 |
|
| 146 |
train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size) |
| 147 |
metric = evaluate.load("glue", "mrpc") |
| 148 |
|
| 149 |
# If the batch size is too big we use gradient accumulation |
| 150 |
gradient_accumulation_steps = 1 |
| 151 |
if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.XLA: |
| 152 |
gradient_accumulation_steps = batch_size // MAX_GPU_BATCH_SIZE |
| 153 |
batch_size = MAX_GPU_BATCH_SIZE |
| 154 |
|
| 155 |
# Instantiate the model (we build the model here so that the seed also control new weights initialization) |
| 156 |
model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True) |
| 157 |
|
| 158 |
# We could avoid this line since the accelerator is set with `device_placement=True` (default value). |
| 159 |
# Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer |
| 160 |
# creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). |
| 161 |
model = model.to(accelerator.device) |
| 162 |
|
| 163 |
# Instantiate optimizer |
| 164 |
optimizer = AdamW(params=model.parameters(), lr=lr) |
| 165 |
|
| 166 |
# Instantiate scheduler |
| 167 |
lr_scheduler = get_linear_schedule_with_warmup( |
| 168 |
optimizer=optimizer, |
| 169 |
num_warmup_steps=100, |
| 170 |
num_training_steps=(len(train_dataloader) * num_epochs) // gradient_accumulation_steps, |
| 171 |
) |
| 172 |
|
| 173 |
# Prepare everything |
| 174 |
# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the |
| 175 |
# prepare method. |
| 176 |
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare( |
| 177 |
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler |
| 178 |
) |
| 179 |
|
| 180 |
# New Code # |
| 181 |
# We need to initialize the trackers we use. Overall configurations can also be stored |
| 182 |
if args.with_tracking: |
| 183 |
run = os.path.split(__file__)[-1].split(".")[0] |
| 184 |
accelerator.init_trackers(run, config) |
| 185 |
|
| 186 |
# Now we train the model |
| 187 |
for epoch in range(num_epochs): |
| 188 |
model.train() |
| 189 |
# New Code # |
| 190 |
# For our tracking example, we will log the total loss of each epoch |
| 191 |
if args.with_tracking: |
| 192 |
total_loss = 0 |
| 193 |
for step, batch in enumerate(train_dataloader): |
| 194 |
# We could avoid this line since we set the accelerator with `device_placement=True`. |
| 195 |
batch.to(accelerator.device) |
| 196 |
outputs = model(**batch) |
| 197 |
loss = outputs.loss |
| 198 |
# New Code # |
| 199 |
if args.with_tracking: |
| 200 |
total_loss += loss.detach().float() |
| 201 |
loss = loss / gradient_accumulation_steps |
| 202 |
accelerator.backward(loss) |
| 203 |
if step % gradient_accumulation_steps == 0: |
| 204 |
optimizer.step() |
| 205 |
lr_scheduler.step() |
| 206 |
optimizer.zero_grad() |
| 207 |
|
| 208 |
model.eval() |
| 209 |
for step, batch in enumerate(eval_dataloader): |
| 210 |
# We could avoid this line since we set the accelerator with `device_placement=True` (the default). |
| 211 |
batch.to(accelerator.device) |
| 212 |
with torch.no_grad(): |
| 213 |
outputs = model(**batch) |
| 214 |
predictions = outputs.logits.argmax(dim=-1) |
| 215 |
predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"])) |
| 216 |
metric.add_batch( |
| 217 |
predictions=predictions, |
| 218 |
references=references, |
| 219 |
) |
| 220 |
|
| 221 |
eval_metric = metric.compute() |
| 222 |
# Use accelerator.print to print only on the main process. |
| 223 |
accelerator.print(f"epoch {epoch}:", eval_metric) |
| 224 |
|
| 225 |
# New Code # |
| 226 |
# To actually log, we call `Accelerator.log` |
| 227 |
# The values passed can be of `str`, `int`, `float` or `dict` of `str` to `float`/`int` |
| 228 |
if args.with_tracking: |
| 229 |
accelerator.log( |
| 230 |
{ |
| 231 |
"accuracy": eval_metric["accuracy"], |
| 232 |
"f1": eval_metric["f1"], |
| 233 |
"train_loss": total_loss.item() / len(train_dataloader), |
| 234 |
"epoch": epoch, |
| 235 |
}, |
| 236 |
step=epoch, |
| 237 |
) |
| 238 |
|
| 239 |
accelerator.end_training() |
| 240 |
|
| 241 |
|
| 242 |
def main(): |
| 243 |
parser = argparse.ArgumentParser(description="Simple example of training script.") |
| 244 |
parser.add_argument( |
| 245 |
"--mixed_precision", |
| 246 |
type=str, |
| 247 |
default=None, |
| 248 |
choices=["no", "fp16", "bf16", "fp8"], |
| 249 |
help="Whether to use mixed precision. Choose" |
| 250 |
"between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10." |
| 251 |
"and an Nvidia Ampere GPU.", |
| 252 |
) |
| 253 |
parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.") |
| 254 |
parser.add_argument( |
| 255 |
"--with_tracking", |
| 256 |
action="store_true", |
| 257 |
help="Whether to load in all available experiment trackers from the environment and use them for logging.", |
| 258 |
) |
| 259 |
parser.add_argument( |
| 260 |
"--project_dir", |
| 261 |
type=str, |
| 262 |
default="logs", |
| 263 |
help="Location on where to store experiment tracking logs` and relevent project information", |
| 264 |
) |
| 265 |
args = parser.parse_args() |
| 266 |
config = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16} |
| 267 |
training_function(config, args) |
| 268 |
|
| 269 |
|
| 270 |
if __name__ == "__main__": |
| 271 |
main() |