| 1 |
# Copyright 2021 The HuggingFace 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 |
import inspect |
| 16 |
import os |
| 17 |
from dataclasses import dataclass |
| 18 |
|
| 19 |
import torch |
| 20 |
|
| 21 |
from accelerate import Accelerator, DistributedDataParallelKwargs, GradScalerKwargs |
| 22 |
from accelerate.state import AcceleratorState |
| 23 |
from accelerate.test_utils import ( |
| 24 |
DEFAULT_LAUNCH_COMMAND, |
| 25 |
execute_subprocess_async, |
| 26 |
path_in_accelerate_package, |
| 27 |
require_fp16, |
| 28 |
require_multi_device, |
| 29 |
require_non_cpu, |
| 30 |
run_first, |
| 31 |
) |
| 32 |
from accelerate.test_utils.testing import AccelerateTestCase, slow |
| 33 |
from accelerate.utils import ( |
| 34 |
AutocastKwargs, |
| 35 |
KwargsHandler, |
| 36 |
ProfileKwargs, |
| 37 |
TorchDynamoPlugin, |
| 38 |
clear_environment, |
| 39 |
) |
| 40 |
from accelerate.utils.dataclasses import DistributedType |
| 41 |
|
| 42 |
|
| 43 |
@dataclass |
| 44 |
class MockClass(KwargsHandler): |
| 45 |
a: int = 0 |
| 46 |
b: bool = False |
| 47 |
c: float = 3.0 |
| 48 |
|
| 49 |
|
| 50 |
class KwargsHandlerTester(AccelerateTestCase): |
| 51 |
def test_kwargs_handler(self): |
| 52 |
# If no defaults are changed, `to_kwargs` returns an empty dict. |
| 53 |
assert MockClass().to_kwargs() == {} |
| 54 |
assert MockClass(a=2).to_kwargs() == {"a": 2} |
| 55 |
assert MockClass(a=2, b=True).to_kwargs() == {"a": 2, "b": True} |
| 56 |
assert MockClass(a=2, c=2.25).to_kwargs() == {"a": 2, "c": 2.25} |
| 57 |
|
| 58 |
@require_fp16 |
| 59 |
@require_non_cpu |
| 60 |
def test_grad_scaler_kwargs(self): |
| 61 |
# If no defaults are changed, `to_kwargs` returns an empty dict. |
| 62 |
scaler_handler = GradScalerKwargs(init_scale=1024, growth_factor=2) |
| 63 |
AcceleratorState._reset_state() |
| 64 |
accelerator = Accelerator(mixed_precision="fp16", kwargs_handlers=[scaler_handler]) |
| 65 |
assert accelerator.mixed_precision == "fp16" |
| 66 |
scaler = accelerator.scaler |
| 67 |
|
| 68 |
# Check the kwargs have been applied |
| 69 |
assert scaler._init_scale == 1024.0 |
| 70 |
assert scaler._growth_factor == 2.0 |
| 71 |
|
| 72 |
# Check the other values are at the default |
| 73 |
assert scaler._backoff_factor == 0.5 |
| 74 |
assert scaler._growth_interval == 2000 |
| 75 |
assert scaler._enabled is True |
| 76 |
|
| 77 |
@run_first |
| 78 |
@require_multi_device |
| 79 |
def test_ddp_kwargs(self): |
| 80 |
cmd = DEFAULT_LAUNCH_COMMAND + [inspect.getfile(self.__class__)] |
| 81 |
execute_subprocess_async(cmd) |
| 82 |
|
| 83 |
@require_fp16 |
| 84 |
@require_non_cpu |
| 85 |
def test_autocast_kwargs(self): |
| 86 |
kwargs = AutocastKwargs(enabled=False) |
| 87 |
AcceleratorState._reset_state() |
| 88 |
accelerator = Accelerator(mixed_precision="fp16") |
| 89 |
|
| 90 |
a_float32 = torch.rand((8, 8), device=accelerator.device) |
| 91 |
b_float32 = torch.rand((8, 8), device=accelerator.device) |
| 92 |
c_float32 = torch.rand((8, 8), device=accelerator.device) |
| 93 |
d_float32 = torch.rand((8, 8), device=accelerator.device) |
| 94 |
|
| 95 |
with accelerator.autocast(): |
| 96 |
e_float16 = torch.mm(a_float32, b_float32) |
| 97 |
assert e_float16.dtype == torch.float16 |
| 98 |
|
| 99 |
with accelerator.autocast(autocast_handler=kwargs): |
| 100 |
# Convert e_float16 to float32 |
| 101 |
f_float32 = torch.mm(c_float32, e_float16.float()) |
| 102 |
assert f_float32.dtype == torch.float32 |
| 103 |
|
| 104 |
g_float16 = torch.mm(d_float32, f_float32) |
| 105 |
# We should be back in fp16 |
| 106 |
assert g_float16.dtype == torch.float16 |
| 107 |
|
| 108 |
@slow |
| 109 |
def test_profile_kwargs(self): |
| 110 |
# Arrange |
| 111 |
schedule_options = [ |
| 112 |
dict(wait=1, warmup=1, active=2, repeat=1), |
| 113 |
dict(wait=2, warmup=2, active=2, repeat=2), |
| 114 |
dict(wait=0, warmup=1, active=3, repeat=3, skip_first=1), |
| 115 |
dict(wait=3, warmup=2, active=1, repeat=1, skip_first=2), |
| 116 |
dict(wait=1, warmup=0, active=1, repeat=5), |
| 117 |
] |
| 118 |
|
| 119 |
total_steps = 100 |
| 120 |
|
| 121 |
for option in schedule_options: |
| 122 |
count = 0 |
| 123 |
table_outputs = [] |
| 124 |
steps_per_cycle = option["wait"] + option["warmup"] + option["active"] |
| 125 |
effective_steps = max(0, total_steps - option.get("skip_first", 0)) |
| 126 |
cycles = effective_steps // steps_per_cycle |
| 127 |
if option["repeat"] > 0: |
| 128 |
expected_count = min(cycles, option["repeat"]) |
| 129 |
else: |
| 130 |
expected_count = cycles |
| 131 |
|
| 132 |
def on_trace_ready(prof): |
| 133 |
nonlocal count |
| 134 |
nonlocal table_outputs |
| 135 |
|
| 136 |
count += 1 |
| 137 |
table_outputs.append(prof.key_averages().table(sort_by="cpu_time_total", row_limit=-1)) |
| 138 |
|
| 139 |
kwargs = ProfileKwargs(activities=["cpu"], on_trace_ready=on_trace_ready, schedule_option=option) |
| 140 |
accelerator = Accelerator(kwargs_handlers=[kwargs]) |
| 141 |
|
| 142 |
# Act |
| 143 |
with accelerator.profile() as prof: |
| 144 |
for _ in range(total_steps): |
| 145 |
prof.step() |
| 146 |
torch.tensor([1, 2, 3, 4, 5], device=accelerator.device) |
| 147 |
|
| 148 |
# Assert |
| 149 |
assert isinstance(prof, torch.profiler.profile) |
| 150 |
assert count == expected_count, f"Option: {option}, Expected count: {expected_count}, but got {count}" |
| 151 |
for output in table_outputs: |
| 152 |
self.assertIn("CPU time total:", output) |
| 153 |
|
| 154 |
def test_torch_dynamo_plugin(self): |
| 155 |
with clear_environment(): |
| 156 |
prefix = "ACCELERATE_DYNAMO_" |
| 157 |
# nvfuser's dynamo backend name is "nvprims_nvfuser" |
| 158 |
# use "nvfuser" here to cause exception if this test causes os.environ changed permanently |
| 159 |
os.environ[prefix + "BACKEND"] = "aot_ts_nvfuser" |
| 160 |
os.environ[prefix + "MODE"] = "reduce-overhead" |
| 161 |
|
| 162 |
dynamo_plugin_kwargs = TorchDynamoPlugin().to_kwargs() |
| 163 |
assert dynamo_plugin_kwargs == {"backend": "aot_ts_nvfuser", "mode": "reduce-overhead"} |
| 164 |
assert os.environ.get(prefix + "BACKEND") != "aot_ts_nvfuser" |
| 165 |
|
| 166 |
@run_first |
| 167 |
@require_multi_device |
| 168 |
def test_ddp_comm_hook(self): |
| 169 |
cmd = DEFAULT_LAUNCH_COMMAND + [path_in_accelerate_package("test_utils", "scripts", "test_ddp_comm_hook.py")] |
| 170 |
execute_subprocess_async(cmd) |
| 171 |
|
| 172 |
|
| 173 |
def main(): |
| 174 |
ddp_scaler = DistributedDataParallelKwargs(bucket_cap_mb=15, find_unused_parameters=True) |
| 175 |
accelerator = Accelerator(kwargs_handlers=[ddp_scaler]) |
| 176 |
|
| 177 |
# Skip this test due to TorchXLA not using torch.nn.parallel.DistributedDataParallel for model wrapping. |
| 178 |
if accelerator.distributed_type == DistributedType.XLA: |
| 179 |
return |
| 180 |
|
| 181 |
model = torch.nn.Linear(100, 200) |
| 182 |
model = accelerator.prepare(model) |
| 183 |
|
| 184 |
# Check the values changed in kwargs |
| 185 |
error_msg = "" |
| 186 |
observed_bucket_cap_map = model.bucket_bytes_cap // (1024 * 1024) |
| 187 |
if observed_bucket_cap_map != 15: |
| 188 |
error_msg += f"Kwargs badly passed, should have `15` but found {observed_bucket_cap_map}.\n" |
| 189 |
if model.find_unused_parameters is not True: |
| 190 |
error_msg += f"Kwargs badly passed, should have `True` but found {model.find_unused_parameters}.\n" |
| 191 |
|
| 192 |
# Check the values of the defaults |
| 193 |
if model.dim != 0: |
| 194 |
error_msg += f"Default value not respected, should have `0` but found {model.dim}.\n" |
| 195 |
if model.broadcast_buffers is not True: |
| 196 |
error_msg += f"Default value not respected, should have `True` but found {model.broadcast_buffers}.\n" |
| 197 |
if model.gradient_as_bucket_view is not False: |
| 198 |
error_msg += f"Default value not respected, should have `False` but found {model.gradient_as_bucket_view}.\n" |
| 199 |
|
| 200 |
# Raise error at the end to make sure we don't stop at the first failure. |
| 201 |
if len(error_msg) > 0: |
| 202 |
raise ValueError(error_msg) |
| 203 |
|
| 204 |
|
| 205 |
if __name__ == "__main__": |
| 206 |
main() |