Debian Codegraph @

benchmarks/fp8/transformer_engine/non_distributed.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 single GPU training.
19 """
20
21 import evaluate
22 import torch
23 import transformer_engine.common.recipe as te_recipe
24 import transformer_engine.pytorch as te
25 from fp8_utils import evaluate_model, get_named_parameters, get_training_utilities
26 from transformer_engine.common.recipe import DelayedScaling
27
28 from accelerate import Accelerator
29 from accelerate.state import AcceleratorState
30 from accelerate.utils import FP8RecipeKwargs, set_seed
31 from accelerate.utils.transformer_engine import convert_model
32
33
34 MODEL_NAME = "bert-base-cased"
35 METRIC = evaluate.load("glue", "mrpc")
36
37
38 def train_baseline():
39 set_seed(42)
40 model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = get_training_utilities(MODEL_NAME)
41
42 # Convert the model to TE
43 old_named_params = get_named_parameters(model)
44
45 with torch.no_grad():
46 convert_model(model)
47
48 new_named_params = get_named_parameters(model)
49 mapping = {p: new_named_params[n] for n, p in old_named_params.items()}
50 for param_group in optimizer.param_groups:
51 param_group["params"] = [mapping[p] for p in param_group["params"]]
52
53 FP8_RECIPE_KWARGS = {"fp8_format": te_recipe.Format.HYBRID, "amax_history_len": 32, "amax_compute_algo": "max"}
54 fp8_recipe = DelayedScaling(**FP8_RECIPE_KWARGS)
55
56 model.to("cuda")
57 base_model_results = evaluate_model(model, eval_dataloader, METRIC)
58 model.train()
59
60 for batch in train_dataloader:
61 with te.fp8_autocast(enabled=True, fp8_recipe=fp8_recipe):
62 with torch.autocast(device_type="cuda", dtype=torch.bfloat16):
63 batch = batch.to("cuda")
64 outputs = model(**batch)
65 loss = outputs.loss
66 loss.backward()
67 optimizer.step()
68 optimizer.zero_grad()
69 lr_scheduler.step()
70
71 trained_model_results = evaluate_model(model, eval_dataloader, METRIC)
72
73 assert trained_model_results["accuracy"] > base_model_results["accuracy"], (
74 f"Accuracy should be higher for the trained model: {trained_model_results['accuracy']} > {base_model_results['accuracy']}"
75 )
76 assert trained_model_results["f1"] > base_model_results["f1"], (
77 f"F1 score should be higher for the trained model: {trained_model_results['f1']} > {base_model_results['f1']}"
78 )
79
80 return base_model_results, trained_model_results
81
82
83 def train_integration():
84 FP8_RECIPE_KWARGS = {"fp8_format": "HYBRID", "amax_history_len": 32, "amax_compute_algo": "max"}
85 kwargs_handlers = [FP8RecipeKwargs(backend="TE", **FP8_RECIPE_KWARGS)]
86 AcceleratorState()._reset_state(True)
87 accelerator = Accelerator(mixed_precision="fp8", kwargs_handlers=kwargs_handlers)
88 set_seed(42)
89 model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = get_training_utilities(
90 MODEL_NAME, accelerator=accelerator
91 )
92
93 model, optimizer, lr_scheduler = accelerator.prepare(model, optimizer, lr_scheduler)
94 base_model_results = evaluate_model(model, eval_dataloader, METRIC)
95 model.train()
96
97 for batch in train_dataloader:
98 outputs = model(**batch)
99 loss = outputs.loss
100 accelerator.backward(loss)
101 optimizer.step()
102 optimizer.zero_grad()
103 lr_scheduler.step()
104
105 trained_model_results = evaluate_model(model, eval_dataloader, METRIC)
106
107 assert trained_model_results["accuracy"] > base_model_results["accuracy"], (
108 f"Accuracy should be higher for the trained model: {trained_model_results['accuracy']} > {base_model_results['accuracy']}"
109 )
110 assert trained_model_results["f1"] > base_model_results["f1"], (
111 f"F1 score should be higher for the trained model: {trained_model_results['f1']} > {base_model_results['f1']}"
112 )
113
114 return base_model_results, trained_model_results
115
116
117 if __name__ == "__main__":
118 baseline_not_trained, baseline_trained = train_baseline()
119 accelerator_not_trained, accelerator_trained = train_integration()
120
121 assert baseline_not_trained["accuracy"] == accelerator_not_trained["accuracy"], (
122 f"Accuracy should be the same for the baseline and accelerator: {baseline_not_trained['accuracy']} == {accelerator_not_trained['accuracy']}"
123 )
124 assert baseline_not_trained["f1"] == accelerator_not_trained["f1"], (
125 f"F1 score should be the same for the baseline and accelerator: {baseline_not_trained['f1']} == {accelerator_not_trained['f1']}"
126 )
127 assert baseline_trained["accuracy"] == accelerator_trained["accuracy"], (
128 f"Accuracy should be the same for the baseline and accelerator: {baseline_trained['accuracy']} == {accelerator_trained['accuracy']}"
129 )
130 assert baseline_trained["f1"] == accelerator_trained["f1"], (
131 f"F1 score should be the same for the baseline and accelerator: {baseline_trained['f1']} == {accelerator_trained['f1']}"
132 )