Debian Codegraph @

examples/by_feature/early_stopping.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
16 import evaluate
17 import torch
18 from datasets import load_dataset
19 from torch.optim import AdamW
20 from torch.utils.data import DataLoader
21 from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
22
23 from accelerate import Accelerator, DistributedType
24
25
26 ########################################################################
27 # This is a fully working simple example to use Accelerate
28 # specifically showcasing how to perform early stopping,
29 # and builds off the `nlp_example.py` script
30 #
31 # This example trains a Bert base model on GLUE MRPC
32 # in any of the following settings (with the same script):
33 # - single CPU or single GPU
34 # - multi GPUS (using PyTorch distributed mode)
35 # - (multi) TPUs
36 # - fp16 (mixed-precision) or fp32 (normal precision)
37 #
38 # To run it in each of these various modes, follow the instructions
39 # in the readme for examples:
40 # https://github.com/huggingface/accelerate/tree/main/examples
41 #
42 ########################################################################
43
44
45 MAX_GPU_BATCH_SIZE = 16
46 EVAL_BATCH_SIZE = 32
47
48
49 def get_dataloaders(accelerator: Accelerator, batch_size: int = 16):
50 """
51 Creates a set of `DataLoader`s for the `glue` dataset,
52 using "bert-base-cased" 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("bert-base-cased")
61 datasets = load_dataset("nyu-mll/glue", "mrpc")
62
63 def tokenize_function(examples):
64 # max_length=None => use the model max length (it's actually the default)
65 outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None)
66 return outputs
67
68 # Apply the method we just defined to all the examples in all the splits of the dataset
69 # starting with the main process first:
70 with accelerator.main_process_first():
71 tokenized_datasets = datasets.map(
72 tokenize_function,
73 batched=True,
74 remove_columns=["idx", "sentence1", "sentence2"],
75 )
76
77 # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
78 # transformers library
79 tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
80
81 def collate_fn(examples):
82 # On TPU it's best to pad everything to the same length or training will be very slow.
83 max_length = 128 if accelerator.distributed_type == DistributedType.XLA else None
84 # When using mixed precision we want round multiples of 8/16
85 if accelerator.mixed_precision == "fp8":
86 pad_to_multiple_of = 16
87 elif accelerator.mixed_precision != "no":
88 pad_to_multiple_of = 8
89 else:
90 pad_to_multiple_of = None
91
92 return tokenizer.pad(
93 examples,
94 padding="longest",
95 max_length=max_length,
96 pad_to_multiple_of=pad_to_multiple_of,
97 return_tensors="pt",
98 )
99
100 # Instantiate dataloaders.
101 train_dataloader = DataLoader(
102 tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size, drop_last=True
103 )
104 eval_dataloader = DataLoader(
105 tokenized_datasets["validation"],
106 shuffle=False,
107 collate_fn=collate_fn,
108 batch_size=EVAL_BATCH_SIZE,
109 drop_last=(accelerator.mixed_precision == "fp8"),
110 )
111
112 return train_dataloader, eval_dataloader
113
114
115 # New code
116 class EarlyStoppingCallback:
117 "A callback class that helps with early stopping"
118
119 def __init__(self, min_delta=0, patience=5):
120 self.min_delta = min_delta
121 self.patience = patience
122 self.counter = 0
123 self.lowest_loss = float("inf")
124
125 def check_early_stopping(self, eval_loss):
126 delta = self.lowest_loss - eval_loss
127 if delta >= self.min_delta:
128 self.lowest_loss = eval_loss
129 self.counter = 0
130 else:
131 self.counter += 1
132 if self.counter >= self.patience:
133 return True
134 return False
135
136
137 callback = EarlyStoppingCallback()
138
139
140 def training_function(config, args):
141 # Initialize accelerator
142 accelerator = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision)
143 # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
144 lr = config["lr"]
145 num_epochs = int(config["num_epochs"])
146 seed = int(config["seed"])
147 batch_size = int(config["batch_size"])
148
149 metric = evaluate.load("glue", "mrpc")
150
151 # If the batch size is too big we use gradient accumulation
152 gradient_accumulation_steps = 1
153 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.XLA:
154 gradient_accumulation_steps = batch_size // MAX_GPU_BATCH_SIZE
155 batch_size = MAX_GPU_BATCH_SIZE
156
157 set_seed(seed)
158 train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size)
159 # Instantiate the model (we build the model here so that the seed also control new weights initialization)
160 model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True)
161
162 # We could avoid this line since the accelerator is set with `device_placement=True` (default value).
163 # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
164 # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
165 model = model.to(accelerator.device)
166 # Instantiate optimizer
167 optimizer = AdamW(params=model.parameters(), lr=lr)
168
169 # Instantiate scheduler
170 lr_scheduler = get_linear_schedule_with_warmup(
171 optimizer=optimizer,
172 num_warmup_steps=100,
173 num_training_steps=(len(train_dataloader) * num_epochs) // gradient_accumulation_steps,
174 )
175
176 # Prepare everything
177 # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
178 # prepare method.
179
180 model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
181 model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
182 )
183
184 # Now we train the model
185 for epoch in range(num_epochs):
186 model.train()
187 for step, batch in enumerate(train_dataloader):
188 # We could avoid this line since we set the accelerator with `device_placement=True`.
189 batch.to(accelerator.device)
190 outputs = model(**batch)
191 loss = outputs.loss
192 loss = loss / gradient_accumulation_steps
193 accelerator.backward(loss)
194 if step % gradient_accumulation_steps == 0:
195 optimizer.step()
196 lr_scheduler.step()
197 optimizer.zero_grad()
198
199 # New code
200 # Check if we should stop the training on any processes
201 if callback.check_early_stopping(loss.item()):
202 accelerator.set_trigger()
203
204 # If so, we break the loop
205 if accelerator.check_trigger():
206 break
207
208 model.eval()
209 for step, batch in enumerate(eval_dataloader):
210 # We could avoid this line since we set the accelerator with `device_placement=True`.
211 batch.to(accelerator.device)
212 with torch.no_grad():
213 outputs = model(**batch)
214 predictions = outputs.logits.argmax(dim=-1)
215 predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"]))
216 metric.add_batch(
217 predictions=predictions,
218 references=references,
219 )
220
221 eval_metric = metric.compute()
222
223 # Use accelerator.print to print only on the main process.
224 accelerator.print(f"epoch {epoch}:", eval_metric)
225 accelerator.end_training()
226
227
228 def main():
229 parser = argparse.ArgumentParser(description="Simple example of training script.")
230 parser.add_argument(
231 "--mixed_precision",
232 type=str,
233 default=None,
234 choices=["no", "fp16", "bf16", "fp8"],
235 help="Whether to use mixed precision. Choose"
236 "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
237 "and an Nvidia Ampere GPU.",
238 )
239 parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.")
240 args = parser.parse_args()
241 config = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16}
242 training_function(config, args)
243
244
245 if __name__ == "__main__":
246 main()