Debian Codegraph @

benchmarks/fp8/torchao/non_distributed.py

raw
1 # Copyright 2025 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
15 """
16 This script tests to ensure that `accelerate` performs at the same level as raw `torchao`.
17
18 This particular script verifies this for single GPU training.
19 """
20
21 from functools import partial
22
23 import evaluate
24 import torch
25 from fp8_utils import get_training_utilities
26 from torchao.float8 import convert_to_float8_training
27
28 from accelerate import Accelerator
29 from accelerate.state import AcceleratorState
30 from accelerate.utils import AORecipeKwargs, set_seed
31
32
33 MODEL_NAME = "bert-base-cased"
34 METRIC = evaluate.load("glue", "mrpc")
35
36
37 def evaluate_model(model, dataloader, metric, accelerator=None):
38 "Turns model to .eval(), runs dataloader, calculates metric, then turns eval back on"
39 model.eval()
40 for step, batch in enumerate(dataloader):
41 with torch.no_grad():
42 outputs = model(**batch)
43 predictions = outputs.logits.argmax(dim=-1)
44 references = batch["labels"]
45 if accelerator is not None and accelerator.num_processes > 1:
46 predictions, references = accelerator.gather_for_metrics((predictions, references))
47 metric.add_batch(predictions=predictions, references=references)
48 return metric.compute()
49
50
51 def filter_linear_layers(module, fqn, first_layer_name=None, last_layer_name=None):
52 if isinstance(module, torch.nn.Linear):
53 if module.in_features % 16 != 0 or module.out_features % 16 != 0:
54 return False
55 # For stability reasons, we skip the first and last linear layers
56 # Otherwise can lead to the model not training or converging properly
57 if fqn in (first_layer_name, last_layer_name):
58 return False
59 return True
60
61
62 def train_baseline():
63 set_seed(42)
64 model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = get_training_utilities(MODEL_NAME)
65 first_linear = None
66 last_linear = None
67 for name, module in model.named_modules():
68 if isinstance(module, torch.nn.Linear):
69 if first_linear is None:
70 first_linear = name
71 last_linear = name
72
73 func = partial(filter_linear_layers, first_layer_name=first_linear, last_layer_name=last_linear)
74 accelerator = Accelerator()
75 device = accelerator.device
76 model.to(device)
77 convert_to_float8_training(model, module_filter_fn=func)
78 base_model_results = evaluate_model(model, eval_dataloader, METRIC)
79 model.train()
80
81 for batch in train_dataloader:
82 with torch.autocast(device_type=device.type, dtype=torch.bfloat16):
83 outputs = model(**batch)
84 loss = outputs.loss
85 loss.backward()
86 optimizer.step()
87 optimizer.zero_grad()
88 lr_scheduler.step()
89
90 trained_model_results = evaluate_model(model, eval_dataloader, METRIC)
91
92 assert trained_model_results["accuracy"] > base_model_results["accuracy"], (
93 f"Accuracy should be higher for the trained model: {trained_model_results['accuracy']} > {base_model_results['accuracy']}"
94 )
95 assert trained_model_results["f1"] > base_model_results["f1"], (
96 f"F1 score should be higher for the trained model: {trained_model_results['f1']} > {base_model_results['f1']}"
97 )
98
99 return base_model_results, trained_model_results
100
101
102 def train_integration():
103 set_seed(42)
104 accelerator = Accelerator(mixed_precision="fp8", kwargs_handlers=[AORecipeKwargs()])
105 model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = get_training_utilities(
106 MODEL_NAME, accelerator=accelerator
107 )
108 model = accelerator.prepare(model)
109 base_model_results = evaluate_model(model, eval_dataloader, METRIC)
110 model.train()
111
112 for batch in train_dataloader:
113 outputs = model(**batch)
114 loss = outputs.loss
115 loss.backward()
116 optimizer.step()
117 optimizer.zero_grad()
118 lr_scheduler.step()
119
120 trained_model_results = evaluate_model(model, eval_dataloader, METRIC)
121
122 assert trained_model_results["accuracy"] > base_model_results["accuracy"], (
123 f"Accuracy should be higher for the trained model: {trained_model_results['accuracy']} > {base_model_results['accuracy']}"
124 )
125 assert trained_model_results["f1"] > base_model_results["f1"], (
126 f"F1 score should be higher for the trained model: {trained_model_results['f1']} > {base_model_results['f1']}"
127 )
128
129 return base_model_results, trained_model_results
130
131
132 if __name__ == "__main__":
133 baseline_not_trained, baseline_trained = train_baseline()
134 AcceleratorState._reset_state(True)
135 accelerator_not_trained, accelerator_trained = train_integration()
136 assert baseline_not_trained["accuracy"] == accelerator_not_trained["accuracy"], (
137 f"Accuracy should be the same for the baseline and accelerator: {baseline_not_trained['accuracy']} == {accelerator_not_trained['accuracy']}"
138 )
139 assert baseline_not_trained["f1"] == accelerator_not_trained["f1"], (
140 f"F1 score should be the same for the baseline and accelerator: {baseline_not_trained['f1']} == {accelerator_not_trained['f1']}"
141 )
142 assert baseline_trained["accuracy"] == accelerator_trained["accuracy"], (
143 f"Accuracy should be the same for the baseline and accelerator: {baseline_trained['accuracy']} == {accelerator_trained['accuracy']}"
144 )
145 assert baseline_trained["f1"] == accelerator_trained["f1"], (
146 f"F1 score should be the same for the baseline and accelerator: {baseline_trained['f1']} == {accelerator_trained['f1']}"
147 )