Debian Codegraph @

examples/by_feature/schedule_free.py

raw
1 # Copyright 2024 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.utils.data import DataLoader
21 from transformers import AutoModelForSequenceClassification, AutoTokenizer, set_seed
22
23 from accelerate import Accelerator, DistributedType
24 from accelerate.utils import is_schedulefree_available
25
26
27 if is_schedulefree_available():
28 import schedulefree
29 else:
30 raise ImportError(
31 "This example requires the `schedulefree` library. Please install it with `pip install schedulefree`"
32 )
33
34
35 ########################################################################
36 # This is a fully working simple example to use Accelerate and Facebook's
37 # scheduler-free optimizer: https://github.com/facebookresearch/schedule_free/
38 #
39 # This example trains a Bert base model on GLUE MRPC
40 # in any of the following settings (with the same script):
41 # - single CPU or single GPU
42 # - multi GPUS (using PyTorch distributed mode)
43 # - (multi) TPUs
44 # - fp16 (mixed-precision) or fp32 (normal precision)
45 #
46 # To run it in each of these various modes, follow the instructions
47 # in the readme for examples:
48 # https://github.com/huggingface/accelerate/tree/main/examples
49 #
50 ########################################################################
51
52
53 MAX_GPU_BATCH_SIZE = 16
54 EVAL_BATCH_SIZE = 32
55
56
57 def get_dataloaders(accelerator: Accelerator, batch_size: int = 16):
58 """
59 Creates a set of `DataLoader`s for the `glue` dataset,
60 using "bert-base-cased" as the tokenizer.
61
62 Args:
63 accelerator (`Accelerator`):
64 An `Accelerator` object
65 batch_size (`int`, *optional*):
66 The batch size for the train and validation DataLoaders.
67 """
68 tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
69 datasets = load_dataset("nyu-mll/glue", "mrpc")
70
71 def tokenize_function(examples):
72 # max_length=None => use the model max length (it's actually the default)
73 outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None)
74 return outputs
75
76 # Apply the method we just defined to all the examples in all the splits of the dataset
77 # starting with the main process first:
78 with accelerator.main_process_first():
79 tokenized_datasets = datasets.map(
80 tokenize_function,
81 batched=True,
82 remove_columns=["idx", "sentence1", "sentence2"],
83 )
84
85 # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
86 # transformers library
87 tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
88
89 def collate_fn(examples):
90 # For Torchxla, it's best to pad everything to the same length or training will be very slow.
91 max_length = 128 if accelerator.distributed_type == DistributedType.XLA else None
92 # When using mixed precision we want round multiples of 8/16
93 if accelerator.mixed_precision == "fp8":
94 pad_to_multiple_of = 16
95 elif accelerator.mixed_precision != "no":
96 pad_to_multiple_of = 8
97 else:
98 pad_to_multiple_of = None
99
100 return tokenizer.pad(
101 examples,
102 padding="longest",
103 max_length=max_length,
104 pad_to_multiple_of=pad_to_multiple_of,
105 return_tensors="pt",
106 )
107
108 # Instantiate dataloaders.
109 train_dataloader = DataLoader(
110 tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size, drop_last=True
111 )
112 eval_dataloader = DataLoader(
113 tokenized_datasets["validation"],
114 shuffle=False,
115 collate_fn=collate_fn,
116 batch_size=EVAL_BATCH_SIZE,
117 drop_last=(accelerator.mixed_precision == "fp8"),
118 )
119
120 return train_dataloader, eval_dataloader
121
122
123 # For testing only
124
125
126 if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
127 from accelerate.test_utils.training import mocked_dataloaders
128
129 get_dataloaders = mocked_dataloaders # noqa: F811
130
131
132 def training_function(config, args):
133 # Initialize accelerator
134 accelerator = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision)
135 # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
136 lr = config["lr"]
137 num_epochs = int(config["num_epochs"])
138 seed = int(config["seed"])
139 batch_size = int(config["batch_size"])
140
141 metric = evaluate.load("glue", "mrpc")
142
143 # If the batch size is too big we use gradient accumulation
144 gradient_accumulation_steps = 1
145 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.XLA:
146 gradient_accumulation_steps = batch_size // MAX_GPU_BATCH_SIZE
147 batch_size = MAX_GPU_BATCH_SIZE
148
149 set_seed(seed)
150 train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size)
151 # Instantiate the model (we build the model here so that the seed also control new weights initialization)
152 model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True)
153
154 # We could avoid this line since the accelerator is set with `device_placement=True` (default value).
155 # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
156 # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
157 model = model.to(accelerator.device)
158 # Instantiate optimizer with warmup steps
159 optimizer = schedulefree.AdamWScheduleFree(
160 model.parameters(),
161 lr=lr,
162 warmup_steps=100,
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
169 model, optimizer, train_dataloader, eval_dataloader = accelerator.prepare(
170 model, optimizer, train_dataloader, eval_dataloader
171 )
172
173 # Now we train the model
174 for epoch in range(num_epochs):
175 model.train()
176 optimizer.train()
177 for step, batch in enumerate(train_dataloader):
178 # We could avoid this line since we set the accelerator with `device_placement=True`.
179 batch.to(accelerator.device)
180 outputs = model(**batch)
181 loss = outputs.loss
182 loss = loss / gradient_accumulation_steps
183 accelerator.backward(loss)
184 if step % gradient_accumulation_steps == 0:
185 optimizer.step()
186 optimizer.zero_grad()
187
188 model.eval()
189 optimizer.eval()
190 for step, batch in enumerate(eval_dataloader):
191 # We could avoid this line since we set the accelerator with `device_placement=True`.
192 batch.to(accelerator.device)
193 with torch.no_grad():
194 outputs = model(**batch)
195 predictions = outputs.logits.argmax(dim=-1)
196 predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"]))
197 metric.add_batch(
198 predictions=predictions,
199 references=references,
200 )
201
202 eval_metric = metric.compute()
203 # Use accelerator.print to print only on the main process.
204 accelerator.print(f"epoch {epoch}:", eval_metric)
205 accelerator.end_training()
206
207
208 def main():
209 parser = argparse.ArgumentParser(description="Simple example of training script.")
210 parser.add_argument(
211 "--mixed_precision",
212 type=str,
213 default=None,
214 choices=["no", "fp16", "bf16", "fp8"],
215 help="Whether to use mixed precision. Choose"
216 "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
217 "and an Nvidia Ampere GPU.",
218 )
219 parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.")
220 args = parser.parse_args()
221 config = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16}
222 training_function(config, args)
223
224
225 if __name__ == "__main__":
226 main()