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