Debian Codegraph @

examples/complete_nlp_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
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, DataLoaderConfiguration, DistributedType
25
26
27 ########################################################################
28 # This is a fully working simple example to use Accelerate
29 #
30 # This example trains a Bert base model on GLUE MRPC
31 # in any of the following settings (with the same script):
32 # - single CPU or single GPU
33 # - multi GPUS (using PyTorch distributed mode)
34 # - (multi) TPUs
35 # - fp16 (mixed-precision) or fp32 (normal precision)
36 #
37 # This example also demonstrates the checkpointing and sharding capabilities
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 MAX_GPU_BATCH_SIZE = 16
47 EVAL_BATCH_SIZE = 32
48
49
50 def training_function(config, args):
51 # Initialize accelerator
52 dataloader_config = DataLoaderConfiguration(use_stateful_dataloader=args.use_stateful_dataloader)
53 if args.with_tracking:
54 accelerator = Accelerator(
55 cpu=args.cpu,
56 mixed_precision=args.mixed_precision,
57 dataloader_config=dataloader_config,
58 log_with="all",
59 project_dir=args.project_dir,
60 )
61 else:
62 accelerator = Accelerator(
63 cpu=args.cpu, mixed_precision=args.mixed_precision, dataloader_config=dataloader_config
64 )
65
66 if hasattr(args.checkpointing_steps, "isdigit"):
67 if args.checkpointing_steps == "epoch":
68 checkpointing_steps = args.checkpointing_steps
69 elif args.checkpointing_steps.isdigit():
70 checkpointing_steps = int(args.checkpointing_steps)
71 else:
72 raise ValueError(
73 f"Argument `checkpointing_steps` must be either a number or `epoch`. `{args.checkpointing_steps}` passed."
74 )
75 else:
76 checkpointing_steps = None
77 # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
78 lr = config["lr"]
79 num_epochs = int(config["num_epochs"])
80 seed = int(config["seed"])
81 batch_size = int(config["batch_size"])
82
83 # We need to initialize the trackers we use, and also store our configuration
84 if args.with_tracking:
85 run = os.path.split(__file__)[-1].split(".")[0]
86 accelerator.init_trackers(run, config)
87
88 tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
89 datasets = load_dataset("nyu-mll/glue", "mrpc")
90 metric = evaluate.load("glue", "mrpc")
91
92 def tokenize_function(examples):
93 # max_length=None => use the model max length (it's actually the default)
94 outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None)
95 return outputs
96
97 # Apply the method we just defined to all the examples in all the splits of the dataset
98 # starting with the main process first:
99 with accelerator.main_process_first():
100 tokenized_datasets = datasets.map(
101 tokenize_function,
102 batched=True,
103 remove_columns=["idx", "sentence1", "sentence2"],
104 )
105
106 # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
107 # transformers library
108 tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
109
110 # If the batch size is too big we use gradient accumulation
111 gradient_accumulation_steps = 1
112 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.XLA:
113 gradient_accumulation_steps = batch_size // MAX_GPU_BATCH_SIZE
114 batch_size = MAX_GPU_BATCH_SIZE
115
116 def collate_fn(examples):
117 # On TPU it's best to pad everything to the same length or training will be very slow.
118 max_length = 128 if accelerator.distributed_type == DistributedType.XLA else None
119 # When using mixed precision we want round multiples of 8/16
120 if accelerator.mixed_precision == "fp8":
121 pad_to_multiple_of = 16
122 elif accelerator.mixed_precision != "no":
123 pad_to_multiple_of = 8
124 else:
125 pad_to_multiple_of = None
126
127 return tokenizer.pad(
128 examples,
129 padding="longest",
130 max_length=max_length,
131 pad_to_multiple_of=pad_to_multiple_of,
132 return_tensors="pt",
133 )
134
135 # Instantiate dataloaders.
136 train_dataloader = DataLoader(
137 tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size
138 )
139 eval_dataloader = DataLoader(
140 tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE
141 )
142
143 set_seed(seed)
144
145 # Instantiate the model (we build the model here so that the seed also control new weights initialization)
146 model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True)
147
148 # We could avoid this line since the accelerator is set with `device_placement=True` (default value).
149 # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
150 # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
151 model = model.to(accelerator.device)
152
153 # Instantiate optimizer
154 optimizer = AdamW(params=model.parameters(), lr=lr)
155
156 # Instantiate scheduler
157 lr_scheduler = get_linear_schedule_with_warmup(
158 optimizer=optimizer,
159 num_warmup_steps=100,
160 num_training_steps=(len(train_dataloader) * num_epochs) // gradient_accumulation_steps,
161 )
162
163 # Prepare everything
164 # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
165 # prepare method.
166 model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
167 model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
168 )
169
170 # We need to keep track of how many total steps we have iterated over
171 overall_step = 0
172 # We also need to keep track of the stating epoch so files are named properly
173 starting_epoch = 0
174
175 # Potentially load in the weights and states from a previous save
176 if args.resume_from_checkpoint:
177 if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "":
178 accelerator.print(f"Resumed from checkpoint: {args.resume_from_checkpoint}")
179 accelerator.load_state(args.resume_from_checkpoint)
180 path = os.path.basename(args.resume_from_checkpoint)
181 else:
182 # Get the most recent checkpoint
183 dirs = [f.name for f in os.scandir(os.getcwd()) if f.is_dir()]
184 dirs.sort(key=os.path.getctime)
185 path = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last
186 # Extract `epoch_{i}` or `step_{i}`
187 training_difference = os.path.splitext(path)[0]
188
189 if "epoch" in training_difference:
190 starting_epoch = int(training_difference.replace("epoch_", "")) + 1
191 resume_step = None
192 else:
193 resume_step = int(training_difference.replace("step_", ""))
194 starting_epoch = resume_step // len(train_dataloader)
195 resume_step -= starting_epoch * len(train_dataloader)
196
197 # Now we train the model
198 for epoch in range(starting_epoch, num_epochs):
199 model.train()
200 if args.with_tracking:
201 total_loss = 0
202 if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None:
203 # We need to skip steps until we reach the resumed step
204 if not args.use_stateful_dataloader:
205 active_dataloader = accelerator.skip_first_batches(train_dataloader, resume_step)
206 else:
207 active_dataloader = train_dataloader
208 overall_step += resume_step
209 else:
210 # After the first iteration though, we need to go back to the original dataloader
211 active_dataloader = train_dataloader
212 for step, batch in enumerate(active_dataloader):
213 # We could avoid this line since we set the accelerator with `device_placement=True`.
214 batch.to(accelerator.device)
215 outputs = model(**batch)
216 loss = outputs.loss
217 loss = loss / gradient_accumulation_steps
218 # We keep track of the loss at each epoch
219 if args.with_tracking:
220 total_loss += loss.detach().float()
221 accelerator.backward(loss)
222 if step % gradient_accumulation_steps == 0:
223 optimizer.step()
224 lr_scheduler.step()
225 optimizer.zero_grad()
226
227 overall_step += 1
228
229 if isinstance(checkpointing_steps, int):
230 output_dir = f"step_{overall_step}"
231 if overall_step % checkpointing_steps == 0:
232 if args.output_dir is not None:
233 output_dir = os.path.join(args.output_dir, output_dir)
234 accelerator.save_state(output_dir)
235
236 model.eval()
237 for step, batch in enumerate(eval_dataloader):
238 # We could avoid this line since we set the accelerator with `device_placement=True`.
239 batch.to(accelerator.device)
240 with torch.no_grad():
241 outputs = model(**batch)
242 predictions = outputs.logits.argmax(dim=-1)
243 predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"]))
244 metric.add_batch(
245 predictions=predictions,
246 references=references,
247 )
248
249 eval_metric = metric.compute()
250 # Use accelerator.print to print only on the main process.
251 accelerator.print(f"epoch {epoch}:", eval_metric)
252 if args.with_tracking:
253 accelerator.log(
254 {
255 "accuracy": eval_metric["accuracy"],
256 "f1": eval_metric["f1"],
257 "train_loss": total_loss.item() / len(train_dataloader),
258 "epoch": epoch,
259 },
260 step=epoch,
261 )
262
263 if checkpointing_steps == "epoch":
264 output_dir = f"epoch_{epoch}"
265 if args.output_dir is not None:
266 output_dir = os.path.join(args.output_dir, output_dir)
267 accelerator.save_state(output_dir)
268
269 accelerator.end_training()
270
271
272 def main():
273 parser = argparse.ArgumentParser(description="Simple example of training script.")
274 parser.add_argument(
275 "--mixed_precision",
276 type=str,
277 default=None,
278 choices=["no", "fp16", "bf16", "fp8"],
279 help="Whether to use mixed precision. Choose"
280 "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
281 "and an Nvidia Ampere GPU.",
282 )
283 parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.")
284 parser.add_argument(
285 "--checkpointing_steps",
286 type=str,
287 default=None,
288 help="Whether the various states should be saved at the end of every n steps, or 'epoch' for each epoch.",
289 )
290 parser.add_argument(
291 "--resume_from_checkpoint",
292 type=str,
293 default=None,
294 help="If the training should continue from a checkpoint folder.",
295 )
296 parser.add_argument(
297 "--use_stateful_dataloader",
298 action="store_true",
299 help="If the dataloader should be a resumable stateful dataloader.",
300 )
301 parser.add_argument(
302 "--with_tracking",
303 action="store_true",
304 help="Whether to load in all available experiment trackers from the environment and use them for logging.",
305 )
306 parser.add_argument(
307 "--output_dir",
308 type=str,
309 default=".",
310 help="Optional save directory where all checkpoint folders will be stored. Default is the current working directory.",
311 )
312 parser.add_argument(
313 "--project_dir",
314 type=str,
315 default="logs",
316 help="Location on where to store experiment tracking logs` and relevent project information",
317 )
318 args = parser.parse_args()
319 config = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16}
320 training_function(config, args)
321
322
323 if __name__ == "__main__":
324 main()