| 1 |
# Copyright 2024 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 contextlib |
| 16 |
import math |
| 17 |
import os |
| 18 |
|
| 19 |
import torch |
| 20 |
from datasets import load_dataset |
| 21 |
from torch.optim import AdamW |
| 22 |
from torch.utils.data import DataLoader |
| 23 |
from transformers import AutoModelForCausalLM, AutoTokenizer, get_constant_schedule, set_seed |
| 24 |
|
| 25 |
from accelerate import Accelerator, DistributedType |
| 26 |
|
| 27 |
|
| 28 |
######################################################################## |
| 29 |
# This is a fully working simple example to use Accelerate |
| 30 |
# and perform gradient accumulation on samples of variable size |
| 31 |
# |
| 32 |
# This example trains a SmolLM base model on WikiText-2 v1 |
| 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 |
EVAL_BATCH_SIZE = 32 |
| 47 |
|
| 48 |
|
| 49 |
def get_dataloaders(accelerator: Accelerator, batch_size: int = 16, max_training_samples=500): |
| 50 |
""" |
| 51 |
Creates a set of `DataLoader`s for the `Salesforce/wikitext` dataset, |
| 52 |
using "HuggingFaceTB/SmolLM-360M" as the tokenizer. |
| 53 |
|
| 54 |
Args: |
| 55 |
accelerator (`Accelerator`): |
| 56 |
An `Accelerator` object |
| 57 |
batch_size (`int`, *optional*): |
| 58 |
The batch size for the train and validation DataLoaders. |
| 59 |
""" |
| 60 |
tokenizer = AutoTokenizer.from_pretrained("HuggingFaceTB/SmolLM-360M") |
| 61 |
tokenizer.pad_token = tokenizer.eos_token |
| 62 |
with accelerator.local_main_process_first(): |
| 63 |
datasets = load_dataset("Salesforce/wikitext", "wikitext-2-v1") |
| 64 |
datasets["train"] = datasets["train"].select(range(max_training_samples)) |
| 65 |
|
| 66 |
def tokenize_function(examples): |
| 67 |
# max_length=None => use the model max length (it's actually the default) |
| 68 |
outputs = tokenizer(examples["text"], truncation=True, max_length=None, return_attention_mask=False) |
| 69 |
return outputs |
| 70 |
|
| 71 |
# Filter out empty texts |
| 72 |
with accelerator.main_process_first(): |
| 73 |
datasets = datasets.filter( |
| 74 |
lambda x: len(x) > 0, |
| 75 |
input_columns="text", |
| 76 |
) |
| 77 |
|
| 78 |
# Apply the method we just defined to all the examples in all the splits of the dataset |
| 79 |
# starting with the main process first: |
| 80 |
with accelerator.main_process_first(): |
| 81 |
tokenized_datasets = datasets.map( |
| 82 |
tokenize_function, |
| 83 |
batched=True, |
| 84 |
remove_columns=["text"], |
| 85 |
) |
| 86 |
|
| 87 |
# Filter out empty samples |
| 88 |
with accelerator.main_process_first(): |
| 89 |
tokenized_datasets = tokenized_datasets.filter( |
| 90 |
lambda x: len(x) > 0, |
| 91 |
input_columns="input_ids", |
| 92 |
) |
| 93 |
|
| 94 |
def collate_fn(examples): |
| 95 |
# On TPU it's best to pad everything to the same length or training will be very slow. |
| 96 |
max_length = ( |
| 97 |
128 |
| 98 |
if accelerator.distributed_type == DistributedType.XLA |
| 99 |
else max([len(e["input_ids"]) for e in examples]) |
| 100 |
) |
| 101 |
# When using mixed precision we want round multiples of 8/16 |
| 102 |
if accelerator.mixed_precision == "fp8": |
| 103 |
pad_to_multiple_of = 16 |
| 104 |
elif accelerator.mixed_precision != "no": |
| 105 |
pad_to_multiple_of = 8 |
| 106 |
else: |
| 107 |
pad_to_multiple_of = None |
| 108 |
|
| 109 |
batch = tokenizer.pad( |
| 110 |
examples, |
| 111 |
padding="max_length", |
| 112 |
max_length=max_length + 1, |
| 113 |
pad_to_multiple_of=pad_to_multiple_of, |
| 114 |
return_tensors="pt", |
| 115 |
) |
| 116 |
|
| 117 |
batch["labels"] = batch["input_ids"][:, 1:] |
| 118 |
batch["input_ids"] = batch["input_ids"][:, :-1] |
| 119 |
if "attention_mask" in batch: |
| 120 |
batch["attention_mask"] = batch["attention_mask"][:, :-1] |
| 121 |
|
| 122 |
batch["labels"] = torch.where(batch["labels"] == tokenizer.pad_token_id, -100, batch["labels"]) |
| 123 |
|
| 124 |
return batch |
| 125 |
|
| 126 |
# Instantiate dataloaders. |
| 127 |
train_dataloader = DataLoader( |
| 128 |
tokenized_datasets["train"], shuffle=False, collate_fn=collate_fn, batch_size=batch_size |
| 129 |
) |
| 130 |
eval_dataloader = DataLoader( |
| 131 |
tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE |
| 132 |
) |
| 133 |
|
| 134 |
return train_dataloader, eval_dataloader |
| 135 |
|
| 136 |
|
| 137 |
# For testing only |
| 138 |
if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": |
| 139 |
from accelerate.test_utils.training import mocked_dataloaders_for_autoregressive_models |
| 140 |
|
| 141 |
get_dataloaders = mocked_dataloaders_for_autoregressive_models # noqa: F811 |
| 142 |
|
| 143 |
|
| 144 |
def training_function(config, args): |
| 145 |
# For testing only |
| 146 |
if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": |
| 147 |
config["num_epochs"] = 2 |
| 148 |
|
| 149 |
gradient_accumulation_steps = int(args.gradient_accumulation_steps) |
| 150 |
# Initialize accelerator |
| 151 |
if args.with_wandb_tracking: |
| 152 |
accelerator = Accelerator( |
| 153 |
cpu=args.cpu, |
| 154 |
mixed_precision=args.mixed_precision, |
| 155 |
gradient_accumulation_steps=gradient_accumulation_steps, |
| 156 |
log_with="wandb", |
| 157 |
) |
| 158 |
else: |
| 159 |
accelerator = Accelerator( |
| 160 |
cpu=args.cpu, mixed_precision=args.mixed_precision, gradient_accumulation_steps=gradient_accumulation_steps |
| 161 |
) |
| 162 |
if accelerator.distributed_type == DistributedType.XLA and gradient_accumulation_steps > 1: |
| 163 |
raise NotImplementedError( |
| 164 |
"Gradient accumulation on TPUs is currently not supported. Pass `gradient_accumulation_steps=1`" |
| 165 |
) |
| 166 |
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs |
| 167 |
lr = config["lr"] |
| 168 |
num_epochs = int(config["num_epochs"]) |
| 169 |
seed = int(config["seed"]) |
| 170 |
batch_size = int(config["batch_size"]) |
| 171 |
max_grad_norm = config["max_grad_norm"] |
| 172 |
|
| 173 |
# We need to initialize the trackers we use, and also store our configuration |
| 174 |
if args.with_wandb_tracking: |
| 175 |
run = os.path.split(__file__)[-1].split(".")[0] |
| 176 |
run_name = f"{accelerator.num_processes}GPU-grad{gradient_accumulation_steps}-bs{batch_size}" |
| 177 |
accelerator.init_trackers( |
| 178 |
run, |
| 179 |
config, |
| 180 |
init_kwargs={"wandb": {"name": run_name}}, |
| 181 |
) |
| 182 |
|
| 183 |
set_seed(seed) |
| 184 |
train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size) |
| 185 |
# Instantiate the model (we build the model here so that the seed also control new weights initialization) |
| 186 |
model = AutoModelForCausalLM.from_pretrained("HuggingFaceTB/SmolLM-360M") |
| 187 |
|
| 188 |
# We could avoid this line since the accelerator is set with `device_placement=True` (default value). |
| 189 |
# Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer |
| 190 |
# creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). |
| 191 |
model = model.to(accelerator.device) |
| 192 |
|
| 193 |
# Instantiate optimizer |
| 194 |
optimizer = AdamW(params=model.parameters(), lr=lr) |
| 195 |
|
| 196 |
# Instantiate scheduler |
| 197 |
lr_scheduler = get_constant_schedule( |
| 198 |
optimizer=optimizer, |
| 199 |
) |
| 200 |
|
| 201 |
# Prepare everything |
| 202 |
# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the |
| 203 |
# prepare method. |
| 204 |
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare( |
| 205 |
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler |
| 206 |
) |
| 207 |
|
| 208 |
num_samples_in_epoch = len(train_dataloader) |
| 209 |
remainder = num_samples_in_epoch % gradient_accumulation_steps |
| 210 |
remainder = remainder if remainder != 0 else gradient_accumulation_steps |
| 211 |
total_gradient_updates = math.ceil(num_samples_in_epoch / gradient_accumulation_steps) |
| 212 |
|
| 213 |
total_batched_samples = 0 |
| 214 |
# Now we train the model |
| 215 |
for epoch in range(num_epochs): |
| 216 |
model.train() |
| 217 |
training_iterator = iter(train_dataloader) |
| 218 |
for update_step in range(total_gradient_updates): |
| 219 |
# In order to correctly the total number of non-padded tokens on which we'll compute the cross-entropy loss |
| 220 |
# we need to pre-load the full local batch - i.e the next per_device_batch_size * accumulation_steps samples |
| 221 |
batch_samples = [] |
| 222 |
num_batches_in_step = ( |
| 223 |
gradient_accumulation_steps if update_step != (total_gradient_updates - 1) else remainder |
| 224 |
) |
| 225 |
for _ in range(num_batches_in_step): |
| 226 |
batch_samples += [next(training_iterator)] |
| 227 |
# get local num items in batch |
| 228 |
local_num_items_in_batch = sum([(batch["labels"].ne(-100)).sum() for batch in batch_samples]) |
| 229 |
|
| 230 |
# to compute it correctly in a multi-device DDP training, we need to gather the total number of items in the full batch. |
| 231 |
num_items_in_batch = accelerator.gather(local_num_items_in_batch).sum().item() |
| 232 |
losses = [] |
| 233 |
for i, batch in enumerate(batch_samples): |
| 234 |
# if we perform gradient accumulation in a multi-devices set-up, we want to avoid unecessary communications when accumulating |
| 235 |
# cf: https://muellerzr.github.io/blog/gradient_accumulation.html |
| 236 |
ctx = ( |
| 237 |
model.no_sync |
| 238 |
if (i < len(batch_samples) - 1 and accelerator.num_processes > 1) |
| 239 |
else contextlib.nullcontext |
| 240 |
) |
| 241 |
with ctx(): |
| 242 |
total_batched_samples += 1 |
| 243 |
|
| 244 |
outputs = model(**batch, use_cache=False, num_items_in_batch=num_items_in_batch) |
| 245 |
loss = outputs.loss |
| 246 |
|
| 247 |
# We multiply by num_processes because the DDP calculates the average gradient across all devices whereas dividing by num_items_in_batch already takes into account all devices |
| 248 |
# Same reason for gradient_accumulation_steps, but this times it's Accelerate that calculate the average gradient across the accumulated steps |
| 249 |
# Because the loss is already divided by `num_items_in_batch` in the `transformers` code, we don't need to do it again |
| 250 |
loss = loss * gradient_accumulation_steps * accelerator.num_processes |
| 251 |
accelerator.backward(loss) |
| 252 |
losses.append(loss.detach()) |
| 253 |
|
| 254 |
# Sync gradients and perform optimization steps once every gradient_accumulation_steps |
| 255 |
grad_norm = accelerator.clip_grad_norm_(model.parameters(), max_grad_norm) |
| 256 |
optimizer.step() |
| 257 |
lr_scheduler.step() |
| 258 |
optimizer.zero_grad() |
| 259 |
|
| 260 |
losses = accelerator.gather(sum(losses)).sum().item() / ( |
| 261 |
accelerator.num_processes * gradient_accumulation_steps |
| 262 |
) |
| 263 |
|
| 264 |
grad_norm = grad_norm.detach().item() if isinstance(grad_norm, torch.Tensor) else grad_norm |
| 265 |
accelerator.print( |
| 266 |
f"epoch {epoch} - update step {update_step}:: grad norm: {grad_norm} ::train loss: {losses}" |
| 267 |
) |
| 268 |
if args.with_wandb_tracking: |
| 269 |
accelerator.log( |
| 270 |
{ |
| 271 |
"train/grad_norm": grad_norm, |
| 272 |
"train/epoch": epoch, |
| 273 |
"train/loss": losses, |
| 274 |
}, |
| 275 |
step=update_step + total_gradient_updates * epoch, |
| 276 |
) |
| 277 |
model.eval() |
| 278 |
losses = [] |
| 279 |
for step, batch in enumerate(eval_dataloader): |
| 280 |
with torch.no_grad(): |
| 281 |
outputs = model(**batch, use_cache=False) |
| 282 |
eval_loss = outputs.loss |
| 283 |
losses.append(accelerator.gather_for_metrics(loss.repeat(EVAL_BATCH_SIZE))) |
| 284 |
|
| 285 |
losses = torch.cat(losses) |
| 286 |
try: |
| 287 |
eval_loss = torch.mean(losses) |
| 288 |
perplexity = math.exp(eval_loss) |
| 289 |
except OverflowError: |
| 290 |
perplexity = float("inf") |
| 291 |
|
| 292 |
# Use accelerator.print to print only on the main process. |
| 293 |
accelerator.print(f"epoch {epoch}:: eval perplexity: {perplexity} eval_loss: {eval_loss}") |
| 294 |
if args.with_wandb_tracking: |
| 295 |
accelerator.log( |
| 296 |
{ |
| 297 |
"eval/perplexity": perplexity, |
| 298 |
"eval/loss": eval_loss, |
| 299 |
"eval/epoch": epoch, |
| 300 |
}, |
| 301 |
step=update_step + total_gradient_updates * epoch, |
| 302 |
) |
| 303 |
accelerator.end_training() |
| 304 |
|
| 305 |
|
| 306 |
def main(): |
| 307 |
parser = argparse.ArgumentParser(description="Simple example of training script.") |
| 308 |
parser.add_argument( |
| 309 |
"--mixed_precision", |
| 310 |
type=str, |
| 311 |
default=None, |
| 312 |
choices=["no", "fp16", "bf16", "fp8"], |
| 313 |
help="Whether to use mixed precision. Choose" |
| 314 |
"between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10." |
| 315 |
"and an Nvidia Ampere GPU.", |
| 316 |
) |
| 317 |
|
| 318 |
parser.add_argument( |
| 319 |
"--gradient_accumulation_steps", |
| 320 |
type=int, |
| 321 |
default=1, |
| 322 |
help="The number of minibatches to be ran before gradients are accumulated.", |
| 323 |
) |
| 324 |
parser.add_argument( |
| 325 |
"--per_device_batch_size", |
| 326 |
type=int, |
| 327 |
default=2, |
| 328 |
help="The size of each minibatch", |
| 329 |
) |
| 330 |
|
| 331 |
parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.") |
| 332 |
parser.add_argument( |
| 333 |
"--with_wandb_tracking", |
| 334 |
action="store_true", |
| 335 |
help="Whether to load in wandb from the environment and use them for logging.", |
| 336 |
) |
| 337 |
args = parser.parse_args() |
| 338 |
config = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": args.per_device_batch_size, "max_grad_norm": 1.0} |
| 339 |
training_function(config, args) |
| 340 |
|
| 341 |
|
| 342 |
if __name__ == "__main__": |
| 343 |
main() |