Debian Codegraph @

examples/by_feature/profiler.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.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 from accelerate.utils import ProfileKwargs
26
27
28 ########################################################################
29 # This is a fully working simple example to use Accelerate
30 # and perform profiling
31 #
32 # This example trains a Bert base model on GLUE MRPC
33 # in any of the following settings (with the same script):
34 # - single CPU or single device (CUDA GPU, Intel XPU etc.)
35 # - multi devices (using PyTorch distributed mode)
36 # - (multi) TPUs
37 # - fp16 (mixed-precision) or fp32 (normal precision)
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 get_dataloaders(accelerator: Accelerator, batch_size: int = 16):
51 """
52 Creates a set of `DataLoader`s for the `glue` dataset,
53 using "bert-base-cased" as the tokenizer.
54
55 Args:
56 accelerator (`Accelerator`):
57 An `Accelerator` object
58 batch_size (`int`, *optional*):
59 The batch size for the train and validation DataLoaders.
60 """
61 tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
62 datasets = load_dataset("nyu-mll/glue", "mrpc")
63
64 def tokenize_function(examples):
65 # max_length=None => use the model max length (it's actually the default)
66 outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None)
67 return outputs
68
69 # Apply the method we just defined to all the examples in all the splits of the dataset
70 # starting with the main process first:
71 with accelerator.main_process_first():
72 tokenized_datasets = datasets.map(
73 tokenize_function,
74 batched=True,
75 remove_columns=["idx", "sentence1", "sentence2"],
76 )
77
78 # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
79 # transformers library
80 tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
81
82 def collate_fn(examples):
83 # On TPU it's best to pad everything to the same length or training will be very slow.
84 max_length = 128 if accelerator.distributed_type == DistributedType.XLA else None
85 # When using mixed precision we want round multiples of 8/16
86 if accelerator.mixed_precision == "fp8":
87 pad_to_multiple_of = 16
88 elif accelerator.mixed_precision != "no":
89 pad_to_multiple_of = 8
90 else:
91 pad_to_multiple_of = None
92
93 return tokenizer.pad(
94 examples,
95 padding="longest",
96 max_length=max_length,
97 pad_to_multiple_of=pad_to_multiple_of,
98 return_tensors="pt",
99 )
100
101 # Instantiate dataloaders.
102 train_dataloader = DataLoader(
103 tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size
104 )
105 eval_dataloader = DataLoader(
106 tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE
107 )
108
109 return train_dataloader, eval_dataloader
110
111
112 # For testing only
113 if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
114 from accelerate.test_utils.training import mocked_dataloaders
115
116 get_dataloaders = mocked_dataloaders # noqa: F811
117
118
119 def training_function(config, args):
120 # For testing only
121 if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
122 config["num_epochs"] = 2
123 # New Code #
124 profile_kwargs = ProfileKwargs(
125 record_shapes=args.record_shapes,
126 profile_memory=args.profile_memory,
127 with_flops=args.with_flops,
128 output_trace_dir=args.output_trace_dir,
129 )
130 # Initialize accelerator
131 accelerator = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision, kwargs_handlers=[profile_kwargs])
132 # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
133 lr = config["lr"]
134 num_epochs = int(config["num_epochs"])
135 seed = int(config["seed"])
136 batch_size = int(config["batch_size"])
137
138 metric = evaluate.load("glue", "mrpc")
139
140 set_seed(seed)
141 train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size)
142 # Instantiate the model (we build the model here so that the seed also control new weights initialization)
143 model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True)
144
145 # We could avoid this line since the accelerator is set with `device_placement=True` (default value).
146 # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
147 # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
148 model = model.to(accelerator.device)
149
150 # Instantiate optimizer
151 optimizer = AdamW(params=model.parameters(), lr=lr)
152
153 # Instantiate scheduler
154 lr_scheduler = get_linear_schedule_with_warmup(
155 optimizer=optimizer,
156 num_warmup_steps=100,
157 num_training_steps=(len(train_dataloader) * num_epochs),
158 )
159
160 # Prepare everything
161 # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
162 # prepare method.
163 model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
164 model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
165 )
166
167 # Now we train the model
168 for epoch in range(num_epochs):
169 model.train()
170 # New Code #
171 with accelerator.profile() as prof:
172 for step, batch in enumerate(train_dataloader):
173 # We could avoid this line since we set the accelerator with `device_placement=True`.
174 batch.to(accelerator.device)
175 # We use the new `accumulate` context manager to perform gradient accumulation
176 with accelerator.accumulate(model):
177 output = model(**batch)
178 loss = output.loss
179 accelerator.backward(loss)
180 optimizer.step()
181 lr_scheduler.step()
182 optimizer.zero_grad()
183 # New Code #
184 accelerator.print(
185 prof.key_averages().table(
186 sort_by="self_cpu_time_total" if args.cpu else f"self_{accelerator.device.type}_time_total",
187 row_limit=-1,
188 )
189 )
190
191 model.eval()
192 for step, batch in enumerate(eval_dataloader):
193 # We could avoid this line since we set the accelerator with `device_placement=True`.
194 batch.to(accelerator.device)
195 with torch.no_grad():
196 outputs = model(**batch)
197 predictions = outputs.logits.argmax(dim=-1)
198 predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"]))
199 metric.add_batch(
200 predictions=predictions,
201 references=references,
202 )
203
204 eval_metric = metric.compute()
205 # Use accelerator.print to print only on the main process.
206 accelerator.print(f"epoch {epoch}:", eval_metric)
207 accelerator.end_training()
208
209
210 def main():
211 parser = argparse.ArgumentParser(description="Simple example of training script.")
212 parser.add_argument(
213 "--mixed_precision",
214 type=str,
215 default=None,
216 choices=["no", "fp16", "bf16", "fp8"],
217 help="Whether to use mixed precision. Choose"
218 "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
219 "and an Nvidia Ampere GPU or an Intel XPU.",
220 )
221 # New Code #
222 parser.add_argument(
223 "--record_shapes",
224 action="store_true",
225 default=False,
226 help="If passed, will record shapes for profiling.",
227 )
228 # New Code #
229 parser.add_argument(
230 "--profile_memory",
231 action="store_true",
232 default=False,
233 help="If passed, will profile memory.",
234 )
235 # New Code #
236 parser.add_argument(
237 "--with_flops",
238 action="store_true",
239 default=False,
240 help="If passed, will profile flops.",
241 )
242 # New Code #
243 parser.add_argument(
244 "--output_trace_dir",
245 type=str,
246 default=None,
247 help="If passed, will save a json trace to the specified path.",
248 )
249 parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.")
250 args = parser.parse_args()
251 config = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16}
252 training_function(config, args)
253
254
255 if __name__ == "__main__":
256 main()