Debian Codegraph @

examples/complete_cv_example.py

raw
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, DataLoaderConfiguration
27 from accelerate.utils import is_xpu_available
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 dataloader_config = DataLoaderConfiguration(use_stateful_dataloader=args.use_stateful_dataloader)
77 if args.with_tracking:
78 accelerator = Accelerator(
79 cpu=args.cpu,
80 mixed_precision=args.mixed_precision,
81 log_with="all",
82 project_dir=args.project_dir,
83 dataloader_config=dataloader_config,
84 )
85 else:
86 accelerator = Accelerator(
87 cpu=args.cpu, mixed_precision=args.mixed_precision, dataloader_config=dataloader_config
88 )
89
90 # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
91 lr = config["lr"]
92 num_epochs = int(config["num_epochs"])
93 seed = int(config["seed"])
94 batch_size = int(config["batch_size"])
95 image_size = config["image_size"]
96 if not isinstance(image_size, (list, tuple)):
97 image_size = (image_size, image_size)
98
99 # Parse out whether we are saving every epoch or after a certain number of batches
100 if hasattr(args.checkpointing_steps, "isdigit"):
101 if args.checkpointing_steps == "epoch":
102 checkpointing_steps = args.checkpointing_steps
103 elif args.checkpointing_steps.isdigit():
104 checkpointing_steps = int(args.checkpointing_steps)
105 else:
106 raise ValueError(
107 f"Argument `checkpointing_steps` must be either a number or `epoch`. `{args.checkpointing_steps}` passed."
108 )
109 else:
110 checkpointing_steps = None
111
112 # We need to initialize the trackers we use, and also store our configuration
113 if args.with_tracking:
114 run = os.path.split(__file__)[-1].split(".")[0]
115 accelerator.init_trackers(run, config)
116
117 # Grab all the image filenames
118 file_names = [os.path.join(args.data_dir, fname) for fname in os.listdir(args.data_dir) if fname.endswith(".jpg")]
119
120 # Build the label correspondences
121 all_labels = [extract_label(fname) for fname in file_names]
122 id_to_label = list(set(all_labels))
123 id_to_label.sort()
124 label_to_id = {lbl: i for i, lbl in enumerate(id_to_label)}
125
126 # Set the seed before splitting the data.
127 np.random.seed(seed)
128 torch.manual_seed(seed)
129 if torch.cuda.is_available():
130 torch.cuda.manual_seed_all(seed)
131 elif is_xpu_available():
132 torch.xpu.manual_seed_all(seed)
133
134 # Split our filenames between train and validation
135 random_perm = np.random.permutation(len(file_names))
136 cut = int(0.8 * len(file_names))
137 train_split = random_perm[:cut]
138 eval_split = random_perm[cut:]
139
140 # For training we use a simple RandomResizedCrop
141 train_tfm = Compose([RandomResizedCrop(image_size, scale=(0.5, 1.0)), ToTensor()])
142 train_dataset = PetsDataset(
143 [file_names[i] for i in train_split], image_transform=train_tfm, label_to_id=label_to_id
144 )
145
146 # For evaluation, we use a deterministic Resize
147 eval_tfm = Compose([Resize(image_size), ToTensor()])
148 eval_dataset = PetsDataset([file_names[i] for i in eval_split], image_transform=eval_tfm, label_to_id=label_to_id)
149
150 # Instantiate dataloaders.
151 train_dataloader = DataLoader(train_dataset, shuffle=True, batch_size=batch_size, num_workers=4)
152 eval_dataloader = DataLoader(eval_dataset, shuffle=False, batch_size=batch_size, num_workers=4)
153
154 # Instantiate the model (we build the model here so that the seed also control new weights initialization)
155 model = create_model("resnet50d", pretrained=True, num_classes=len(label_to_id))
156
157 # We could avoid this line since the accelerator is set with `device_placement=True` (default value).
158 # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
159 # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
160 model = model.to(accelerator.device)
161
162 # Freezing the base model
163 for param in model.parameters():
164 param.requires_grad = False
165 for param in model.get_classifier().parameters():
166 param.requires_grad = True
167
168 # We normalize the batches of images to be a bit faster.
169 mean = torch.tensor(model.default_cfg["mean"])[None, :, None, None].to(accelerator.device)
170 std = torch.tensor(model.default_cfg["std"])[None, :, None, None].to(accelerator.device)
171
172 # Instantiate optimizer
173 optimizer = torch.optim.Adam(params=model.parameters(), lr=lr / 25)
174
175 # Instantiate learning rate scheduler
176 lr_scheduler = OneCycleLR(optimizer=optimizer, max_lr=lr, epochs=num_epochs, steps_per_epoch=len(train_dataloader))
177
178 # Prepare everything
179 # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
180 # prepare method.
181 model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
182 model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
183 )
184 # We need to keep track of how many total steps we have iterated over
185 overall_step = 0
186 # We also need to keep track of the starting epoch so files are named properly
187 starting_epoch = 0
188
189 # Potentially load in the weights and states from a previous save
190 if args.resume_from_checkpoint:
191 if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "":
192 accelerator.print(f"Resumed from checkpoint: {args.resume_from_checkpoint}")
193 accelerator.load_state(args.resume_from_checkpoint)
194 path = os.path.basename(args.resume_from_checkpoint)
195 else:
196 # Get the most recent checkpoint
197 dirs = [f.name for f in os.scandir(os.getcwd()) if f.is_dir()]
198 dirs.sort(key=os.path.getctime)
199 path = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last
200 # Extract `epoch_{i}` or `step_{i}`
201 training_difference = os.path.splitext(path)[0]
202
203 if "epoch" in training_difference:
204 starting_epoch = int(training_difference.replace("epoch_", "")) + 1
205 resume_step = None
206 else:
207 resume_step = int(training_difference.replace("step_", ""))
208 starting_epoch = resume_step // len(train_dataloader)
209 resume_step -= starting_epoch * len(train_dataloader)
210
211 # Now we train the model
212 for epoch in range(starting_epoch, num_epochs):
213 model.train()
214 if args.with_tracking:
215 total_loss = 0
216 if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None:
217 # We need to skip steps until we reach the resumed step
218 active_dataloader = accelerator.skip_first_batches(train_dataloader, resume_step)
219 overall_step += resume_step
220 else:
221 # After the first iteration though, we need to go back to the original dataloader
222 active_dataloader = train_dataloader
223 for batch in active_dataloader:
224 # We could avoid this line since we set the accelerator with `device_placement=True`.
225 batch = {k: v.to(accelerator.device) for k, v in batch.items()}
226 inputs = (batch["image"] - mean) / std
227 outputs = model(inputs)
228 loss = torch.nn.functional.cross_entropy(outputs, batch["label"])
229 # We keep track of the loss at each epoch
230 if args.with_tracking:
231 total_loss += loss.detach().float()
232 accelerator.backward(loss)
233 optimizer.step()
234 lr_scheduler.step()
235 optimizer.zero_grad()
236 overall_step += 1
237 if isinstance(checkpointing_steps, int):
238 output_dir = f"step_{overall_step}"
239 if overall_step % checkpointing_steps == 0:
240 if args.output_dir is not None:
241 output_dir = os.path.join(args.output_dir, output_dir)
242 accelerator.save_state(output_dir)
243 model.eval()
244 accurate = 0
245 num_elems = 0
246 for step, batch in enumerate(eval_dataloader):
247 # We could avoid this line since we set the accelerator with `device_placement=True`.
248 batch = {k: v.to(accelerator.device) for k, v in batch.items()}
249 inputs = (batch["image"] - mean) / std
250 with torch.no_grad():
251 outputs = model(inputs)
252 predictions = outputs.argmax(dim=-1)
253 predictions, references = accelerator.gather_for_metrics((predictions, batch["label"]))
254 accurate_preds = predictions == references
255 num_elems += accurate_preds.shape[0]
256 accurate += accurate_preds.long().sum()
257
258 eval_metric = accurate.item() / num_elems
259 # Use accelerator.print to print only on the main process.
260 accelerator.print(f"epoch {epoch}: {100 * eval_metric:.2f}")
261 if args.with_tracking:
262 accelerator.log(
263 {
264 "accuracy": 100 * eval_metric,
265 "train_loss": total_loss.item() / len(train_dataloader),
266 "epoch": epoch,
267 },
268 step=overall_step,
269 )
270 if checkpointing_steps == "epoch":
271 output_dir = f"epoch_{epoch}"
272 if args.output_dir is not None:
273 output_dir = os.path.join(args.output_dir, output_dir)
274 accelerator.save_state(output_dir)
275
276 accelerator.end_training()
277
278
279 def main():
280 parser = argparse.ArgumentParser(description="Simple example of training script.")
281 parser.add_argument("--data_dir", required=True, help="The data folder on disk.")
282 parser.add_argument("--fp16", action="store_true", help="If passed, will use FP16 training.")
283 parser.add_argument(
284 "--mixed_precision",
285 type=str,
286 default=None,
287 choices=["no", "fp16", "bf16", "fp8"],
288 help="Whether to use mixed precision. Choose"
289 "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
290 "and an Nvidia Ampere GPU.",
291 )
292 parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.")
293 parser.add_argument(
294 "--checkpointing_steps",
295 type=str,
296 default=None,
297 help="Whether the various states should be saved at the end of every n steps, or 'epoch' for each epoch.",
298 )
299 parser.add_argument(
300 "--output_dir",
301 type=str,
302 default=".",
303 help="Optional save directory where all checkpoint folders will be stored. Default is the current working directory.",
304 )
305 parser.add_argument(
306 "--resume_from_checkpoint",
307 type=str,
308 default=None,
309 help="If the training should continue from a checkpoint folder.",
310 )
311 parser.add_argument(
312 "--use_stateful_dataloader",
313 action="store_true",
314 help="If the dataloader should be a resumable stateful dataloader.",
315 )
316 parser.add_argument(
317 "--with_tracking",
318 action="store_true",
319 help="Whether to load in all available experiment trackers from the environment and use them for logging.",
320 )
321 parser.add_argument(
322 "--project_dir",
323 type=str,
324 default="logs",
325 help="Location on where to store experiment tracking logs` and relevent project information",
326 )
327 args = parser.parse_args()
328 config = {"lr": 3e-2, "num_epochs": 3, "seed": 42, "batch_size": 64, "image_size": 224}
329 training_function(config, args)
330
331
332 if __name__ == "__main__":
333 main()