| 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 ast |
| 16 |
import os |
| 17 |
import re |
| 18 |
import shutil |
| 19 |
import tempfile |
| 20 |
import unittest |
| 21 |
from pathlib import Path |
| 22 |
from typing import Optional |
| 23 |
from unittest import mock, skip |
| 24 |
|
| 25 |
import torch |
| 26 |
|
| 27 |
from accelerate.test_utils.examples import compare_against_test |
| 28 |
from accelerate.test_utils.testing import ( |
| 29 |
TempDirTestCase, |
| 30 |
get_launch_command, |
| 31 |
is_hpu_available, |
| 32 |
is_xpu_available, |
| 33 |
require_fp16, |
| 34 |
require_huggingface_suite, |
| 35 |
require_multi_device, |
| 36 |
require_pippy, |
| 37 |
require_schedulefree, |
| 38 |
require_trackers, |
| 39 |
run_command, |
| 40 |
run_first, |
| 41 |
slow, |
| 42 |
) |
| 43 |
from accelerate.utils import write_basic_config |
| 44 |
|
| 45 |
|
| 46 |
# DataLoaders built from `test_samples/MRPC` for quick testing |
| 47 |
# Should mock `{script_name}.get_dataloaders` via: |
| 48 |
# @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders) |
| 49 |
|
| 50 |
EXCLUDE_EXAMPLES = [ |
| 51 |
"cross_validation.py", |
| 52 |
"checkpointing.py", |
| 53 |
"gradient_accumulation.py", |
| 54 |
"local_sgd.py", |
| 55 |
"multi_process_metrics.py", |
| 56 |
"memory.py", |
| 57 |
"schedule_free.py", |
| 58 |
"tracking.py", |
| 59 |
"automatic_gradient_accumulation.py", |
| 60 |
"gradient_accumulation_for_autoregressive_models.py", |
| 61 |
"fsdp_with_peak_mem_tracking.py", |
| 62 |
"deepspeed_with_config_support.py", |
| 63 |
"megatron_lm_gpt_pretraining.py", |
| 64 |
"early_stopping.py", |
| 65 |
"ddp_comm_hook.py", |
| 66 |
"profiler.py", |
| 67 |
] |
| 68 |
|
| 69 |
|
| 70 |
class ExampleDifferenceTests(unittest.TestCase): |
| 71 |
""" |
| 72 |
This TestCase checks that all of the `complete_*` scripts contain all of the |
| 73 |
information found in the `by_feature` scripts, line for line. If one fails, |
| 74 |
then a complete example does not contain all of the features in the features |
| 75 |
scripts, and should be updated. |
| 76 |
|
| 77 |
Each example script should be a single test (such as `test_nlp_example`), |
| 78 |
and should run `one_complete_example` twice: once with `parser_only=True`, |
| 79 |
and the other with `parser_only=False`. This is so that when the test |
| 80 |
failures are returned to the user, they understand if the discrepancy lies in |
| 81 |
the `main` function, or the `training_loop` function. Otherwise it will be |
| 82 |
unclear. |
| 83 |
|
| 84 |
Also, if there are any expected differences between the base script used and |
| 85 |
`complete_nlp_example.py` (the canonical base script), these should be included in |
| 86 |
`special_strings`. These would be differences in how something is logged, print statements, |
| 87 |
etc (such as calls to `Accelerate.log()`) |
| 88 |
""" |
| 89 |
|
| 90 |
by_feature_path = Path("examples", "by_feature").resolve() |
| 91 |
examples_path = Path("examples").resolve() |
| 92 |
|
| 93 |
def one_complete_example( |
| 94 |
self, |
| 95 |
complete_file_name: str, |
| 96 |
parser_only: bool, |
| 97 |
secondary_filename: Optional[str] = None, |
| 98 |
special_strings: Optional[list] = None, |
| 99 |
): |
| 100 |
""" |
| 101 |
Tests a single `complete` example against all of the implemented `by_feature` scripts |
| 102 |
|
| 103 |
Args: |
| 104 |
complete_file_name (`str`): |
| 105 |
The filename of a complete example |
| 106 |
parser_only (`bool`): |
| 107 |
Whether to look at the main training function, or the argument parser |
| 108 |
secondary_filename (`str`, *optional*): |
| 109 |
A potential secondary base file to strip all script information not relevant for checking, |
| 110 |
such as "cv_example.py" when testing "complete_cv_example.py" |
| 111 |
special_strings (`list`, *optional*): |
| 112 |
A list of strings to potentially remove before checking no differences are left. These should be |
| 113 |
diffs that are file specific, such as different logging variations between files. |
| 114 |
""" |
| 115 |
self.maxDiff = None |
| 116 |
for item in os.listdir(self.by_feature_path): |
| 117 |
if item not in EXCLUDE_EXAMPLES: |
| 118 |
item_path = self.by_feature_path / item |
| 119 |
if item_path.is_file() and item_path.suffix == ".py": |
| 120 |
with self.subTest( |
| 121 |
tested_script=complete_file_name, |
| 122 |
feature_script=item, |
| 123 |
tested_section="main()" if parser_only else "training_function()", |
| 124 |
): |
| 125 |
diff = compare_against_test( |
| 126 |
self.examples_path / complete_file_name, item_path, parser_only, secondary_filename |
| 127 |
) |
| 128 |
diff = "\n".join(diff) |
| 129 |
if special_strings is not None: |
| 130 |
for string in special_strings: |
| 131 |
diff = diff.replace(string, "") |
| 132 |
assert diff == "" |
| 133 |
|
| 134 |
def test_nlp_examples(self): |
| 135 |
self.one_complete_example("complete_nlp_example.py", True) |
| 136 |
self.one_complete_example("complete_nlp_example.py", False) |
| 137 |
|
| 138 |
def test_cv_examples(self): |
| 139 |
cv_path = (self.examples_path / "cv_example.py").resolve() |
| 140 |
special_strings = [ |
| 141 |
" " * 16 + "{\n\n", |
| 142 |
" " * 20 + '"accuracy": eval_metric["accuracy"],\n\n', |
| 143 |
" " * 20 + '"f1": eval_metric["f1"],\n\n', |
| 144 |
" " * 20 + '"train_loss": total_loss.item() / len(train_dataloader),\n\n', |
| 145 |
" " * 20 + '"epoch": epoch,\n\n', |
| 146 |
" " * 16 + "},\n\n", |
| 147 |
" " * 16 + "step=epoch,\n", |
| 148 |
" " * 12, |
| 149 |
" " * 8 + "for step, batch in enumerate(active_dataloader):\n", |
| 150 |
] |
| 151 |
self.one_complete_example("complete_cv_example.py", True, cv_path, special_strings) |
| 152 |
self.one_complete_example("complete_cv_example.py", False, cv_path, special_strings) |
| 153 |
|
| 154 |
|
| 155 |
@mock.patch.dict(os.environ, {"TESTING_MOCKED_DATALOADERS": "1"}) |
| 156 |
@require_huggingface_suite |
| 157 |
@run_first |
| 158 |
class FeatureExamplesTests(TempDirTestCase): |
| 159 |
clear_on_setup = False |
| 160 |
|
| 161 |
@classmethod |
| 162 |
def setUpClass(cls): |
| 163 |
super().setUpClass() |
| 164 |
cls._tmpdir = tempfile.mkdtemp() |
| 165 |
cls.config_file = Path(cls._tmpdir) / "default_config.yml" |
| 166 |
|
| 167 |
write_basic_config(save_location=cls.config_file) |
| 168 |
cls.launch_args = get_launch_command(config_file=cls.config_file) |
| 169 |
|
| 170 |
@classmethod |
| 171 |
def tearDownClass(cls): |
| 172 |
super().tearDownClass() |
| 173 |
shutil.rmtree(cls._tmpdir) |
| 174 |
|
| 175 |
def test_checkpointing_by_epoch(self): |
| 176 |
testargs = f""" |
| 177 |
examples/by_feature/checkpointing.py |
| 178 |
--checkpointing_steps epoch |
| 179 |
--output_dir {self.tmpdir} |
| 180 |
""".split() |
| 181 |
run_command(self.launch_args + testargs) |
| 182 |
assert (self.tmpdir / "epoch_0").exists() |
| 183 |
|
| 184 |
def test_checkpointing_by_steps(self): |
| 185 |
testargs = f""" |
| 186 |
examples/by_feature/checkpointing.py |
| 187 |
--checkpointing_steps 1 |
| 188 |
--output_dir {self.tmpdir} |
| 189 |
""".split() |
| 190 |
_ = run_command(self.launch_args + testargs) |
| 191 |
assert (self.tmpdir / "step_2").exists() |
| 192 |
|
| 193 |
def test_load_states_by_epoch(self): |
| 194 |
testargs = f""" |
| 195 |
examples/by_feature/checkpointing.py |
| 196 |
--resume_from_checkpoint {self.tmpdir / "epoch_0"} |
| 197 |
""".split() |
| 198 |
output = run_command(self.launch_args + testargs, return_stdout=True) |
| 199 |
assert "epoch 0:" not in output |
| 200 |
assert "epoch 1:" in output |
| 201 |
|
| 202 |
def test_load_states_by_steps(self): |
| 203 |
testargs = f""" |
| 204 |
examples/by_feature/checkpointing.py |
| 205 |
--resume_from_checkpoint {self.tmpdir / "step_2"} |
| 206 |
""".split() |
| 207 |
output = run_command(self.launch_args + testargs, return_stdout=True) |
| 208 |
if is_hpu_available(): |
| 209 |
num_processes = torch.hpu.device_count() |
| 210 |
elif torch.cuda.is_available(): |
| 211 |
num_processes = torch.cuda.device_count() |
| 212 |
elif is_xpu_available(): |
| 213 |
num_processes = torch.xpu.device_count() |
| 214 |
else: |
| 215 |
num_processes = 1 |
| 216 |
|
| 217 |
if num_processes > 1: |
| 218 |
assert "epoch 0:" not in output |
| 219 |
assert "epoch 1:" in output |
| 220 |
else: |
| 221 |
assert "epoch 0:" in output |
| 222 |
assert "epoch 1:" in output |
| 223 |
|
| 224 |
@slow |
| 225 |
def test_cross_validation(self): |
| 226 |
testargs = """ |
| 227 |
examples/by_feature/cross_validation.py |
| 228 |
--num_folds 2 |
| 229 |
""".split() |
| 230 |
with mock.patch.dict(os.environ, {"TESTING_MOCKED_DATALOADERS": "0"}): |
| 231 |
output = run_command(self.launch_args + testargs, return_stdout=True) |
| 232 |
results = re.findall("({.+})", output) |
| 233 |
results = [r for r in results if "accuracy" in r][-1] |
| 234 |
results = ast.literal_eval(results) |
| 235 |
assert results["accuracy"] >= 0.75 |
| 236 |
|
| 237 |
def test_multi_process_metrics(self): |
| 238 |
testargs = ["examples/by_feature/multi_process_metrics.py"] |
| 239 |
run_command(self.launch_args + testargs) |
| 240 |
|
| 241 |
@require_schedulefree |
| 242 |
def test_schedulefree(self): |
| 243 |
testargs = ["examples/by_feature/schedule_free.py"] |
| 244 |
run_command(self.launch_args + testargs) |
| 245 |
|
| 246 |
@require_trackers |
| 247 |
@mock.patch.dict( |
| 248 |
os.environ, |
| 249 |
{"WANDB_MODE": "offline", "DVCLIVE_TEST": "true", "SWANLAB_MODE": "disabled"}, |
| 250 |
) |
| 251 |
def test_tracking(self): |
| 252 |
with tempfile.TemporaryDirectory() as tmpdir: |
| 253 |
testargs = f""" |
| 254 |
examples/by_feature/tracking.py |
| 255 |
--with_tracking |
| 256 |
--project_dir {tmpdir} |
| 257 |
""".split() |
| 258 |
run_command(self.launch_args + testargs) |
| 259 |
|
| 260 |
def test_gradient_accumulation(self): |
| 261 |
testargs = ["examples/by_feature/gradient_accumulation.py"] |
| 262 |
run_command(self.launch_args + testargs) |
| 263 |
|
| 264 |
def test_gradient_accumulation_for_autoregressive_models(self): |
| 265 |
testargs = [ |
| 266 |
"examples/by_feature/gradient_accumulation_for_autoregressive_models.py", |
| 267 |
"--gradient_accumulation_steps", |
| 268 |
"2", |
| 269 |
] |
| 270 |
run_command(self.launch_args + testargs) |
| 271 |
|
| 272 |
def test_local_sgd(self): |
| 273 |
testargs = ["examples/by_feature/local_sgd.py"] |
| 274 |
run_command(self.launch_args + testargs) |
| 275 |
|
| 276 |
def test_early_stopping(self): |
| 277 |
testargs = ["examples/by_feature/early_stopping.py"] |
| 278 |
run_command(self.launch_args + testargs) |
| 279 |
|
| 280 |
def test_profiler(self): |
| 281 |
testargs = ["examples/by_feature/profiler.py"] |
| 282 |
run_command(self.launch_args + testargs) |
| 283 |
|
| 284 |
@require_fp16 |
| 285 |
@require_multi_device |
| 286 |
def test_ddp_comm_hook(self): |
| 287 |
testargs = ["examples/by_feature/ddp_comm_hook.py", "--ddp_comm_hook", "fp16"] |
| 288 |
run_command(self.launch_args + testargs) |
| 289 |
|
| 290 |
@require_fp16 |
| 291 |
@require_multi_device |
| 292 |
def test_distributed_inference_examples_stable_diffusion(self): |
| 293 |
testargs = ["examples/inference/distributed/stable_diffusion.py"] |
| 294 |
run_command(self.launch_args + testargs) |
| 295 |
|
| 296 |
@require_fp16 |
| 297 |
@require_multi_device |
| 298 |
def test_distributed_inference_examples_phi2(self): |
| 299 |
testargs = ["examples/inference/distributed/phi2.py"] |
| 300 |
run_command(self.launch_args + testargs) |
| 301 |
|
| 302 |
@require_pippy |
| 303 |
@require_multi_device |
| 304 |
@skip("Will soon deprecate pippy") |
| 305 |
def test_pippy_examples_bert(self): |
| 306 |
testargs = ["examples/inference/pippy/bert.py"] |
| 307 |
run_command(self.launch_args + testargs) |
| 308 |
|
| 309 |
@require_pippy |
| 310 |
@require_multi_device |
| 311 |
@skip("Will soon deprecate pippy") |
| 312 |
def test_pippy_examples_gpt2(self): |
| 313 |
testargs = ["examples/inference/pippy/gpt2.py"] |
| 314 |
run_command(self.launch_args + testargs) |