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