| 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 |
import re |
| 17 |
|
| 18 |
import numpy as np |
| 19 |
import PIL |
| 20 |
import torch |
| 21 |
from timm import create_model |
| 22 |
from torch.optim.lr_scheduler import OneCycleLR |
| 23 |
from torch.utils.data import DataLoader, Dataset |
| 24 |
from torchvision.transforms import Compose, RandomResizedCrop, Resize, ToTensor |
| 25 |
|
| 26 |
from accelerate import Accelerator |
| 27 |
from accelerate.utils import set_seed |
| 28 |
|
| 29 |
|
| 30 |
######################################################################## |
| 31 |
# This is a fully working simple example to use Accelerate |
| 32 |
# |
| 33 |
# This example trains a ResNet50 on the Oxford-IIT Pet Dataset |
| 34 |
# in any of the following settings (with the same script): |
| 35 |
# - single CPU or single GPU |
| 36 |
# - multi GPUS (using PyTorch distributed mode) |
| 37 |
# - (multi) TPUs |
| 38 |
# - fp16 (mixed-precision) or fp32 (normal precision) |
| 39 |
# |
| 40 |
# To run it in each of these various modes, follow the instructions |
| 41 |
# in the readme for examples: |
| 42 |
# https://github.com/huggingface/accelerate/tree/main/examples |
| 43 |
# |
| 44 |
######################################################################## |
| 45 |
|
| 46 |
|
| 47 |
# Function to get the label from the filename |
| 48 |
def extract_label(fname): |
| 49 |
stem = fname.split(os.path.sep)[-1] |
| 50 |
return re.search(r"^(.*)_\d+\.jpg$", stem).groups()[0] |
| 51 |
|
| 52 |
|
| 53 |
class PetsDataset(Dataset): |
| 54 |
def __init__(self, file_names, image_transform=None, label_to_id=None): |
| 55 |
self.file_names = file_names |
| 56 |
self.image_transform = image_transform |
| 57 |
self.label_to_id = label_to_id |
| 58 |
|
| 59 |
def __len__(self): |
| 60 |
return len(self.file_names) |
| 61 |
|
| 62 |
def __getitem__(self, idx): |
| 63 |
fname = self.file_names[idx] |
| 64 |
raw_image = PIL.Image.open(fname) |
| 65 |
image = raw_image.convert("RGB") |
| 66 |
if self.image_transform is not None: |
| 67 |
image = self.image_transform(image) |
| 68 |
label = extract_label(fname) |
| 69 |
if self.label_to_id is not None: |
| 70 |
label = self.label_to_id[label] |
| 71 |
return {"image": image, "label": label} |
| 72 |
|
| 73 |
|
| 74 |
def training_function(config, args): |
| 75 |
# Initialize accelerator |
| 76 |
accelerator = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision) |
| 77 |
|
| 78 |
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs |
| 79 |
lr = config["lr"] |
| 80 |
num_epochs = int(config["num_epochs"]) |
| 81 |
seed = int(config["seed"]) |
| 82 |
batch_size = int(config["batch_size"]) |
| 83 |
image_size = config["image_size"] |
| 84 |
if not isinstance(image_size, (list, tuple)): |
| 85 |
image_size = (image_size, image_size) |
| 86 |
|
| 87 |
# Grab all the image filenames |
| 88 |
file_names = [os.path.join(args.data_dir, fname) for fname in os.listdir(args.data_dir) if fname.endswith(".jpg")] |
| 89 |
|
| 90 |
# Build the label correspondences |
| 91 |
all_labels = [extract_label(fname) for fname in file_names] |
| 92 |
id_to_label = list(set(all_labels)) |
| 93 |
id_to_label.sort() |
| 94 |
label_to_id = {lbl: i for i, lbl in enumerate(id_to_label)} |
| 95 |
|
| 96 |
# Set the seed before splitting the data. |
| 97 |
set_seed(seed) |
| 98 |
# Split our filenames between train and validation |
| 99 |
random_perm = np.random.permutation(len(file_names)) |
| 100 |
cut = int(0.8 * len(file_names)) |
| 101 |
train_split = random_perm[:cut] |
| 102 |
eval_split = random_perm[cut:] |
| 103 |
|
| 104 |
# For training we use a simple RandomResizedCrop |
| 105 |
train_tfm = Compose([RandomResizedCrop(image_size, scale=(0.5, 1.0)), ToTensor()]) |
| 106 |
train_dataset = PetsDataset( |
| 107 |
[file_names[i] for i in train_split], image_transform=train_tfm, label_to_id=label_to_id |
| 108 |
) |
| 109 |
|
| 110 |
# For evaluation, we use a deterministic Resize |
| 111 |
eval_tfm = Compose([Resize(image_size), ToTensor()]) |
| 112 |
eval_dataset = PetsDataset([file_names[i] for i in eval_split], image_transform=eval_tfm, label_to_id=label_to_id) |
| 113 |
|
| 114 |
# Instantiate dataloaders. |
| 115 |
train_dataloader = DataLoader(train_dataset, shuffle=True, batch_size=batch_size, num_workers=4) |
| 116 |
eval_dataloader = DataLoader(eval_dataset, shuffle=False, batch_size=batch_size, num_workers=4) |
| 117 |
|
| 118 |
# Instantiate the model (we build the model here so that the seed also control new weights initialization) |
| 119 |
model = create_model("resnet50d", pretrained=True, num_classes=len(label_to_id)) |
| 120 |
|
| 121 |
# We could avoid this line since the accelerator is set with `device_placement=True` (default value). |
| 122 |
# Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer |
| 123 |
# creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). |
| 124 |
model = model.to(accelerator.device) |
| 125 |
|
| 126 |
# Freezing the base model |
| 127 |
for param in model.parameters(): |
| 128 |
param.requires_grad = False |
| 129 |
for param in model.get_classifier().parameters(): |
| 130 |
param.requires_grad = True |
| 131 |
|
| 132 |
# We normalize the batches of images to be a bit faster. |
| 133 |
mean = torch.tensor(model.default_cfg["mean"])[None, :, None, None].to(accelerator.device) |
| 134 |
std = torch.tensor(model.default_cfg["std"])[None, :, None, None].to(accelerator.device) |
| 135 |
|
| 136 |
# Instantiate optimizer |
| 137 |
optimizer = torch.optim.Adam(params=model.parameters(), lr=lr / 25) |
| 138 |
|
| 139 |
# Instantiate learning rate scheduler |
| 140 |
lr_scheduler = OneCycleLR(optimizer=optimizer, max_lr=lr, epochs=num_epochs, steps_per_epoch=len(train_dataloader)) |
| 141 |
|
| 142 |
# Prepare everything |
| 143 |
# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the |
| 144 |
# prepare method. |
| 145 |
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare( |
| 146 |
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler |
| 147 |
) |
| 148 |
|
| 149 |
# Now we train the model |
| 150 |
for epoch in range(num_epochs): |
| 151 |
model.train() |
| 152 |
for step, batch in enumerate(train_dataloader): |
| 153 |
# We could avoid this line since we set the accelerator with `device_placement=True`. |
| 154 |
batch = {k: v.to(accelerator.device) for k, v in batch.items()} |
| 155 |
inputs = (batch["image"] - mean) / std |
| 156 |
outputs = model(inputs) |
| 157 |
loss = torch.nn.functional.cross_entropy(outputs, batch["label"]) |
| 158 |
accelerator.backward(loss) |
| 159 |
optimizer.step() |
| 160 |
lr_scheduler.step() |
| 161 |
optimizer.zero_grad() |
| 162 |
|
| 163 |
model.eval() |
| 164 |
accurate = 0 |
| 165 |
num_elems = 0 |
| 166 |
for _, batch in enumerate(eval_dataloader): |
| 167 |
# We could avoid this line since we set the accelerator with `device_placement=True`. |
| 168 |
batch = {k: v.to(accelerator.device) for k, v in batch.items()} |
| 169 |
inputs = (batch["image"] - mean) / std |
| 170 |
with torch.no_grad(): |
| 171 |
outputs = model(inputs) |
| 172 |
predictions = outputs.argmax(dim=-1) |
| 173 |
predictions, references = accelerator.gather_for_metrics((predictions, batch["label"])) |
| 174 |
accurate_preds = predictions == references |
| 175 |
num_elems += accurate_preds.shape[0] |
| 176 |
accurate += accurate_preds.long().sum() |
| 177 |
|
| 178 |
eval_metric = accurate.item() / num_elems |
| 179 |
# Use accelerator.print to print only on the main process. |
| 180 |
accelerator.print(f"epoch {epoch}: {100 * eval_metric:.2f}") |
| 181 |
accelerator.end_training() |
| 182 |
|
| 183 |
|
| 184 |
def main(): |
| 185 |
parser = argparse.ArgumentParser(description="Simple example of training script.") |
| 186 |
parser.add_argument("--data_dir", required=True, help="The data folder on disk.") |
| 187 |
parser.add_argument( |
| 188 |
"--mixed_precision", |
| 189 |
type=str, |
| 190 |
default=None, |
| 191 |
choices=["no", "fp16", "bf16", "fp8"], |
| 192 |
help="Whether to use mixed precision. Choose" |
| 193 |
"between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10." |
| 194 |
"and an Nvidia Ampere GPU.", |
| 195 |
) |
| 196 |
parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.") |
| 197 |
args = parser.parse_args() |
| 198 |
config = {"lr": 3e-2, "num_epochs": 3, "seed": 42, "batch_size": 64, "image_size": 224} |
| 199 |
training_function(config, args) |
| 200 |
|
| 201 |
|
| 202 |
if __name__ == "__main__": |
| 203 |
main() |