| 1 |
# Copyright 2022 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 |
|
| 16 |
import evaluate |
| 17 |
import numpy as np |
| 18 |
import torch |
| 19 |
from datasets import DatasetDict, load_dataset |
| 20 |
|
| 21 |
# New Code # |
| 22 |
# We'll be using StratifiedKFold for this example |
| 23 |
from sklearn.model_selection import StratifiedKFold |
| 24 |
from torch.optim import AdamW |
| 25 |
from torch.utils.data import DataLoader |
| 26 |
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed |
| 27 |
|
| 28 |
from accelerate import Accelerator, DistributedType |
| 29 |
|
| 30 |
|
| 31 |
######################################################################## |
| 32 |
# This is a fully working simple example to use Accelerate, |
| 33 |
# specifically showcasing how to perform Cross Validation, |
| 34 |
# and builds off the `nlp_example.py` script. |
| 35 |
# |
| 36 |
# This example trains a Bert base model on GLUE MRPC |
| 37 |
# in any of the following settings (with the same script): |
| 38 |
# - single CPU or single GPU |
| 39 |
# - multi GPUS (using PyTorch distributed mode) |
| 40 |
# - (multi) TPUs |
| 41 |
# - fp16 (mixed-precision) or fp32 (normal precision) |
| 42 |
# |
| 43 |
# To help focus on the differences in the code, building `DataLoaders` |
| 44 |
# was refactored into its own function. |
| 45 |
# New additions from the base script can be found quickly by |
| 46 |
# looking for the # New Code # tags |
| 47 |
# |
| 48 |
# To run it in each of these various modes, follow the instructions |
| 49 |
# in the readme for examples: |
| 50 |
# https://github.com/huggingface/accelerate/tree/main/examples |
| 51 |
# |
| 52 |
######################################################################## |
| 53 |
|
| 54 |
|
| 55 |
MAX_GPU_BATCH_SIZE = 16 |
| 56 |
EVAL_BATCH_SIZE = 32 |
| 57 |
|
| 58 |
# New Code # |
| 59 |
# We need a different `get_dataloaders` function that will build dataloaders by index |
| 60 |
|
| 61 |
|
| 62 |
def get_fold_dataloaders( |
| 63 |
accelerator: Accelerator, dataset: DatasetDict, train_idxs: list[int], valid_idxs: list[int], batch_size: int = 16 |
| 64 |
): |
| 65 |
""" |
| 66 |
Gets a set of train, valid, and test dataloaders for a particular fold |
| 67 |
|
| 68 |
Args: |
| 69 |
accelerator (`Accelerator`): |
| 70 |
The main `Accelerator` object |
| 71 |
train_idxs (list of `int`): |
| 72 |
The split indices for the training dataset |
| 73 |
valid_idxs (list of `int`): |
| 74 |
The split indices for the validation dataset |
| 75 |
batch_size (`int`): |
| 76 |
The size of the minibatch. Default is 16 |
| 77 |
""" |
| 78 |
tokenizer = AutoTokenizer.from_pretrained("bert-base-cased") |
| 79 |
datasets = DatasetDict( |
| 80 |
{ |
| 81 |
"train": dataset["train"].select(train_idxs), |
| 82 |
"validation": dataset["train"].select(valid_idxs), |
| 83 |
"test": dataset["validation"], |
| 84 |
} |
| 85 |
) |
| 86 |
|
| 87 |
def tokenize_function(examples): |
| 88 |
# max_length=None => use the model max length (it's actually the default) |
| 89 |
outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None) |
| 90 |
return outputs |
| 91 |
|
| 92 |
# Apply the method we just defined to all the examples in all the splits of the dataset |
| 93 |
# starting with the main process first: |
| 94 |
with accelerator.main_process_first(): |
| 95 |
tokenized_datasets = datasets.map( |
| 96 |
tokenize_function, |
| 97 |
batched=True, |
| 98 |
remove_columns=["idx", "sentence1", "sentence2"], |
| 99 |
) |
| 100 |
|
| 101 |
# We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the |
| 102 |
# transformers library |
| 103 |
tokenized_datasets = tokenized_datasets.rename_column("label", "labels") |
| 104 |
|
| 105 |
def collate_fn(examples): |
| 106 |
# On TPU it's best to pad everything to the same length or training will be very slow. |
| 107 |
max_length = 128 if accelerator.distributed_type == DistributedType.XLA else None |
| 108 |
# When using mixed precision we want round multiples of 8/16 |
| 109 |
if accelerator.mixed_precision == "fp8": |
| 110 |
pad_to_multiple_of = 16 |
| 111 |
elif accelerator.mixed_precision != "no": |
| 112 |
pad_to_multiple_of = 8 |
| 113 |
else: |
| 114 |
pad_to_multiple_of = None |
| 115 |
|
| 116 |
return tokenizer.pad( |
| 117 |
examples, |
| 118 |
padding="longest", |
| 119 |
max_length=max_length, |
| 120 |
pad_to_multiple_of=pad_to_multiple_of, |
| 121 |
return_tensors="pt", |
| 122 |
) |
| 123 |
|
| 124 |
# Instantiate dataloaders. |
| 125 |
train_dataloader = DataLoader( |
| 126 |
tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size |
| 127 |
) |
| 128 |
eval_dataloader = DataLoader( |
| 129 |
tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE |
| 130 |
) |
| 131 |
|
| 132 |
test_dataloader = DataLoader( |
| 133 |
tokenized_datasets["test"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE |
| 134 |
) |
| 135 |
|
| 136 |
return train_dataloader, eval_dataloader, test_dataloader |
| 137 |
|
| 138 |
|
| 139 |
def training_function(config, args): |
| 140 |
# New Code # |
| 141 |
test_predictions = [] |
| 142 |
# Download the dataset |
| 143 |
datasets = load_dataset("nyu-mll/glue", "mrpc") |
| 144 |
# Create our splits |
| 145 |
kfold = StratifiedKFold(n_splits=int(args.num_folds)) |
| 146 |
# Initialize accelerator |
| 147 |
accelerator = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision) |
| 148 |
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs |
| 149 |
lr = config["lr"] |
| 150 |
num_epochs = int(config["num_epochs"]) |
| 151 |
seed = int(config["seed"]) |
| 152 |
batch_size = int(config["batch_size"]) |
| 153 |
|
| 154 |
metric = evaluate.load("glue", "mrpc") |
| 155 |
|
| 156 |
# If the batch size is too big we use gradient accumulation |
| 157 |
gradient_accumulation_steps = 1 |
| 158 |
if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.XLA: |
| 159 |
gradient_accumulation_steps = batch_size // MAX_GPU_BATCH_SIZE |
| 160 |
batch_size = MAX_GPU_BATCH_SIZE |
| 161 |
|
| 162 |
set_seed(seed) |
| 163 |
|
| 164 |
# New Code # |
| 165 |
# Create our folds: |
| 166 |
folds = kfold.split(np.zeros(datasets["train"].num_rows), datasets["train"]["label"]) |
| 167 |
test_references = [] |
| 168 |
# Iterate over them |
| 169 |
for i, (train_idxs, valid_idxs) in enumerate(folds): |
| 170 |
train_dataloader, eval_dataloader, test_dataloader = get_fold_dataloaders( |
| 171 |
accelerator, |
| 172 |
datasets, |
| 173 |
train_idxs, |
| 174 |
valid_idxs, |
| 175 |
) |
| 176 |
# Instantiate the model (we build the model here so that the seed also control new weights initialization) |
| 177 |
model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True) |
| 178 |
|
| 179 |
# We could avoid this line since the accelerator is set with `device_placement=True` (default value). |
| 180 |
# Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer |
| 181 |
# creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). |
| 182 |
model = model.to(accelerator.device) |
| 183 |
|
| 184 |
# Instantiate optimizer |
| 185 |
optimizer = AdamW(params=model.parameters(), lr=lr) |
| 186 |
|
| 187 |
# Instantiate scheduler |
| 188 |
lr_scheduler = get_linear_schedule_with_warmup( |
| 189 |
optimizer=optimizer, |
| 190 |
num_warmup_steps=100, |
| 191 |
num_training_steps=(len(train_dataloader) * num_epochs) // gradient_accumulation_steps, |
| 192 |
) |
| 193 |
|
| 194 |
# Prepare everything |
| 195 |
# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the |
| 196 |
# prepare method. |
| 197 |
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare( |
| 198 |
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler |
| 199 |
) |
| 200 |
|
| 201 |
# Now we train the model |
| 202 |
for epoch in range(num_epochs): |
| 203 |
model.train() |
| 204 |
for step, batch in enumerate(train_dataloader): |
| 205 |
# We could avoid this line since we set the accelerator with `device_placement=True`. |
| 206 |
batch.to(accelerator.device) |
| 207 |
outputs = model(**batch) |
| 208 |
loss = outputs.loss |
| 209 |
loss = loss / gradient_accumulation_steps |
| 210 |
accelerator.backward(loss) |
| 211 |
if step % gradient_accumulation_steps == 0: |
| 212 |
optimizer.step() |
| 213 |
lr_scheduler.step() |
| 214 |
optimizer.zero_grad() |
| 215 |
|
| 216 |
model.eval() |
| 217 |
for step, batch in enumerate(eval_dataloader): |
| 218 |
# We could avoid this line since we set the accelerator with `device_placement=True`. |
| 219 |
batch.to(accelerator.device) |
| 220 |
with torch.no_grad(): |
| 221 |
outputs = model(**batch) |
| 222 |
predictions = outputs.logits.argmax(dim=-1) |
| 223 |
predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"])) |
| 224 |
metric.add_batch( |
| 225 |
predictions=predictions, |
| 226 |
references=references, |
| 227 |
) |
| 228 |
|
| 229 |
eval_metric = metric.compute() |
| 230 |
# Use accelerator.print to print only on the main process. |
| 231 |
accelerator.print(f"epoch {epoch}:", eval_metric) |
| 232 |
|
| 233 |
# New Code # |
| 234 |
# We also run predictions on the test set at the very end |
| 235 |
fold_predictions = [] |
| 236 |
for step, batch in enumerate(test_dataloader): |
| 237 |
# We could avoid this line since we set the accelerator with `device_placement=True`. |
| 238 |
batch.to(accelerator.device) |
| 239 |
with torch.no_grad(): |
| 240 |
outputs = model(**batch) |
| 241 |
predictions = outputs.logits |
| 242 |
predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"])) |
| 243 |
fold_predictions.append(predictions.cpu()) |
| 244 |
if i == 0: |
| 245 |
# We need all of the test predictions |
| 246 |
test_references.append(references.cpu()) |
| 247 |
# Use accelerator.print to print only on the main process. |
| 248 |
test_predictions.append(torch.cat(fold_predictions, dim=0)) |
| 249 |
# We now need to release all our memory and get rid of the current model, optimizer, etc |
| 250 |
model, optimizer = accelerator.free_memory(model, optimizer) |
| 251 |
# New Code # |
| 252 |
# Finally we check the accuracy of our folded results: |
| 253 |
test_references = torch.cat(test_references, dim=0) |
| 254 |
preds = torch.stack(test_predictions, dim=0).sum(dim=0).div(int(args.num_folds)).argmax(dim=-1) |
| 255 |
test_metric = metric.compute(predictions=preds, references=test_references) |
| 256 |
accelerator.print("Average test metrics from all folds:", test_metric) |
| 257 |
accelerator.end_training() |
| 258 |
|
| 259 |
|
| 260 |
def main(): |
| 261 |
parser = argparse.ArgumentParser(description="Simple example of training script.") |
| 262 |
parser.add_argument( |
| 263 |
"--mixed_precision", |
| 264 |
type=str, |
| 265 |
default=None, |
| 266 |
choices=["no", "fp16", "bf16", "fp8"], |
| 267 |
help="Whether to use mixed precision. Choose" |
| 268 |
"between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10." |
| 269 |
"and an Nvidia Ampere GPU.", |
| 270 |
) |
| 271 |
parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.") |
| 272 |
# New Code # |
| 273 |
parser.add_argument("--num_folds", type=int, default=3, help="The number of splits to perform across the dataset") |
| 274 |
args = parser.parse_args() |
| 275 |
config = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16} |
| 276 |
training_function(config, args) |
| 277 |
|
| 278 |
|
| 279 |
if __name__ == "__main__": |
| 280 |
main() |