Debian Codegraph @

examples/by_feature/multi_process_metrics.py

raw
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 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, DistributedType
25
26
27 ########################################################################
28 # This is a fully working simple example to use Accelerate,
29 # specifically showcasing how to properly calculate the metrics on the
30 # validation dataset when in a distributed system, and builds off the
31 # `nlp_example.py` script.
32 #
33 # This example trains a Bert base model on GLUE MRPC
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 help focus on the differences in the code, building `DataLoaders`
41 # was refactored into its own function.
42 # New additions from the base script can be found quickly by
43 # looking for the # New Code # tags
44 #
45 # To run it in each of these various modes, follow the instructions
46 # in the readme for examples:
47 # https://github.com/huggingface/accelerate/tree/main/examples
48 #
49 ########################################################################
50
51
52 MAX_GPU_BATCH_SIZE = 16
53 EVAL_BATCH_SIZE = 32
54
55
56 def get_dataloaders(accelerator: Accelerator, batch_size: int = 16):
57 """
58 Creates a set of `DataLoader`s for the `glue` dataset,
59 using "bert-base-cased" as the tokenizer.
60
61 Args:
62 accelerator (`Accelerator`):
63 An `Accelerator` object
64 batch_size (`int`, *optional*):
65 The batch size for the train and validation DataLoaders.
66 """
67 tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
68 datasets = load_dataset("nyu-mll/glue", "mrpc")
69
70 def tokenize_function(examples):
71 # max_length=None => use the model max length (it's actually the default)
72 outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None)
73 return outputs
74
75 # Apply the method we just defined to all the examples in all the splits of the dataset
76 # starting with the main process first:
77 with accelerator.main_process_first():
78 tokenized_datasets = datasets.map(
79 tokenize_function,
80 batched=True,
81 remove_columns=["idx", "sentence1", "sentence2"],
82 )
83
84 # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
85 # transformers library
86 tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
87
88 def collate_fn(examples):
89 # On TPU it's best to pad everything to the same length or training will be very slow.
90 max_length = 128 if accelerator.distributed_type == DistributedType.XLA else None
91 # When using mixed precision we want round multiples of 8/16
92 if accelerator.mixed_precision == "fp8":
93 pad_to_multiple_of = 16
94 elif accelerator.mixed_precision != "no":
95 pad_to_multiple_of = 8
96 else:
97 pad_to_multiple_of = None
98
99 return tokenizer.pad(
100 examples,
101 padding="longest",
102 max_length=max_length,
103 pad_to_multiple_of=pad_to_multiple_of,
104 return_tensors="pt",
105 )
106
107 # Instantiate dataloaders.
108 train_dataloader = DataLoader(
109 tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size
110 )
111 eval_dataloader = DataLoader(
112 tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE
113 )
114
115 return train_dataloader, eval_dataloader
116
117
118 # For testing only
119 if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
120 from accelerate.test_utils.training import mocked_dataloaders
121
122 get_dataloaders = mocked_dataloaders # noqa: F811
123
124
125 def training_function(config, args):
126 # For testing only
127 if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
128 config["num_epochs"] = 2
129 # Initialize accelerator
130 accelerator = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision)
131 # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
132 lr = config["lr"]
133 num_epochs = int(config["num_epochs"])
134 seed = int(config["seed"])
135 batch_size = int(config["batch_size"])
136
137 metric = evaluate.load("glue", "mrpc")
138
139 # If the batch size is too big we use gradient accumulation
140 gradient_accumulation_steps = 1
141 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.XLA:
142 gradient_accumulation_steps = batch_size // MAX_GPU_BATCH_SIZE
143 batch_size = MAX_GPU_BATCH_SIZE
144
145 set_seed(seed)
146 train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size)
147 # Instantiate the model (we build the model here so that the seed also control new weights initialization)
148 model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True)
149
150 # We could avoid this line since the accelerator is set with `device_placement=True` (default value).
151 # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
152 # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
153 model = model.to(accelerator.device)
154
155 # Instantiate optimizer
156 optimizer = AdamW(params=model.parameters(), lr=lr)
157
158 # Instantiate scheduler
159 lr_scheduler = get_linear_schedule_with_warmup(
160 optimizer=optimizer,
161 num_warmup_steps=100,
162 num_training_steps=(len(train_dataloader) * num_epochs) // gradient_accumulation_steps,
163 )
164
165 # Prepare everything
166 # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
167 # prepare method.
168 model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
169 model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
170 )
171
172 # Now we train the model
173 for epoch in range(num_epochs):
174 model.train()
175 for step, batch in enumerate(train_dataloader):
176 # We could avoid this line since we set the accelerator with `device_placement=True`.
177 batch.to(accelerator.device)
178 outputs = model(**batch)
179 loss = outputs.loss
180 loss = loss / gradient_accumulation_steps
181 accelerator.backward(loss)
182 if step % gradient_accumulation_steps == 0:
183 optimizer.step()
184 lr_scheduler.step()
185 optimizer.zero_grad()
186
187 model.eval()
188 samples_seen = 0
189 for step, batch in enumerate(eval_dataloader):
190 # We could avoid this line since we set the accelerator with `device_placement=True`.
191 batch.to(accelerator.device)
192 with torch.no_grad():
193 outputs = model(**batch)
194 predictions = outputs.logits.argmax(dim=-1)
195 predictions, references = accelerator.gather((predictions, batch["labels"]))
196 # New Code #
197 # First we check if it's a distributed system
198 if accelerator.use_distributed:
199 # Then see if we're on the last batch of our eval dataloader
200 if step == len(eval_dataloader) - 1:
201 # Last batch needs to be truncated on distributed systems as it contains additional samples
202 predictions = predictions[: len(eval_dataloader.dataset) - samples_seen]
203 references = references[: len(eval_dataloader.dataset) - samples_seen]
204 else:
205 # Otherwise we add the number of samples seen
206 samples_seen += references.shape[0]
207 # All of this can be avoided if you use `Accelerator.gather_for_metrics` instead of `Accelerator.gather`:
208 # accelerator.gather_for_metrics((predictions, batch["labels"]))
209 metric.add_batch(
210 predictions=predictions,
211 references=references,
212 )
213
214 eval_metric = metric.compute()
215 # Use accelerator.print to print only on the main process.
216 accelerator.print(f"epoch {epoch}:", eval_metric)
217 accelerator.end_training()
218
219
220 def main():
221 parser = argparse.ArgumentParser(description="Simple example of training script.")
222 parser.add_argument(
223 "--mixed_precision",
224 type=str,
225 default=None,
226 choices=["no", "fp16", "bf16", "fp8"],
227 help="Whether to use mixed precision. Choose"
228 "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
229 "and an Nvidia Ampere GPU.",
230 )
231 parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.")
232 args = parser.parse_args()
233 config = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16}
234 training_function(config, args)
235
236
237 if __name__ == "__main__":
238 main()