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