| 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 `torchao`. |
| 17 |
|
| 18 |
This particular script verifies this for deepspeed training. |
| 19 |
""" |
| 20 |
|
| 21 |
from functools import partial |
| 22 |
from unittest.mock import patch |
| 23 |
|
| 24 |
import deepspeed |
| 25 |
import evaluate |
| 26 |
import torch |
| 27 |
from fp8_utils import evaluate_model, get_training_utilities |
| 28 |
from torchao.float8 import convert_to_float8_training |
| 29 |
from transformers.integrations import HfDeepSpeedConfig |
| 30 |
|
| 31 |
from accelerate import Accelerator, DeepSpeedPlugin |
| 32 |
from accelerate.state import AcceleratorState |
| 33 |
from accelerate.utils import AORecipeKwargs, set_seed |
| 34 |
|
| 35 |
|
| 36 |
MODEL_NAME = "bert-base-cased" |
| 37 |
METRIC = evaluate.load("glue", "mrpc") |
| 38 |
|
| 39 |
|
| 40 |
def filter_linear_layers(module, fqn, first_layer_name=None, last_layer_name=None): |
| 41 |
if isinstance(module, torch.nn.Linear): |
| 42 |
if module.in_features % 16 != 0 or module.out_features % 16 != 0: |
| 43 |
return False |
| 44 |
# For stability reasons, we skip the first and last linear layers |
| 45 |
# Otherwise can lead to the model not training or converging properly |
| 46 |
if fqn in (first_layer_name, last_layer_name): |
| 47 |
return False |
| 48 |
return True |
| 49 |
|
| 50 |
|
| 51 |
def train_baseline(zero_stage: int = 1): |
| 52 |
set_seed(42) |
| 53 |
# This forces transformers to think Zero-3 Init should be used |
| 54 |
with patch("transformers.integrations.deepspeed.is_deepspeed_zero3_enabled") as mock: |
| 55 |
mock.return_value = zero_stage == 3 |
| 56 |
|
| 57 |
config = HfDeepSpeedConfig( |
| 58 |
{ |
| 59 |
"train_micro_batch_size_per_gpu": 16, |
| 60 |
"gradient_accumulation_steps": 1, |
| 61 |
"zero_optimization": {"stage": zero_stage}, |
| 62 |
} |
| 63 |
) |
| 64 |
plugin = DeepSpeedPlugin(hf_ds_config=config) |
| 65 |
accelerator = Accelerator(deepspeed_plugin=plugin) |
| 66 |
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = get_training_utilities( |
| 67 |
MODEL_NAME, accelerator=accelerator |
| 68 |
) |
| 69 |
first_linear = None |
| 70 |
last_linear = None |
| 71 |
for name, module in model.named_modules(): |
| 72 |
if isinstance(module, torch.nn.Linear): |
| 73 |
if first_linear is None: |
| 74 |
first_linear = name |
| 75 |
last_linear = name |
| 76 |
func = partial(filter_linear_layers, first_layer_name=first_linear, last_layer_name=last_linear) |
| 77 |
|
| 78 |
convert_to_float8_training(model, module_filter_fn=func) |
| 79 |
|
| 80 |
import numpy as np |
| 81 |
|
| 82 |
config = { |
| 83 |
"train_batch_size": 32, |
| 84 |
"train_micro_batch_size_per_gpu": 16, |
| 85 |
"gradient_accumulation_steps": 1, |
| 86 |
"zero_optimization": { |
| 87 |
"stage": zero_stage, |
| 88 |
"offload_optimizer": {"device": "none", "nvme_path": None}, |
| 89 |
"offload_param": {"device": "none", "nvme_path": None}, |
| 90 |
"stage3_gather_16bit_weights_on_model_save": False, |
| 91 |
}, |
| 92 |
"gradient_clipping": 1.0, |
| 93 |
"steps_per_print": np.inf, |
| 94 |
"bf16": {"enabled": True}, |
| 95 |
"fp16": {"enabled": False}, |
| 96 |
"zero_allow_untested_optimizer": True, |
| 97 |
} |
| 98 |
|
| 99 |
( |
| 100 |
model, |
| 101 |
optimizer, |
| 102 |
_, |
| 103 |
lr_scheduler, |
| 104 |
) = deepspeed.initialize( |
| 105 |
model=model, |
| 106 |
optimizer=optimizer, |
| 107 |
lr_scheduler=lr_scheduler, |
| 108 |
config_params=config, |
| 109 |
) |
| 110 |
|
| 111 |
base_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator) |
| 112 |
model.train() |
| 113 |
|
| 114 |
model_outputs = [] |
| 115 |
data = [] |
| 116 |
|
| 117 |
for batch in train_dataloader: |
| 118 |
outputs = model(**batch) |
| 119 |
data.append(batch.to("cpu")) |
| 120 |
model_outputs.append(outputs.logits.to("cpu")) |
| 121 |
loss = outputs.loss |
| 122 |
model.backward(loss) |
| 123 |
model.step() |
| 124 |
for _ in range(accelerator.num_processes): |
| 125 |
lr_scheduler.step() |
| 126 |
|
| 127 |
trained_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator) |
| 128 |
model.destroy() |
| 129 |
assert trained_model_results["accuracy"] > base_model_results["accuracy"], ( |
| 130 |
f"Accuracy should be higher for the trained model: {trained_model_results['accuracy']} > {base_model_results['accuracy']}" |
| 131 |
) |
| 132 |
assert trained_model_results["f1"] > base_model_results["f1"], ( |
| 133 |
f"F1 score should be higher for the trained model: {trained_model_results['f1']} > {base_model_results['f1']}" |
| 134 |
) |
| 135 |
|
| 136 |
del config |
| 137 |
return base_model_results, trained_model_results, model_outputs, data |
| 138 |
|
| 139 |
|
| 140 |
def train_integration(zero_stage: int = 1): |
| 141 |
set_seed(42) |
| 142 |
AcceleratorState()._reset_state(True) |
| 143 |
config = HfDeepSpeedConfig( |
| 144 |
{ |
| 145 |
"train_micro_batch_size_per_gpu": 16, |
| 146 |
"gradient_accumulation_steps": 1, |
| 147 |
"zero_optimization": {"stage": zero_stage}, |
| 148 |
} |
| 149 |
) |
| 150 |
deepspeed_plugin = DeepSpeedPlugin( |
| 151 |
hf_ds_config=config, |
| 152 |
) |
| 153 |
# This forces transformers to think Zero-3 Init should be used |
| 154 |
with patch("transformers.integrations.deepspeed.is_deepspeed_zero3_enabled") as mock: |
| 155 |
mock.return_value = zero_stage == 3 |
| 156 |
accelerator = Accelerator( |
| 157 |
mixed_precision="fp8", kwargs_handlers=[AORecipeKwargs()], deepspeed_plugin=deepspeed_plugin |
| 158 |
) |
| 159 |
|
| 160 |
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = get_training_utilities( |
| 161 |
MODEL_NAME, accelerator=accelerator |
| 162 |
) |
| 163 |
|
| 164 |
model, optimizer, lr_scheduler, train_dataloader, eval_dataloader = accelerator.prepare( |
| 165 |
model, optimizer, lr_scheduler, train_dataloader, eval_dataloader |
| 166 |
) |
| 167 |
base_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator) |
| 168 |
model.train() |
| 169 |
model_outputs = [] |
| 170 |
data = [] |
| 171 |
for batch in train_dataloader: |
| 172 |
outputs = model(**batch) |
| 173 |
data.append(batch.to("cpu")) |
| 174 |
model_outputs.append(outputs.logits.to("cpu")) |
| 175 |
loss = outputs.loss |
| 176 |
accelerator.backward(loss) |
| 177 |
optimizer.step() |
| 178 |
lr_scheduler.step() |
| 179 |
optimizer.zero_grad() |
| 180 |
|
| 181 |
trained_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator) |
| 182 |
model.destroy() |
| 183 |
assert trained_model_results["accuracy"] > base_model_results["accuracy"], ( |
| 184 |
f"Accuracy should be higher for the trained model: {trained_model_results['accuracy']} > {base_model_results['accuracy']}" |
| 185 |
) |
| 186 |
assert trained_model_results["f1"] > base_model_results["f1"], ( |
| 187 |
f"F1 score should be higher for the trained model: {trained_model_results['f1']} > {base_model_results['f1']}" |
| 188 |
) |
| 189 |
|
| 190 |
del config |
| 191 |
return base_model_results, trained_model_results, model_outputs, data |
| 192 |
|
| 193 |
|
| 194 |
if __name__ == "__main__": |
| 195 |
for zero_stage in [1, 2, 3]: |
| 196 |
baseline_not_trained, baseline_trained, baseline_outputs, baseline_data = train_baseline(zero_stage) |
| 197 |
accelerator_not_trained, accelerator_trained, accelerator_outputs, accelerator_data = train_integration( |
| 198 |
zero_stage |
| 199 |
) |
| 200 |
assert baseline_not_trained["accuracy"] == accelerator_not_trained["accuracy"], ( |
| 201 |
f"ZERO stage {zero_stage}: Accuracy should be the same for the baseline and accelerator: {baseline_not_trained['accuracy']} == {accelerator_not_trained['accuracy']}" |
| 202 |
) |
| 203 |
assert baseline_not_trained["f1"] == accelerator_not_trained["f1"], ( |
| 204 |
f"ZERO stage {zero_stage}: F1 score should be the same for the baseline and accelerator: {baseline_not_trained['f1']} == {accelerator_not_trained['f1']}" |
| 205 |
) |
| 206 |
assert baseline_trained["accuracy"] == accelerator_trained["accuracy"], ( |
| 207 |
f"ZERO stage {zero_stage}: Accuracy should be the same for the baseline and accelerator: {baseline_trained['accuracy']} == {accelerator_trained['accuracy']}" |
| 208 |
) |
| 209 |
assert baseline_trained["f1"] == accelerator_trained["f1"], ( |
| 210 |
f"ZERO stage {zero_stage}: F1 score should be the same for the baseline and accelerator: {baseline_trained['f1']} == {accelerator_trained['f1']}" |
| 211 |
) |
| 212 |
AcceleratorState()._reset_state(True) |
| 213 |
torch.distributed.destroy_process_group() |