1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
|
# Copyright 2025 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse
import json
import os
import tempfile
import textwrap
import unittest
from pathlib import Path
import torch
from accelerate import Accelerator
from accelerate.state import AcceleratorState
from accelerate.test_utils import (
get_launch_command,
require_cuda_or_hpu,
require_huggingface_suite,
require_multi_device,
require_torchao,
require_transformer_engine,
require_transformer_engine_mxfp8,
run_first,
)
from accelerate.test_utils.testing import require_deepspeed, run_command
from accelerate.utils import (
AORecipeKwargs,
TERecipeKwargs,
has_ao_layers,
has_transformer_engine_layers,
)
def can_convert_te_model(from_config=False):
if not from_config:
accelerator_kwargs = {"mixed_precision": "fp8", "kwargs_handlers": [TERecipeKwargs()]}
else:
accelerator_kwargs = {}
accelerator = Accelerator(**accelerator_kwargs)
assert accelerator.fp8_enabled, "FP8 is not enabled"
dataloader = torch.utils.data.DataLoader(torch.randn(10, 32), batch_size=2)
model = torch.nn.Sequential(torch.nn.Linear(32, 32), torch.nn.LayerNorm(32, bias=False), torch.nn.Linear(32, 16))
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.1)
model, optimizer, dataloader, scheduler = accelerator.prepare(model, optimizer, dataloader, scheduler)
assert has_transformer_engine_layers(model)
def maintain_proper_deepspeed_config(expected_version):
assert AcceleratorState().deepspeed_plugin.zero_stage == expected_version, (
f"Expected zero stage {expected_version} but got {AcceleratorState().deepspeed_plugin.zero_stage}"
)
def can_convert_ao_model(from_config=False):
from transformers import AutoModelForSequenceClassification
if not from_config:
accelerator_kwargs = {"mixed_precision": "fp8", "kwargs_handlers": [AORecipeKwargs()]}
else:
accelerator_kwargs = {}
accelerator = Accelerator(**accelerator_kwargs)
dataloader = torch.utils.data.DataLoader(torch.randn(10, 32), batch_size=2)
model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased")
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.1)
model, optimizer, dataloader, scheduler = accelerator.prepare(model, optimizer, dataloader, scheduler)
assert has_ao_layers(model)
@run_first
@require_transformer_engine
@require_cuda_or_hpu
class TestTransformerEngine(unittest.TestCase):
def test_can_prepare_model_single_gpu(self):
command = get_launch_command(num_processes=1, monitor_interval=0.1)
command += ["-m", "tests.test_fp8", "--test_te"]
run_command(command)
def test_can_prepare_model_single_gpu_from_config(self):
with tempfile.TemporaryDirectory() as dir_name:
config_file = Path(dir_name) / "config.yaml"
config_file.write_text(
textwrap.dedent(
"""
distributed_type: "NO"
num_processes: 1
mixed_precision: fp8
fp8_config:
backend: TE
"""
)
)
command = get_launch_command(config_file=str(config_file), monitor_interval=0.1)
command += ["-m", "tests.test_fp8", "--test_te", "--from_config"]
run_command(command)
@require_transformer_engine_mxfp8
def test_can_prepare_model_with_mxfp8_block_scaling(self):
with tempfile.TemporaryDirectory() as dir_name:
config_file = Path(dir_name) / "config.yaml"
config_file.write_text(
textwrap.dedent(
"""
distributed_type: "NO"
num_processes: 1
mixed_precision: fp8
fp8_config:
backend: TE
use_mxfp8_block_scaling: true
"""
)
)
command = get_launch_command(config_file=str(config_file), monitor_interval=0.1)
command += ["-m", "tests.test_fp8", "--test_te", "--from_config"]
run_command(command)
@require_multi_device
def test_can_prepare_model_multi_gpu(self):
command = get_launch_command(num_processes=2, monitor_interval=0.1)
command += ["-m", "tests.test_fp8", "--test_te"]
run_command(command)
@require_deepspeed
@require_multi_device
def test_can_prepare_model_multigpu_deepspeed(self):
for zero_stage in [1, 2, 3]:
os.environ["ZERO_STAGE"] = str(zero_stage)
ds_config = {
"bf16": {"enabled": True},
"zero_optimization": {
"stage": zero_stage,
"allgather_partitions": True,
"allgather_bucket_size": 2e8,
"overlap_comm": True,
"reduce_scatter": True,
"reduce_bucket_size": 2e8,
"contiguous_gradients": True,
},
"gradient_accumulation_steps": 1,
"gradient_clipping": "auto",
"steps_per_print": 2000,
"train_batch_size": "auto",
"train_micro_batch_size_per_gpu": "auto",
"wall_clock_breakdown": False,
}
ds_config = json.dumps(ds_config)
command = get_launch_command(
num_processes=2, monitor_interval=0.1, use_deepspeed=True, deepspeed_config_file=ds_config
)
command += ["-m", "tests.test_fp8", "--test_te"]
run_command(command)
@require_deepspeed
@require_multi_device
def test_can_prepare_model_multigpu_deepspeed_from_config(self):
os.environ["ZERO_STAGE"] = str(1)
with tempfile.TemporaryDirectory() as dir_name:
config_file = Path(dir_name) / "config.yaml"
config_file.write_text(
textwrap.dedent(
"""
distributed_type: "DEEPSPEED"
deepspeed_config:
gradient_clipping: 1.0
gradient_accumulation_steps: 1
offload_optimizer_device: none
offload_param_device: none
zero3_init_flag: false
zero_stage: 1
deepspeed_multinode_launcher: standard
num_processes: 2
mixed_precision: fp8
fp8_config:
backend: TE
"""
)
)
command = get_launch_command(config_file=str(config_file), monitor_interval=0.1)
command += ["-m", "tests.test_fp8", "--test_te", "--from_config"]
run_command(command)
@require_torchao
@require_huggingface_suite
class TestTorchAO(unittest.TestCase):
def test_can_prepare_model_single_accelerator(self):
command = get_launch_command(num_processes=1, monitor_interval=0.1)
command += ["-m", "tests.test_fp8", "--test_ao"]
run_command(command)
def test_can_prepare_model_single_gpu_from_config(self):
with tempfile.TemporaryDirectory() as dir_name:
config_file = Path(dir_name) / "config.yaml"
config_file.write_text(
textwrap.dedent(
"""
distributed_type: "NO"
num_processes: 1
mixed_precision: fp8
fp8_config:
backend: AO
"""
)
)
command = get_launch_command(config_file=str(config_file), monitor_interval=0.1)
command += ["-m", "tests.test_fp8", "--test_ao", "--from_config"]
run_command(command)
@require_multi_device
def test_can_prepare_model_multi_accelerator(self):
command = get_launch_command(num_processes=2, monitor_interval=0.1)
command += ["-m", "tests.test_fp8", "--test_ao"]
run_command(command)
@require_deepspeed
@require_multi_device
def test_can_prepare_model_multi_accelerator_deepspeed(self):
for zero_stage in [1, 2, 3]:
os.environ["ZERO_STAGE"] = str(zero_stage)
ds_config = {
"bf16": {"enabled": True},
"zero_optimization": {
"stage": zero_stage,
"allgather_partitions": True,
"allgather_bucket_size": 2e8,
"overlap_comm": True,
"reduce_scatter": True,
"reduce_bucket_size": 2e8,
"contiguous_gradients": True,
},
"gradient_accumulation_steps": 1,
"gradient_clipping": "auto",
"steps_per_print": 2000,
"train_batch_size": "auto",
"train_micro_batch_size_per_gpu": "auto",
"wall_clock_breakdown": False,
}
ds_config = json.dumps(ds_config)
command = get_launch_command(
num_processes=2, monitor_interval=0.1, use_deepspeed=True, deepspeed_config_file=ds_config
)
command += ["-m", "tests.test_fp8", "--test_ao"]
run_command(command)
if __name__ == "__main__":
# TE suite
parser = argparse.ArgumentParser()
parser.add_argument("--test_te", action="store_true", default=False)
parser.add_argument("--test_ao", action="store_true", default=False)
parser.add_argument("--from_config", action="store_true", default=False)
args = parser.parse_args()
if not args.test_te and not args.test_ao:
raise ValueError("Must specify at least one of --test_te or --test_ao")
if args.test_te:
can_convert_te_model(args.from_config)
if os.environ.get("ACCELERATE_USE_DEEPSPEED", "false") == "true":
maintain_proper_deepspeed_config(int(os.environ.get("ZERO_STAGE")))
# AO suite
if args.test_ao:
can_convert_ao_model(args.from_config)
|