| 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 DDP training. |
| 19 |
""" |
| 20 |
|
| 21 |
from unittest.mock import patch |
| 22 |
|
| 23 |
import deepspeed |
| 24 |
import evaluate |
| 25 |
import torch |
| 26 |
import transformer_engine.common.recipe as te_recipe |
| 27 |
import transformer_engine.pytorch as te |
| 28 |
from fp8_utils import evaluate_model, get_named_parameters, get_training_utilities |
| 29 |
from transformer_engine.common.recipe import DelayedScaling |
| 30 |
|
| 31 |
from accelerate import Accelerator, DeepSpeedPlugin |
| 32 |
from accelerate.state import AcceleratorState |
| 33 |
from accelerate.utils import FP8RecipeKwargs, set_seed |
| 34 |
from accelerate.utils.transformer_engine import convert_model |
| 35 |
|
| 36 |
|
| 37 |
MODEL_NAME = "bert-base-cased" |
| 38 |
METRIC = evaluate.load("glue", "mrpc") |
| 39 |
|
| 40 |
|
| 41 |
def train_baseline(zero_stage: int = 1): |
| 42 |
# This forces transformers to think Zero-3 Init should be used |
| 43 |
with patch("transformers.integrations.deepspeed.is_deepspeed_zero3_enabled") as mock: |
| 44 |
mock.return_value = zero_stage == 3 |
| 45 |
set_seed(42) |
| 46 |
|
| 47 |
accelerator = Accelerator() |
| 48 |
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = get_training_utilities( |
| 49 |
MODEL_NAME, accelerator=accelerator |
| 50 |
) |
| 51 |
|
| 52 |
# Convert the model to TE |
| 53 |
old_named_params = get_named_parameters(model) |
| 54 |
|
| 55 |
with torch.no_grad(): |
| 56 |
convert_model(model) |
| 57 |
new_named_params = get_named_parameters(model) |
| 58 |
|
| 59 |
mapping = {p: new_named_params[n] for n, p in old_named_params.items()} |
| 60 |
for param_group in optimizer.param_groups: |
| 61 |
param_group["params"] = [mapping[p] for p in param_group["params"]] |
| 62 |
|
| 63 |
FP8_RECIPE_KWARGS = {"fp8_format": te_recipe.Format.HYBRID, "amax_history_len": 32, "amax_compute_algo": "max"} |
| 64 |
fp8_recipe = DelayedScaling(**FP8_RECIPE_KWARGS) |
| 65 |
|
| 66 |
import numpy as np |
| 67 |
|
| 68 |
config = { |
| 69 |
"train_batch_size": 16, |
| 70 |
"train_micro_batch_size_per_gpu": 16, |
| 71 |
"gradient_accumulation_steps": 1, |
| 72 |
"zero_optimization": { |
| 73 |
"stage": zero_stage, |
| 74 |
"offload_optimizer": {"device": "none", "nvme_path": None}, |
| 75 |
"offload_param": {"device": "none", "nvme_path": None}, |
| 76 |
"stage3_gather_16bit_weights_on_model_save": False, |
| 77 |
}, |
| 78 |
"gradient_clipping": 1.0, |
| 79 |
"steps_per_print": np.inf, |
| 80 |
"bf16": {"enabled": True}, |
| 81 |
"fp16": {"enabled": False}, |
| 82 |
"zero_allow_untested_optimizer": True, |
| 83 |
} |
| 84 |
|
| 85 |
( |
| 86 |
model, |
| 87 |
optimizer, |
| 88 |
_, |
| 89 |
_, |
| 90 |
) = deepspeed.initialize( |
| 91 |
model=model, |
| 92 |
optimizer=optimizer, |
| 93 |
config_params=config, |
| 94 |
) |
| 95 |
|
| 96 |
base_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator) |
| 97 |
model.train() |
| 98 |
|
| 99 |
model_outputs = [] |
| 100 |
data = [] |
| 101 |
|
| 102 |
for _ in range(2): |
| 103 |
for batch in train_dataloader: |
| 104 |
with te.fp8_autocast(enabled=True, fp8_recipe=fp8_recipe): |
| 105 |
outputs = model(**batch) |
| 106 |
data.append(batch.to("cpu")) |
| 107 |
model_outputs.append(outputs.logits.to("cpu")) |
| 108 |
loss = outputs.loss |
| 109 |
model.backward(loss) |
| 110 |
model.step() |
| 111 |
for _ in range(accelerator.num_processes): |
| 112 |
lr_scheduler.step() |
| 113 |
|
| 114 |
trained_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator) |
| 115 |
model.destroy() |
| 116 |
assert trained_model_results["accuracy"] > base_model_results["accuracy"], ( |
| 117 |
f"Accuracy should be higher for the trained model: {trained_model_results['accuracy']} > {base_model_results['accuracy']}" |
| 118 |
) |
| 119 |
assert trained_model_results["f1"] > base_model_results["f1"], ( |
| 120 |
f"F1 score should be higher for the trained model: {trained_model_results['f1']} > {base_model_results['f1']}" |
| 121 |
) |
| 122 |
|
| 123 |
return base_model_results, trained_model_results, model_outputs, data |
| 124 |
|
| 125 |
|
| 126 |
def train_integration(zero_stage: int = 1): |
| 127 |
set_seed(42) |
| 128 |
FP8_RECIPE_KWARGS = {"fp8_format": "HYBRID", "amax_history_len": 32, "amax_compute_algo": "max"} |
| 129 |
kwargs_handlers = [FP8RecipeKwargs(backend="TE", **FP8_RECIPE_KWARGS)] |
| 130 |
AcceleratorState()._reset_state(True) |
| 131 |
deepspeed_plugin = DeepSpeedPlugin( |
| 132 |
zero_stage=zero_stage, |
| 133 |
zero3_init_flag=zero_stage == 3, |
| 134 |
) |
| 135 |
accelerator = Accelerator( |
| 136 |
mixed_precision="fp8", kwargs_handlers=kwargs_handlers, deepspeed_plugin=deepspeed_plugin |
| 137 |
) |
| 138 |
accelerator.state.deepspeed_plugin.deepspeed_config["train_micro_batch_size_per_gpu"] = 16 |
| 139 |
|
| 140 |
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = get_training_utilities( |
| 141 |
MODEL_NAME, accelerator=accelerator |
| 142 |
) |
| 143 |
|
| 144 |
model, optimizer, lr_scheduler = accelerator.prepare(model, optimizer, lr_scheduler) |
| 145 |
base_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator) |
| 146 |
model.train() |
| 147 |
model_outputs = [] |
| 148 |
data = [] |
| 149 |
for _ in range(2): |
| 150 |
for batch in train_dataloader: |
| 151 |
outputs = model(**batch) |
| 152 |
data.append(batch.to("cpu")) |
| 153 |
model_outputs.append(outputs.logits.to("cpu")) |
| 154 |
loss = outputs.loss |
| 155 |
accelerator.backward(loss) |
| 156 |
optimizer.step() |
| 157 |
lr_scheduler.step() |
| 158 |
optimizer.zero_grad() |
| 159 |
|
| 160 |
trained_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator) |
| 161 |
model.destroy() |
| 162 |
assert trained_model_results["accuracy"] > base_model_results["accuracy"], ( |
| 163 |
f"Accuracy should be higher for the trained model: {trained_model_results['accuracy']} > {base_model_results['accuracy']}" |
| 164 |
) |
| 165 |
assert trained_model_results["f1"] > base_model_results["f1"], ( |
| 166 |
f"F1 score should be higher for the trained model: {trained_model_results['f1']} > {base_model_results['f1']}" |
| 167 |
) |
| 168 |
|
| 169 |
return base_model_results, trained_model_results, model_outputs, data |
| 170 |
|
| 171 |
|
| 172 |
if __name__ == "__main__": |
| 173 |
for zero_stage in [1, 2, 3]: |
| 174 |
baseline_not_trained, baseline_trained, baseline_outputs, baseline_data = train_baseline(zero_stage) |
| 175 |
accelerator_not_trained, accelerator_trained, accelerator_outputs, accelerator_data = train_integration( |
| 176 |
zero_stage |
| 177 |
) |
| 178 |
assert baseline_not_trained["accuracy"] == accelerator_not_trained["accuracy"], ( |
| 179 |
f"ZERO stage {zero_stage}: Accuracy should be the same for the baseline and accelerator: {baseline_not_trained['accuracy']} == {accelerator_not_trained['accuracy']}" |
| 180 |
) |
| 181 |
assert baseline_not_trained["f1"] == accelerator_not_trained["f1"], ( |
| 182 |
f"ZERO stage {zero_stage}: F1 score should be the same for the baseline and accelerator: {baseline_not_trained['f1']} == {accelerator_not_trained['f1']}" |
| 183 |
) |
| 184 |
assert baseline_trained["accuracy"] == accelerator_trained["accuracy"], ( |
| 185 |
f"ZERO stage {zero_stage}: Accuracy should be the same for the baseline and accelerator: {baseline_trained['accuracy']} == {accelerator_trained['accuracy']}" |
| 186 |
) |
| 187 |
assert baseline_trained["f1"] == accelerator_trained["f1"], ( |
| 188 |
f"ZERO stage {zero_stage}: F1 score should be the same for the baseline and accelerator: {baseline_trained['f1']} == {accelerator_trained['f1']}" |
| 189 |
) |
| 190 |
|
| 191 |
torch.distributed.destroy_process_group() |