| 1 |
# Copyright 2022 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 unittest |
| 16 |
from pathlib import Path |
| 17 |
from unittest.mock import patch |
| 18 |
|
| 19 |
import torch |
| 20 |
from huggingface_hub.utils import GatedRepoError |
| 21 |
|
| 22 |
import accelerate.commands.test as accelerate_test_cmd |
| 23 |
from accelerate.commands.config.config_args import BaseConfig, ClusterConfig, SageMakerConfig, load_config_from_file |
| 24 |
from accelerate.commands.estimate import estimate_command, estimate_command_parser, gather_data |
| 25 |
from accelerate.commands.launch import _validate_launch_command, launch_command, launch_command_parser |
| 26 |
from accelerate.commands.to_fsdp2 import ( |
| 27 |
convert_config_to_fsdp2, |
| 28 |
to_fsdp2_command, |
| 29 |
to_fsdp2_command_parser, |
| 30 |
) |
| 31 |
from accelerate.commands.tpu import tpu_command_launcher, tpu_command_parser |
| 32 |
from accelerate.test_utils.testing import ( |
| 33 |
capture_call_output, |
| 34 |
path_in_accelerate_package, |
| 35 |
require_multi_device, |
| 36 |
require_non_hpu, |
| 37 |
require_timm, |
| 38 |
require_transformers, |
| 39 |
run_command, |
| 40 |
run_first, |
| 41 |
) |
| 42 |
from accelerate.utils import patch_environment |
| 43 |
from accelerate.utils.launch import prepare_simple_launcher_cmd_env |
| 44 |
|
| 45 |
|
| 46 |
class AccelerateLauncherTester(unittest.TestCase): |
| 47 |
""" |
| 48 |
Test case for verifying the `accelerate launch` CLI operates correctly. |
| 49 |
If a `default_config.yaml` file is located in the cache it will temporarily move it |
| 50 |
for the duration of the tests. |
| 51 |
""" |
| 52 |
|
| 53 |
test_file_path = path_in_accelerate_package("test_utils", "scripts", "test_cli.py") |
| 54 |
notebook_launcher_path = path_in_accelerate_package("test_utils", "scripts", "test_notebook.py") |
| 55 |
|
| 56 |
config_folder = Path.home() / ".cache/huggingface/accelerate" |
| 57 |
config_file = "default_config.yaml" |
| 58 |
config_path = config_folder / config_file |
| 59 |
changed_path = config_folder / "_default_config.yaml" |
| 60 |
|
| 61 |
test_config_path = Path("tests/test_configs") |
| 62 |
parser = launch_command_parser() |
| 63 |
|
| 64 |
@classmethod |
| 65 |
def setUpClass(cls): |
| 66 |
if cls.config_path.is_file(): |
| 67 |
cls.config_path.rename(cls.changed_path) |
| 68 |
|
| 69 |
@classmethod |
| 70 |
def tearDownClass(cls): |
| 71 |
if cls.changed_path.is_file(): |
| 72 |
cls.changed_path.rename(cls.config_path) |
| 73 |
|
| 74 |
@run_first |
| 75 |
def test_no_config(self): |
| 76 |
args = ["--monitor_interval", "0.1", str(self.test_file_path)] |
| 77 |
if torch.cuda.is_available() and (torch.cuda.device_count() > 1): |
| 78 |
args = ["--multi_gpu"] + args |
| 79 |
elif torch.xpu.is_available() and (torch.xpu.device_count() > 1): |
| 80 |
args = ["--multi_gpu"] + args |
| 81 |
args = self.parser.parse_args(["--monitor_interval", "0.1", str(self.test_file_path)]) |
| 82 |
launch_command(args) |
| 83 |
|
| 84 |
@run_first |
| 85 |
def test_config_compatibility(self): |
| 86 |
invalid_configs = ["fp8", "invalid", "mpi", "sagemaker"] |
| 87 |
for config in sorted(self.test_config_path.glob("**/*.yaml")): |
| 88 |
if any(invalid_config in str(config) for invalid_config in invalid_configs): |
| 89 |
continue |
| 90 |
with self.subTest(config_file=config): |
| 91 |
args = self.parser.parse_args(["--config_file", str(config), str(self.test_file_path)]) |
| 92 |
launch_command(args) |
| 93 |
|
| 94 |
@run_first |
| 95 |
def test_invalid_keys(self): |
| 96 |
config_path = self.test_config_path / "invalid_keys.yaml" |
| 97 |
with self.assertRaises( |
| 98 |
ValueError, |
| 99 |
msg="The config file at 'invalid_keys.yaml' had unknown keys ('another_invalid_key', 'invalid_key')", |
| 100 |
): |
| 101 |
args = self.parser.parse_args(["--config_file", str(config_path), str(self.test_file_path)]) |
| 102 |
launch_command(args) |
| 103 |
|
| 104 |
@run_first |
| 105 |
def test_accelerate_test(self): |
| 106 |
args = accelerate_test_cmd.test_command_parser().parse_args([]) |
| 107 |
accelerate_test_cmd.test_command(args) |
| 108 |
|
| 109 |
@run_first |
| 110 |
@require_non_hpu |
| 111 |
@require_multi_device |
| 112 |
def test_notebook_launcher(self): |
| 113 |
""" |
| 114 |
This test checks a variety of situations and scenarios |
| 115 |
with the `notebook_launcher` |
| 116 |
""" |
| 117 |
cmd = ["python", self.notebook_launcher_path] |
| 118 |
with patch_environment(omp_num_threads=1, accelerate_num_processes=2): |
| 119 |
run_command(cmd) |
| 120 |
|
| 121 |
def test_mpi_multicpu_config_cmd(self): |
| 122 |
""" |
| 123 |
Parses a launch command with a test file and the 0_28_0_mpi.yaml config. Tests getting the command and |
| 124 |
environment vars and verifies the mpirun command arg values. |
| 125 |
""" |
| 126 |
mpi_config_path = str(self.test_config_path / "0_28_0_mpi.yaml") |
| 127 |
test_file_arg = "--cpu" |
| 128 |
|
| 129 |
with patch("sys.argv", ["accelerate", str(self.test_file_path), test_file_arg]): |
| 130 |
parser = launch_command_parser() |
| 131 |
args = parser.parse_args() |
| 132 |
args.config_file = mpi_config_path |
| 133 |
args, _, _ = _validate_launch_command(args) |
| 134 |
|
| 135 |
# Mock out the check for mpirun version to simulate Intel MPI |
| 136 |
with patch("accelerate.utils.launch.which", return_value=True): |
| 137 |
with patch("accelerate.utils.launch.subprocess.check_output", return_value=b"Intel MPI"): |
| 138 |
cmd, _ = prepare_simple_launcher_cmd_env(args) |
| 139 |
|
| 140 |
# Verify the mpirun command args |
| 141 |
expected_mpirun_cmd = ["mpirun", "-f", "/home/user/hostfile", "-ppn", "4", "-n", "16"] |
| 142 |
self.assertGreater(len(cmd), len(expected_mpirun_cmd)) |
| 143 |
generated_mpirun_cmd = cmd[0 : len(expected_mpirun_cmd)] |
| 144 |
self.assertEqual(expected_mpirun_cmd, generated_mpirun_cmd) |
| 145 |
|
| 146 |
# Verify the python script and args in the mpirun command |
| 147 |
python_script_cmd = cmd[len(expected_mpirun_cmd) :] |
| 148 |
self.assertEqual(len(python_script_cmd), 3) |
| 149 |
self.assertEqual(python_script_cmd[1], str(self.test_file_path)) |
| 150 |
self.assertEqual(python_script_cmd[2], test_file_arg) |
| 151 |
|
| 152 |
def test_validate_launch_command(self): |
| 153 |
"""Test that the validation function combines args and defaults.""" |
| 154 |
parser = launch_command_parser() |
| 155 |
args = parser.parse_args( |
| 156 |
[ |
| 157 |
"--num-processes", |
| 158 |
"2", |
| 159 |
"--deepspeed_config_file", |
| 160 |
"path/to/be/accepted", |
| 161 |
"--config-file", |
| 162 |
str(self.test_config_path / "validate_launch_cmd.yaml"), |
| 163 |
"test.py", |
| 164 |
] |
| 165 |
) |
| 166 |
self.assertFalse(args.debug) |
| 167 |
self.assertTrue(args.fsdp_sync_module_states) |
| 168 |
_validate_launch_command(args) |
| 169 |
self.assertTrue(args.debug) |
| 170 |
self.assertEqual(2, args.num_processes) |
| 171 |
self.assertFalse(args.fsdp_sync_module_states) |
| 172 |
self.assertEqual("path/to/be/accepted", args.deepspeed_config_file) |
| 173 |
|
| 174 |
|
| 175 |
class LaunchArgTester(unittest.TestCase): |
| 176 |
""" |
| 177 |
Test cases revolving around the CLI wrappers |
| 178 |
""" |
| 179 |
|
| 180 |
parser = launch_command_parser() |
| 181 |
|
| 182 |
def test_hyphen(self): |
| 183 |
# Try a little from each cluster |
| 184 |
args = ["--config-file", "test.yaml", "test.py"] |
| 185 |
result = self.parser.parse_args(args) |
| 186 |
assert result.config_file == "test.yaml" |
| 187 |
assert result.multi_gpu is False |
| 188 |
|
| 189 |
args = ["--multi-gpu", "--num-processes", "4", "test.py"] |
| 190 |
result = self.parser.parse_args(args) |
| 191 |
assert result.multi_gpu is True |
| 192 |
assert result.num_processes == 4 |
| 193 |
# And use a mix |
| 194 |
args = ["--multi-gpu", "--use-deepspeed", "--use-fsdp", "--num_processes", "4", "test.py"] |
| 195 |
result = self.parser.parse_args(args) |
| 196 |
assert result.multi_gpu is True |
| 197 |
assert result.use_deepspeed is True |
| 198 |
assert result.use_fsdp is True |
| 199 |
assert result.num_processes == 4 |
| 200 |
|
| 201 |
def test_underscore(self): |
| 202 |
# Try a little from each cluster |
| 203 |
args = ["--config_file", "test.yaml", "test.py"] |
| 204 |
result = self.parser.parse_args(args) |
| 205 |
assert result.config_file == "test.yaml" |
| 206 |
|
| 207 |
args = ["--multi_gpu", "--num_processes", "4", "test.py"] |
| 208 |
result = self.parser.parse_args(args) |
| 209 |
assert result.multi_gpu is True |
| 210 |
assert result.num_processes == 4 |
| 211 |
# And use a mix |
| 212 |
args = ["--multi_gpu", "--use_deepspeed", "--use_fsdp", "--num-processes", "4", "test.py"] |
| 213 |
result = self.parser.parse_args(args) |
| 214 |
assert result.multi_gpu is True |
| 215 |
assert result.use_deepspeed is True |
| 216 |
assert result.use_fsdp is True |
| 217 |
assert result.num_processes == 4 |
| 218 |
|
| 219 |
def test_duplicate_entities(self): |
| 220 |
help_return = self.parser.format_help() |
| 221 |
args = self.parser.parse_args(["test.py"]) |
| 222 |
for arg in args.__dict__: |
| 223 |
if "_" in arg: |
| 224 |
bad_arg = f"--{arg.replace('_', '-')}" |
| 225 |
# Need an exception for `num-processes` since it's in the docstring |
| 226 |
if bad_arg == "--num-processes": |
| 227 |
assert help_return.count(bad_arg) == 1, f"Found {bad_arg} in `accelerate launch -h`" |
| 228 |
else: |
| 229 |
assert bad_arg not in help_return, f"Found {bad_arg} in `accelerate launch -h`" |
| 230 |
|
| 231 |
|
| 232 |
class ClusterConfigTester(unittest.TestCase): |
| 233 |
""" |
| 234 |
Test case for verifying the config dataclasses work |
| 235 |
""" |
| 236 |
|
| 237 |
test_config_path = Path("tests/test_configs") |
| 238 |
|
| 239 |
def test_base_config(self): |
| 240 |
# Tests that all the dataclasses can be initialized |
| 241 |
config = BaseConfig( |
| 242 |
compute_environment="LOCAL_MACHINE", |
| 243 |
distributed_type="NO", |
| 244 |
mixed_precision="fp16", |
| 245 |
debug=False, |
| 246 |
use_cpu=False, |
| 247 |
) |
| 248 |
|
| 249 |
assert config.compute_environment == "LOCAL_MACHINE" |
| 250 |
assert config.distributed_type == "NO" |
| 251 |
assert config.mixed_precision == "fp16" |
| 252 |
assert config.debug is False |
| 253 |
|
| 254 |
def test_cluster_config(self): |
| 255 |
# First normally |
| 256 |
config = ClusterConfig( |
| 257 |
compute_environment="LOCAL_MACHINE", |
| 258 |
distributed_type="NO", |
| 259 |
mixed_precision="fp16", |
| 260 |
num_processes=2, |
| 261 |
debug=False, |
| 262 |
use_cpu=False, |
| 263 |
) |
| 264 |
|
| 265 |
assert config.compute_environment == "LOCAL_MACHINE" |
| 266 |
assert config.distributed_type == "NO" |
| 267 |
assert config.mixed_precision == "fp16" |
| 268 |
assert config.debug is False |
| 269 |
|
| 270 |
# Then check with other compute environments |
| 271 |
config = ClusterConfig( |
| 272 |
compute_environment="LOCAL_MACHINE", |
| 273 |
distributed_type="MULTI_GPU", |
| 274 |
mixed_precision="fp16", |
| 275 |
debug=False, |
| 276 |
num_processes=2, |
| 277 |
enable_cpu_affinity=True, |
| 278 |
use_cpu=False, |
| 279 |
) |
| 280 |
|
| 281 |
assert config.distributed_type == "MULTI_GPU" |
| 282 |
assert config.num_processes == 2 |
| 283 |
assert config.enable_cpu_affinity is True |
| 284 |
|
| 285 |
def test_sagemaker_config(self): |
| 286 |
config = SageMakerConfig( |
| 287 |
compute_environment="AMAZON_SAGEMAKER", |
| 288 |
distributed_type="NO", |
| 289 |
mixed_precision="fp16", |
| 290 |
debug=False, |
| 291 |
use_cpu=False, |
| 292 |
ec2_instance_type="MY_TYPE", |
| 293 |
iam_role_name="MY_ROLE", |
| 294 |
) |
| 295 |
|
| 296 |
assert config.compute_environment == "AMAZON_SAGEMAKER" |
| 297 |
assert config.ec2_instance_type == "MY_TYPE" |
| 298 |
assert config.iam_role_name == "MY_ROLE" |
| 299 |
|
| 300 |
config = load_config_from_file(str(self.test_config_path / "0_30_0_sagemaker.yaml")) |
| 301 |
|
| 302 |
|
| 303 |
class TpuConfigTester(unittest.TestCase): |
| 304 |
""" |
| 305 |
Test case for verifying the `accelerate tpu-config` CLI passes the right `gcloud` command. |
| 306 |
""" |
| 307 |
|
| 308 |
tpu_name = "test-tpu" |
| 309 |
tpu_zone = "us-central1-a" |
| 310 |
command = "ls" |
| 311 |
cmd = ["accelerate", "tpu-config"] |
| 312 |
base_output = "cd /usr/share" |
| 313 |
command_file = "tests/test_samples/test_command_file.sh" |
| 314 |
gcloud = "Running gcloud compute tpus tpu-vm ssh" |
| 315 |
|
| 316 |
def setUp(self): |
| 317 |
self.parser = tpu_command_parser() |
| 318 |
|
| 319 |
def test_base(self): |
| 320 |
args = self.parser.parse_args( |
| 321 |
["--command", self.command, "--tpu_zone", self.tpu_zone, "--tpu_name", self.tpu_name, "--debug"] |
| 322 |
) |
| 323 |
output = capture_call_output(tpu_command_launcher, args) |
| 324 |
assert f"{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all" in output |
| 325 |
|
| 326 |
def test_base_backward_compatibility(self): |
| 327 |
args = self.parser.parse_args( |
| 328 |
[ |
| 329 |
"--config_file", |
| 330 |
"tests/test_configs/0_12_0.yaml", |
| 331 |
"--command", |
| 332 |
self.command, |
| 333 |
"--tpu_zone", |
| 334 |
self.tpu_zone, |
| 335 |
"--tpu_name", |
| 336 |
self.tpu_name, |
| 337 |
"--debug", |
| 338 |
] |
| 339 |
) |
| 340 |
output = capture_call_output(tpu_command_launcher, args) |
| 341 |
assert f"{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all" in output |
| 342 |
|
| 343 |
def test_with_config_file(self): |
| 344 |
args = self.parser.parse_args(["--config_file", "tests/test_configs/latest.yaml", "--debug"]) |
| 345 |
output = capture_call_output(tpu_command_launcher, args) |
| 346 |
assert ( |
| 347 |
f'{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all' |
| 348 |
in output |
| 349 |
) |
| 350 |
|
| 351 |
def test_with_config_file_and_command(self): |
| 352 |
args = self.parser.parse_args( |
| 353 |
["--config_file", "tests/test_configs/latest.yaml", "--command", self.command, "--debug"] |
| 354 |
) |
| 355 |
output = capture_call_output(tpu_command_launcher, args) |
| 356 |
assert f"{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all" in output |
| 357 |
|
| 358 |
def test_with_config_file_and_multiple_command(self): |
| 359 |
args = self.parser.parse_args( |
| 360 |
[ |
| 361 |
"--config_file", |
| 362 |
"tests/test_configs/latest.yaml", |
| 363 |
"--command", |
| 364 |
self.command, |
| 365 |
"--command", |
| 366 |
'echo "Hello World"', |
| 367 |
"--debug", |
| 368 |
] |
| 369 |
) |
| 370 |
output = capture_call_output(tpu_command_launcher, args) |
| 371 |
assert ( |
| 372 |
f'{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls; echo "Hello World" --worker all' |
| 373 |
in output |
| 374 |
) |
| 375 |
|
| 376 |
def test_with_config_file_and_command_file(self): |
| 377 |
args = self.parser.parse_args( |
| 378 |
["--config_file", "tests/test_configs/latest.yaml", "--command_file", self.command_file, "--debug"] |
| 379 |
) |
| 380 |
output = capture_call_output(tpu_command_launcher, args) |
| 381 |
assert ( |
| 382 |
f'{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all' |
| 383 |
in output |
| 384 |
) |
| 385 |
|
| 386 |
def test_with_config_file_and_command_file_backward_compatibility(self): |
| 387 |
args = self.parser.parse_args( |
| 388 |
[ |
| 389 |
"--config_file", |
| 390 |
"tests/test_configs/0_12_0.yaml", |
| 391 |
"--command_file", |
| 392 |
self.command_file, |
| 393 |
"--tpu_zone", |
| 394 |
self.tpu_zone, |
| 395 |
"--tpu_name", |
| 396 |
self.tpu_name, |
| 397 |
"--debug", |
| 398 |
] |
| 399 |
) |
| 400 |
output = capture_call_output(tpu_command_launcher, args) |
| 401 |
assert ( |
| 402 |
f'{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all' |
| 403 |
in output |
| 404 |
) |
| 405 |
|
| 406 |
def test_accelerate_install(self): |
| 407 |
args = self.parser.parse_args( |
| 408 |
["--config_file", "tests/test_configs/latest.yaml", "--install_accelerate", "--debug"] |
| 409 |
) |
| 410 |
output = capture_call_output(tpu_command_launcher, args) |
| 411 |
assert ( |
| 412 |
f'{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate -U; echo "hello world"; echo "this is a second command" --worker all' |
| 413 |
in output |
| 414 |
) |
| 415 |
|
| 416 |
def test_accelerate_install_version(self): |
| 417 |
args = self.parser.parse_args( |
| 418 |
[ |
| 419 |
"--config_file", |
| 420 |
"tests/test_configs/latest.yaml", |
| 421 |
"--install_accelerate", |
| 422 |
"--accelerate_version", |
| 423 |
"12.0.0", |
| 424 |
"--debug", |
| 425 |
] |
| 426 |
) |
| 427 |
output = capture_call_output(tpu_command_launcher, args) |
| 428 |
assert ( |
| 429 |
f'{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate==12.0.0; echo "hello world"; echo "this is a second command" --worker all' |
| 430 |
in output |
| 431 |
) |
| 432 |
|
| 433 |
|
| 434 |
class ModelEstimatorTester(unittest.TestCase): |
| 435 |
""" |
| 436 |
Test case for checking the output of `accelerate estimate-memory` is correct. |
| 437 |
|
| 438 |
- Uses `estimate_command` when trying to catch raised errors |
| 439 |
- Uses `gather_data` when just verifying the calculations are correct |
| 440 |
""" |
| 441 |
|
| 442 |
parser = estimate_command_parser() |
| 443 |
|
| 444 |
def test_invalid_model_name(self): |
| 445 |
with self.assertRaises(OSError, msg="Repo for model `somebrokenname` does not exist on the Hub"): |
| 446 |
args = self.parser.parse_args(["somebrokenname"]) |
| 447 |
estimate_command(args) |
| 448 |
|
| 449 |
@require_timm |
| 450 |
def test_invalid_model_name_timm(self): |
| 451 |
with self.assertRaises(RuntimeError, msg="Tried to load `muellerzr/dummy` with `timm` but"): |
| 452 |
args = self.parser.parse_args(["muellerzr/dummy", "--library_name", "timm"]) |
| 453 |
estimate_command(args) |
| 454 |
|
| 455 |
@require_transformers |
| 456 |
def test_invalid_model_name_transformers(self): |
| 457 |
with self.assertRaises(RuntimeError, msg="Tried to load `muellerzr/dummy` with `transformers` but"): |
| 458 |
args = self.parser.parse_args(["muellerzr/dummy", "--library_name", "transformers"]) |
| 459 |
estimate_command(args) |
| 460 |
|
| 461 |
def test_no_metadata(self): |
| 462 |
with self.assertRaises( |
| 463 |
ValueError, msg="Model `muellerzr/dummy` does not have any library metadata on the Hub" |
| 464 |
): |
| 465 |
args = self.parser.parse_args(["muellerzr/dummy"]) |
| 466 |
estimate_command(args) |
| 467 |
|
| 468 |
def test_gated(self): |
| 469 |
with self.assertRaises( |
| 470 |
(GatedRepoError, EnvironmentError), |
| 471 |
msg="Repo for model `meta-llama/Llama-2-7b-hf` is gated or environment error occurred", |
| 472 |
): |
| 473 |
args = self.parser.parse_args(["meta-llama/Llama-2-7b-hf"]) |
| 474 |
with patch_environment(hf_hub_disable_implicit_token="1"): |
| 475 |
estimate_command(args) |
| 476 |
|
| 477 |
@require_transformers |
| 478 |
def test_remote_code(self): |
| 479 |
# Also tests that custom `Auto` classes work |
| 480 |
args = self.parser.parse_args(["hf-internal-testing/test_dynamic_model"]) |
| 481 |
with self.assertRaises(ValueError, msg="--trust_remote_code"): |
| 482 |
gather_data(args) |
| 483 |
|
| 484 |
# Verify it works with the flag |
| 485 |
args = self.parser.parse_args(["hf-internal-testing/test_dynamic_model", "--trust_remote_code"]) |
| 486 |
gather_data(args) |
| 487 |
|
| 488 |
@require_transformers |
| 489 |
def test_explicit_dtypes(self): |
| 490 |
args = self.parser.parse_args(["bert-base-cased", "--dtypes", "float32", "float16"]) |
| 491 |
output = gather_data(args) |
| 492 |
# The largest layer and total size of the model in bytes |
| 493 |
largest_layer, total_size = 90669056, 433249280 |
| 494 |
# Check that full precision -> int4 is calculating correctly |
| 495 |
assert len(output) == 2, f"Output was missing a precision, expected 2 but received {len(output)}" |
| 496 |
|
| 497 |
for i, factor in enumerate([1, 2]): |
| 498 |
precision = 32 // factor |
| 499 |
precision_str = f"float{precision}" |
| 500 |
largest_layer_estimate = largest_layer / factor |
| 501 |
total_size_estimate = total_size / factor |
| 502 |
total_training_size_estimate = total_size_estimate * 4 |
| 503 |
|
| 504 |
assert precision_str == output[i][0], f"Output is missing precision `{precision_str}`" |
| 505 |
assert largest_layer_estimate == output[i][1], ( |
| 506 |
f"Calculation for largest layer size in `{precision_str}` is incorrect." |
| 507 |
) |
| 508 |
|
| 509 |
assert total_size_estimate == output[i][2], ( |
| 510 |
f"Calculation for total size in `{precision_str}` is incorrect." |
| 511 |
) |
| 512 |
assert total_training_size_estimate == max(output[i][3].values()), ( |
| 513 |
f"Calculation for total training size in `{precision_str}` is incorrect." |
| 514 |
) |
| 515 |
|
| 516 |
@require_transformers |
| 517 |
def test_transformers_model(self): |
| 518 |
args = self.parser.parse_args(["bert-base-cased", "--dtypes", "float32"]) |
| 519 |
output = gather_data(args) |
| 520 |
# The largest layer and total size of the model in bytes |
| 521 |
largest_layer, total_size = 90669056, 433249280 |
| 522 |
assert largest_layer == output[0][1], ( |
| 523 |
f"Calculation for largest layer size in `fp32` is incorrect, expected {largest_layer} but received {output[0][1]}" |
| 524 |
) |
| 525 |
assert total_size == output[0][2], ( |
| 526 |
f"Calculation for total size in `fp32` is incorrect, expected {total_size} but received {output[0][2]}" |
| 527 |
) |
| 528 |
|
| 529 |
@require_transformers |
| 530 |
def test_no_split_modules(self): |
| 531 |
# idefics-80b-instruct has ["IdeficsDecoderLayer", "IdeficsGatedCrossAttentionLayer"] |
| 532 |
args = self.parser.parse_args(["HuggingFaceM4/idefics-80b-instruct", "--dtypes", "float32"]) |
| 533 |
output = gather_data(args) |
| 534 |
# without factoring in `no_split` modules, the largest layer is 721420288 bytes |
| 535 |
assert output[0][1] != 721420288, "Largest layer calculation incorrect, did not factor in `no_split` modules." |
| 536 |
# the real answer is 3240165632 bytes |
| 537 |
assert output[0][1] == 3240165632 |
| 538 |
|
| 539 |
@require_timm |
| 540 |
def test_timm_model(self): |
| 541 |
args = self.parser.parse_args(["timm/resnet50.a1_in1k", "--library_name", "timm"]) |
| 542 |
output = gather_data(args) |
| 543 |
# The largest layer and total size of the model in bytes |
| 544 |
largest_layer, total_size = 9437184, 102441032 |
| 545 |
assert largest_layer == output[0][1], ( |
| 546 |
f"Calculation for largest layer size in `fp32` is incorrect, expected {largest_layer} but received {output[0][1]}" |
| 547 |
) |
| 548 |
assert total_size == output[0][2], ( |
| 549 |
f"Calculation for total size in `fp32` is incorrect, expected {total_size} but received {output[0][2]}" |
| 550 |
) |
| 551 |
|
| 552 |
|
| 553 |
class ToFSDP2Tester(unittest.TestCase): |
| 554 |
""" |
| 555 |
Test case for verifying the `accelerate to-fsdp2` CLI outputs. |
| 556 |
""" |
| 557 |
|
| 558 |
parser = to_fsdp2_command_parser() |
| 559 |
test_config_path = Path("tests/test_configs") |
| 560 |
|
| 561 |
@classmethod |
| 562 |
def setUpClass(cls): |
| 563 |
if (cls.test_config_path / "latest_fsdp.yaml").exists(): |
| 564 |
cls.original_config = load_config_from_file(str(cls.test_config_path / "latest_fsdp.yaml")) |
| 565 |
|
| 566 |
@classmethod |
| 567 |
def tearDownClass(cls): |
| 568 |
if cls.original_config is not None: |
| 569 |
cls.original_config.to_yaml_file(str(cls.test_config_path / "latest_fsdp.yaml")) |
| 570 |
|
| 571 |
def tearDown(self): |
| 572 |
if (self.test_config_path / "output.yaml").exists(): |
| 573 |
(self.test_config_path / "output.yaml").unlink() |
| 574 |
|
| 575 |
def test_nonexistent_config_file(self): |
| 576 |
with self.assertRaises(FileNotFoundError, msg="Config file `nonexistent.yaml` not found"): |
| 577 |
args = self.parser.parse_args(["--config_file", "nonexistent.yaml"]) |
| 578 |
to_fsdp2_command(args) |
| 579 |
|
| 580 |
def test_no_output_without_overwrite(self): |
| 581 |
with self.assertRaises(ValueError, msg="If --overwrite is not set, --output_file must be provided"): |
| 582 |
args = self.parser.parse_args(["--config_file", str(self.test_config_path / "latest_fsdp.yaml")]) |
| 583 |
to_fsdp2_command(args) |
| 584 |
|
| 585 |
def test_convert_config_drops_removed_and_unimplemented_keys(self): |
| 586 |
config = { |
| 587 |
"fsdp_config": { |
| 588 |
"fsdp_backward_prefetch": "BACKWARD_PRE", # REMOVED |
| 589 |
"fsdp_use_orig_params": True, # REMOVED |
| 590 |
"fsdp_sync_module_states": True, # REMOVED |
| 591 |
"fsdp_forward_prefetch": True, # NOT_YET_IMPLEMENTED |
| 592 |
"fsdp_sharding_strategy": "FULL_SHARD", # renamed + value-mapped |
| 593 |
"fsdp_offload_params": True, # carried over (maps to itself) |
| 594 |
"some_unknown_key": 5, # not in the mapping -> carried over |
| 595 |
} |
| 596 |
} |
| 597 |
out = convert_config_to_fsdp2(config)["fsdp_config"] |
| 598 |
|
| 599 |
# FSDP1-only keys must not leak into the FSDP2 config |
| 600 |
for removed in ( |
| 601 |
"fsdp_backward_prefetch", |
| 602 |
"fsdp_use_orig_params", |
| 603 |
"fsdp_sync_module_states", |
| 604 |
"fsdp_forward_prefetch", |
| 605 |
): |
| 606 |
self.assertNotIn(removed, out) |
| 607 |
|
| 608 |
# renamed key + value mapping, pass-through keys, and version bump |
| 609 |
self.assertEqual(out["fsdp_reshard_after_forward"], True) |
| 610 |
self.assertNotIn("fsdp_sharding_strategy", out) |
| 611 |
self.assertEqual(out["fsdp_offload_params"], True) |
| 612 |
self.assertEqual(out["some_unknown_key"], 5) |
| 613 |
self.assertEqual(out["fsdp_version"], 2) |
| 614 |
|
| 615 |
@patch("pathlib.Path.exists") |
| 616 |
def test_overwrite_when_output_file_exists(self, mock_exists): |
| 617 |
mock_exists.side_effect = ( |
| 618 |
lambda: str(mock_exists._mock_self) == "output.yaml" or mock_exists._mock_self.exists() |
| 619 |
) |
| 620 |
|
| 621 |
with self.assertRaises( |
| 622 |
FileExistsError, msg="Output file `output.yaml` already exists and --overwrite is not set" |
| 623 |
): |
| 624 |
args = self.parser.parse_args( |
| 625 |
["--config_file", str(self.test_config_path / "latest_fsdp.yaml"), "--output_file", "output.yaml"] |
| 626 |
) |
| 627 |
to_fsdp2_command(args) |
| 628 |
|
| 629 |
def test_fsdp2_config(self): |
| 630 |
args = self.parser.parse_args( |
| 631 |
[ |
| 632 |
"--config_file", |
| 633 |
str(self.test_config_path / "latest_fsdp.yaml"), |
| 634 |
"--output_file", |
| 635 |
str(self.test_config_path / "output.yaml"), |
| 636 |
] |
| 637 |
) |
| 638 |
to_fsdp2_command(args) |
| 639 |
|
| 640 |
config = load_config_from_file(str(self.test_config_path / "output.yaml")) |
| 641 |
assert isinstance(config, ClusterConfig) |
| 642 |
assert config.fsdp_config["fsdp_version"] == 2 |
| 643 |
|
| 644 |
def test_config_already_fsdp2(self): |
| 645 |
args = self.parser.parse_args( |
| 646 |
[ |
| 647 |
"--config_file", |
| 648 |
str(self.test_config_path / "latest_fsdp.yaml"), |
| 649 |
"--output_file", |
| 650 |
str(self.test_config_path / "output.yaml"), |
| 651 |
] |
| 652 |
) |
| 653 |
|
| 654 |
mock_config = {"fsdp_config": {"fsdp_version": 2}} |
| 655 |
|
| 656 |
with patch("accelerate.commands.to_fsdp2.load_config", return_value=mock_config): |
| 657 |
with self.assertLogs(level="WARNING") as cm: |
| 658 |
to_fsdp2_command(args) |
| 659 |
|
| 660 |
assert "Config already specifies FSDP2, skipping conversion..." in cm.output[0] |
| 661 |
|
| 662 |
# Has to be the last test because it overwrites the config file |
| 663 |
def test_fsdp2_overwrite(self): |
| 664 |
args = self.parser.parse_args( |
| 665 |
[ |
| 666 |
"--config_file", |
| 667 |
str(self.test_config_path / "latest_fsdp.yaml"), |
| 668 |
"--overwrite", |
| 669 |
] |
| 670 |
) |
| 671 |
to_fsdp2_command(args) |
| 672 |
|
| 673 |
config = load_config_from_file(str(self.test_config_path / "latest_fsdp.yaml")) |
| 674 |
assert isinstance(config, ClusterConfig) |
| 675 |
assert config.fsdp_config["fsdp_version"] == 2 |