Debian Codegraph @

benchmarks/fp8/torchao/fsdp.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 FSDP 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 torch.distributed.fsdp import FullyShardedDataParallel as FSDP
27 from torch.distributed.fsdp import MixedPrecision
28 from torch.distributed.fsdp.wrap import transformer_auto_wrap_policy
29 from torchao.float8 import convert_to_float8_training
30 from transformers.models.bert import BertLayer
31
32 from accelerate import Accelerator
33 from accelerate import FullyShardedDataParallelPlugin as FSDPPlugin
34 from accelerate.state import AcceleratorState
35 from accelerate.utils import AORecipeKwargs, set_seed
36
37
38 MODEL_NAME = "bert-base-cased"
39 METRIC = evaluate.load("glue", "mrpc")
40
41 FSDP_WRAP_POLICY = partial(transformer_auto_wrap_policy, transformer_layer_cls={BertLayer})
42
43
44 def filter_linear_layers(module, fqn, first_layer_name=None, last_layer_name=None):
45 if isinstance(module, torch.nn.Linear):
46 if module.in_features % 16 != 0 or module.out_features % 16 != 0:
47 return False
48 # For stability reasons, we skip the first and last linear layers
49 # Otherwise can lead to the model not training or converging properly
50 if fqn in (first_layer_name, last_layer_name):
51 return False
52 return True
53
54
55 def evaluate_model(model, dataloader, metric, accelerator=None):
56 "Turns model to .eval(), runs dataloader, calculates metric, then turns eval back on"
57 model.eval()
58 for step, batch in enumerate(dataloader):
59 with torch.no_grad():
60 outputs = model(**batch)
61 predictions = outputs.logits.argmax(dim=-1)
62 references = batch["labels"]
63 if accelerator is not None and accelerator.num_processes > 1:
64 predictions, references = accelerator.gather_for_metrics((predictions, references))
65 metric.add_batch(predictions=predictions, references=references)
66 return metric.compute()
67
68
69 def train_baseline():
70 set_seed(42)
71 model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = get_training_utilities(MODEL_NAME)
72 first_linear = None
73 last_linear = None
74 for name, module in model.named_modules():
75 if isinstance(module, torch.nn.Linear):
76 if first_linear is None:
77 first_linear = name
78 last_linear = name
79 func = partial(filter_linear_layers, first_layer_name=first_linear, last_layer_name=last_linear)
80 accelerator = Accelerator()
81 device = accelerator.device
82 model.to(device)
83
84 convert_to_float8_training(model, module_filter_fn=func)
85
86 # Convert the model to FSDP
87 model = FSDP(
88 model,
89 use_orig_params=True,
90 mixed_precision=MixedPrecision(param_dtype=torch.bfloat16, reduce_dtype=torch.float32),
91 auto_wrap_policy=FSDP_WRAP_POLICY,
92 )
93
94 base_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator)
95 model.train()
96
97 for batch in train_dataloader:
98 with torch.autocast(device_type=device.type, dtype=torch.bfloat16):
99 batch = batch.to(device)
100 outputs = model(**batch)
101 loss = outputs.loss
102 loss.backward()
103 optimizer.step()
104 optimizer.zero_grad()
105 lr_scheduler.step()
106
107 trained_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator)
108
109 assert trained_model_results["accuracy"] > base_model_results["accuracy"], (
110 f"Accuracy should be higher for the trained model: {trained_model_results['accuracy']} > {base_model_results['accuracy']}"
111 )
112 assert trained_model_results["f1"] > base_model_results["f1"], (
113 f"F1 score should be higher for the trained model: {trained_model_results['f1']} > {base_model_results['f1']}"
114 )
115
116 return base_model_results, trained_model_results
117
118
119 def train_integration():
120 AcceleratorState()._reset_state(True)
121 fsdp_plugin = FSDPPlugin(
122 auto_wrap_policy=FSDP_WRAP_POLICY,
123 use_orig_params=True,
124 mixed_precision_policy=MixedPrecision(param_dtype=torch.bfloat16, reduce_dtype=torch.float32),
125 )
126 accelerator = Accelerator(mixed_precision="fp8", fsdp_plugin=fsdp_plugin, kwargs_handlers=[AORecipeKwargs()])
127 set_seed(42)
128 model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = get_training_utilities(
129 MODEL_NAME, accelerator=accelerator
130 )
131
132 model, optimizer = accelerator.prepare(model, optimizer)
133 base_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator)
134 model.train()
135
136 for batch in train_dataloader:
137 outputs = model(**batch)
138 loss = outputs.loss
139 accelerator.backward(loss)
140 optimizer.step()
141 optimizer.zero_grad()
142 lr_scheduler.step()
143
144 trained_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator)
145
146 assert trained_model_results["accuracy"] > base_model_results["accuracy"], (
147 f"Accuracy should be higher for the trained model: {trained_model_results['accuracy']} > {base_model_results['accuracy']}"
148 )
149 assert trained_model_results["f1"] > base_model_results["f1"], (
150 f"F1 score should be higher for the trained model: {trained_model_results['f1']} > {base_model_results['f1']}"
151 )
152
153 return base_model_results, trained_model_results
154
155
156 if __name__ == "__main__":
157 baseline_not_trained, baseline_trained = train_baseline()
158 accelerator_not_trained, accelerator_trained = train_integration()
159
160 assert baseline_not_trained["accuracy"] == accelerator_not_trained["accuracy"], (
161 f"Accuracy should be the same for the baseline and accelerator: {baseline_not_trained['accuracy']} == {accelerator_not_trained['accuracy']}"
162 )
163 assert baseline_not_trained["f1"] == accelerator_not_trained["f1"], (
164 f"F1 score should be the same for the baseline and accelerator: {baseline_not_trained['f1']} == {accelerator_not_trained['f1']}"
165 )
166 assert baseline_trained["accuracy"] == accelerator_trained["accuracy"], (
167 f"Accuracy should be the same for the baseline and accelerator: {baseline_trained['accuracy']} == {accelerator_trained['accuracy']}"
168 )
169 assert baseline_trained["f1"] == accelerator_trained["f1"], (
170 f"F1 score should be the same for the baseline and accelerator: {baseline_trained['f1']} == {accelerator_trained['f1']}"
171 )
172
173 torch.distributed.destroy_process_group()