Debian Codegraph @

benchmarks/fp8/transformer_engine/fsdp.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
15 """
16 This script tests to ensure that `accelerate` performs at the same level as raw `TransformersEngine`.
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 import transformer_engine.common.recipe as te_recipe
26 import transformer_engine.pytorch as te
27 from fp8_utils import evaluate_model, get_named_parameters, get_training_utilities
28 from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
29 from torch.distributed.fsdp import MixedPrecision
30 from torch.distributed.fsdp.wrap import transformer_auto_wrap_policy
31 from transformer_engine.common.recipe import DelayedScaling
32 from transformers.models.bert import BertLayer
33
34 from accelerate import Accelerator
35 from accelerate import FullyShardedDataParallelPlugin as FSDPPlugin
36 from accelerate.state import AcceleratorState
37 from accelerate.utils import FP8RecipeKwargs, set_seed
38 from accelerate.utils.transformer_engine import convert_model
39
40
41 MODEL_NAME = "bert-base-cased"
42 METRIC = evaluate.load("glue", "mrpc")
43
44 FSDP_WRAP_POLICY = partial(transformer_auto_wrap_policy, transformer_layer_cls={BertLayer})
45
46
47 def train_baseline():
48 set_seed(42)
49 model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = get_training_utilities(MODEL_NAME)
50 accelerator = Accelerator()
51 device = accelerator.device
52 model.to(device)
53
54 # Convert the model to TE
55 old_named_params = get_named_parameters(model)
56
57 with torch.no_grad():
58 convert_model(model)
59
60 FP8_RECIPE_KWARGS = {"fp8_format": te_recipe.Format.HYBRID, "amax_history_len": 32, "amax_compute_algo": "max"}
61 fp8_recipe = DelayedScaling(**FP8_RECIPE_KWARGS)
62
63 new_named_params = get_named_parameters(model)
64
65 # Convert the model to FSDP
66 model = FSDP(
67 model,
68 use_orig_params=True,
69 mixed_precision=MixedPrecision(param_dtype=torch.bfloat16, reduce_dtype=torch.float32),
70 auto_wrap_policy=FSDP_WRAP_POLICY,
71 )
72
73 mapping = {p: new_named_params[n] for n, p in old_named_params.items()}
74 for param_group in optimizer.param_groups:
75 param_group["params"] = [mapping[p] for p in param_group["params"]]
76
77 base_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator)
78 model.train()
79
80 for _ in range(2):
81 for batch in train_dataloader:
82 with te.fp8_autocast(enabled=True, fp8_recipe=fp8_recipe):
83 with torch.autocast(device_type="cuda", dtype=torch.bfloat16):
84 batch = batch.to(device)
85 outputs = model(**batch)
86 loss = outputs.loss
87 loss.backward()
88 optimizer.step()
89 optimizer.zero_grad()
90 lr_scheduler.step()
91
92 trained_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator)
93
94 assert trained_model_results["accuracy"] > base_model_results["accuracy"], (
95 f"Accuracy should be higher for the trained model: {trained_model_results['accuracy']} > {base_model_results['accuracy']}"
96 )
97 assert trained_model_results["f1"] > base_model_results["f1"], (
98 f"F1 score should be higher for the trained model: {trained_model_results['f1']} > {base_model_results['f1']}"
99 )
100
101 return base_model_results, trained_model_results
102
103
104 def train_integration():
105 FP8_RECIPE_KWARGS = {"fp8_format": "HYBRID", "amax_history_len": 32, "amax_compute_algo": "max"}
106 kwargs_handlers = [FP8RecipeKwargs(backend="TE", **FP8_RECIPE_KWARGS)]
107 AcceleratorState()._reset_state(True)
108 fsdp_plugin = FSDPPlugin(
109 auto_wrap_policy=FSDP_WRAP_POLICY,
110 use_orig_params=True,
111 mixed_precision_policy=MixedPrecision(param_dtype=torch.bfloat16, reduce_dtype=torch.float32),
112 )
113 accelerator = Accelerator(mixed_precision="fp8", fsdp_plugin=fsdp_plugin, kwargs_handlers=kwargs_handlers)
114 set_seed(42)
115 model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = get_training_utilities(
116 MODEL_NAME, accelerator=accelerator
117 )
118
119 model, optimizer = accelerator.prepare(model, optimizer)
120 base_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator)
121 model.train()
122
123 for _ in range(2):
124 for batch in train_dataloader:
125 outputs = model(**batch)
126 loss = outputs.loss
127 accelerator.backward(loss)
128 optimizer.step()
129 optimizer.zero_grad()
130 lr_scheduler.step()
131
132 trained_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator)
133
134 assert trained_model_results["accuracy"] > base_model_results["accuracy"], (
135 f"Accuracy should be higher for the trained model: {trained_model_results['accuracy']} > {base_model_results['accuracy']}"
136 )
137 assert trained_model_results["f1"] > base_model_results["f1"], (
138 f"F1 score should be higher for the trained model: {trained_model_results['f1']} > {base_model_results['f1']}"
139 )
140
141 return base_model_results, trained_model_results
142
143
144 if __name__ == "__main__":
145 baseline_not_trained, baseline_trained = train_baseline()
146 accelerator_not_trained, accelerator_trained = train_integration()
147
148 assert baseline_not_trained["accuracy"] == accelerator_not_trained["accuracy"], (
149 f"Accuracy should be the same for the baseline and accelerator: {baseline_not_trained['accuracy']} == {accelerator_not_trained['accuracy']}"
150 )
151 assert baseline_not_trained["f1"] == accelerator_not_trained["f1"], (
152 f"F1 score should be the same for the baseline and accelerator: {baseline_not_trained['f1']} == {accelerator_not_trained['f1']}"
153 )
154 assert baseline_trained["accuracy"] == accelerator_trained["accuracy"], (
155 f"Accuracy should be the same for the baseline and accelerator: {baseline_trained['accuracy']} == {accelerator_trained['accuracy']}"
156 )
157 assert baseline_trained["f1"] == accelerator_trained["f1"], (
158 f"F1 score should be the same for the baseline and accelerator: {baseline_trained['f1']} == {accelerator_trained['f1']}"
159 )
160
161 torch.distributed.destroy_process_group()