| 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 |
from accelerate.utils import DDPCommunicationHookType, DistributedDataParallelKwargs |
| 26 |
|
| 27 |
|
| 28 |
######################################################################## |
| 29 |
# This is a fully working simple example to use Accelerate |
| 30 |
# and perform ddp communication hook |
| 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 run it in each of these various modes, follow the instructions |
| 40 |
# in the readme for examples: |
| 41 |
# https://github.com/huggingface/accelerate/tree/main/examples |
| 42 |
# |
| 43 |
######################################################################## |
| 44 |
|
| 45 |
|
| 46 |
MAX_GPU_BATCH_SIZE = 16 |
| 47 |
EVAL_BATCH_SIZE = 32 |
| 48 |
|
| 49 |
|
| 50 |
def get_dataloaders(accelerator: Accelerator, batch_size: int = 16): |
| 51 |
""" |
| 52 |
Creates a set of `DataLoader`s for the `glue` dataset, |
| 53 |
using "bert-base-cased" as the tokenizer. |
| 54 |
|
| 55 |
Args: |
| 56 |
accelerator (`Accelerator`): |
| 57 |
An `Accelerator` object |
| 58 |
batch_size (`int`, *optional*): |
| 59 |
The batch size for the train and validation DataLoaders. |
| 60 |
""" |
| 61 |
tokenizer = AutoTokenizer.from_pretrained("bert-base-cased") |
| 62 |
datasets = load_dataset("nyu-mll/glue", "mrpc") |
| 63 |
|
| 64 |
def tokenize_function(examples): |
| 65 |
# max_length=None => use the model max length (it's actually the default) |
| 66 |
outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None) |
| 67 |
return outputs |
| 68 |
|
| 69 |
# Apply the method we just defined to all the examples in all the splits of the dataset |
| 70 |
# starting with the main process first: |
| 71 |
with accelerator.main_process_first(): |
| 72 |
tokenized_datasets = datasets.map( |
| 73 |
tokenize_function, |
| 74 |
batched=True, |
| 75 |
remove_columns=["idx", "sentence1", "sentence2"], |
| 76 |
) |
| 77 |
|
| 78 |
# We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the |
| 79 |
# transformers library |
| 80 |
tokenized_datasets = tokenized_datasets.rename_column("label", "labels") |
| 81 |
|
| 82 |
def collate_fn(examples): |
| 83 |
# On TPU it's best to pad everything to the same length or training will be very slow. |
| 84 |
max_length = 128 if accelerator.distributed_type == DistributedType.XLA else None |
| 85 |
# When using mixed precision we want round multiples of 8/16 |
| 86 |
if accelerator.mixed_precision == "fp8": |
| 87 |
pad_to_multiple_of = 16 |
| 88 |
elif accelerator.mixed_precision != "no": |
| 89 |
pad_to_multiple_of = 8 |
| 90 |
else: |
| 91 |
pad_to_multiple_of = None |
| 92 |
|
| 93 |
return tokenizer.pad( |
| 94 |
examples, |
| 95 |
padding="longest", |
| 96 |
max_length=max_length, |
| 97 |
pad_to_multiple_of=pad_to_multiple_of, |
| 98 |
return_tensors="pt", |
| 99 |
) |
| 100 |
|
| 101 |
# Instantiate dataloaders. |
| 102 |
train_dataloader = DataLoader( |
| 103 |
tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size |
| 104 |
) |
| 105 |
eval_dataloader = DataLoader( |
| 106 |
tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE |
| 107 |
) |
| 108 |
|
| 109 |
return train_dataloader, eval_dataloader |
| 110 |
|
| 111 |
|
| 112 |
# For testing only |
| 113 |
if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": |
| 114 |
from accelerate.test_utils.training import mocked_dataloaders |
| 115 |
|
| 116 |
get_dataloaders = mocked_dataloaders # noqa: F811 |
| 117 |
|
| 118 |
|
| 119 |
def training_function(config, args): |
| 120 |
# For testing only |
| 121 |
if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": |
| 122 |
config["num_epochs"] = 2 |
| 123 |
# New Code # |
| 124 |
ddp_comm_hook_type = DDPCommunicationHookType(args.ddp_comm_hook) |
| 125 |
ddp_comm_wrapper = DDPCommunicationHookType(args.ddp_comm_wrapper) |
| 126 |
ddp_kwargs = DistributedDataParallelKwargs(comm_hook=ddp_comm_hook_type, comm_wrapper=ddp_comm_wrapper) |
| 127 |
# Initialize accelerator |
| 128 |
accelerator = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision, kwargs_handlers=[ddp_kwargs]) |
| 129 |
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs |
| 130 |
lr = config["lr"] |
| 131 |
num_epochs = int(config["num_epochs"]) |
| 132 |
seed = int(config["seed"]) |
| 133 |
batch_size = int(config["batch_size"]) |
| 134 |
|
| 135 |
metric = evaluate.load("glue", "mrpc") |
| 136 |
|
| 137 |
set_seed(seed) |
| 138 |
train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size) |
| 139 |
# Instantiate the model (we build the model here so that the seed also control new weights initialization) |
| 140 |
model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True) |
| 141 |
|
| 142 |
# We could avoid this line since the accelerator is set with `device_placement=True` (default value). |
| 143 |
# Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer |
| 144 |
# creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). |
| 145 |
model = model.to(accelerator.device) |
| 146 |
|
| 147 |
# Instantiate optimizer |
| 148 |
optimizer = AdamW(params=model.parameters(), lr=lr) |
| 149 |
|
| 150 |
# Instantiate scheduler |
| 151 |
lr_scheduler = get_linear_schedule_with_warmup( |
| 152 |
optimizer=optimizer, |
| 153 |
num_warmup_steps=100, |
| 154 |
num_training_steps=(len(train_dataloader) * num_epochs), |
| 155 |
) |
| 156 |
|
| 157 |
# Prepare everything |
| 158 |
# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the |
| 159 |
# prepare method. |
| 160 |
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare( |
| 161 |
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler |
| 162 |
) |
| 163 |
|
| 164 |
# Now we train the model |
| 165 |
for epoch in range(num_epochs): |
| 166 |
model.train() |
| 167 |
for step, batch in enumerate(train_dataloader): |
| 168 |
# We could avoid this line since we set the accelerator with `device_placement=True`. |
| 169 |
batch.to(accelerator.device) |
| 170 |
# We use the new `accumulate` context manager to perform gradient accumulation |
| 171 |
with accelerator.accumulate(model): |
| 172 |
output = model(**batch) |
| 173 |
loss = output.loss |
| 174 |
accelerator.backward(loss) |
| 175 |
optimizer.step() |
| 176 |
lr_scheduler.step() |
| 177 |
optimizer.zero_grad() |
| 178 |
|
| 179 |
model.eval() |
| 180 |
for step, batch in enumerate(eval_dataloader): |
| 181 |
# We could avoid this line since we set the accelerator with `device_placement=True`. |
| 182 |
batch.to(accelerator.device) |
| 183 |
with torch.no_grad(): |
| 184 |
outputs = model(**batch) |
| 185 |
predictions = outputs.logits.argmax(dim=-1) |
| 186 |
predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"])) |
| 187 |
metric.add_batch( |
| 188 |
predictions=predictions, |
| 189 |
references=references, |
| 190 |
) |
| 191 |
|
| 192 |
eval_metric = metric.compute() |
| 193 |
# Use accelerator.print to print only on the main process. |
| 194 |
accelerator.print(f"epoch {epoch}:", eval_metric) |
| 195 |
accelerator.end_training() |
| 196 |
|
| 197 |
|
| 198 |
def main(): |
| 199 |
parser = argparse.ArgumentParser(description="Simple example of training script.") |
| 200 |
parser.add_argument( |
| 201 |
"--mixed_precision", |
| 202 |
type=str, |
| 203 |
default=None, |
| 204 |
choices=["no", "fp16", "bf16", "fp8"], |
| 205 |
help="Whether to use mixed precision. Choose" |
| 206 |
"between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10." |
| 207 |
"and an Nvidia Ampere GPU.", |
| 208 |
) |
| 209 |
# New Code # |
| 210 |
parser.add_argument( |
| 211 |
"--ddp_comm_hook", |
| 212 |
type=str, |
| 213 |
default="no", |
| 214 |
choices=["no", "fp16", "bf16", "power_sgd", "batched_power_sgd"], |
| 215 |
help="DDP Communication hook to use. Choose between `no`, `fp16`, `bf16`, `power_sgd`, and `batched_power_sgd`.", |
| 216 |
) |
| 217 |
# New Code # |
| 218 |
parser.add_argument( |
| 219 |
"--ddp_comm_wrapper", |
| 220 |
type=str, |
| 221 |
default="no", |
| 222 |
choices=["no", "fp16", "bf16"], |
| 223 |
help="DDP Communication wrapper to use. Choose between `no`, `fp16`, and `bf16`.", |
| 224 |
) |
| 225 |
parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.") |
| 226 |
args = parser.parse_args() |
| 227 |
config = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16} |
| 228 |
training_function(config, args) |
| 229 |
|
| 230 |
|
| 231 |
if __name__ == "__main__": |
| 232 |
main() |