Debian Codegraph @

tests/test_accelerator.py

raw
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 import itertools
15 import json
16 import os
17 import pickle
18 import tempfile
19 import time
20 from unittest import skip
21 from unittest.mock import patch
22
23 import psutil
24 import torch
25 from parameterized import parameterized
26 from torch.utils.data import DataLoader, TensorDataset
27
28 from accelerate import DistributedType, infer_auto_device_map, init_empty_weights, load_checkpoint_and_dispatch
29 from accelerate.accelerator import Accelerator
30 from accelerate.data_loader import DataLoaderDispatcher, DataLoaderShard, skip_first_batches
31 from accelerate.state import GradientState, PartialState
32 from accelerate.test_utils import (
33 require_bnb,
34 require_cuda_or_xpu,
35 require_fp8,
36 require_fp16,
37 require_huggingface_suite,
38 require_multi_device,
39 require_non_cpu,
40 require_non_hpu,
41 require_transformer_engine,
42 slow,
43 torch_device,
44 )
45 from accelerate.test_utils.testing import (
46 AccelerateTestCase,
47 assert_exception,
48 require_cuda,
49 require_non_torch_xla,
50 require_torchdata_stateful_dataloader,
51 )
52 from accelerate.utils import FP8RecipeKwargs, is_torchdata_stateful_dataloader_available, patch_environment
53 from accelerate.utils.dataclasses import DataLoaderConfiguration
54 from accelerate.utils.modeling import get_state_dict_from_offload, load_checkpoint_in_model
55 from accelerate.utils.random import set_seed
56
57
58 if is_torchdata_stateful_dataloader_available():
59 from torchdata.stateful_dataloader import StatefulDataLoader
60
61
62 class ModelWithTiedWeights(torch.nn.Module):
63 def __init__(self):
64 super().__init__()
65 self.linear1 = torch.nn.Linear(2, 4)
66 self.linear2 = torch.nn.Linear(4, 2)
67 self.linear2.weight = self.linear1.weight
68 self.linear2.bias = self.linear1.bias
69
70 def forward(self, x):
71 return self.linear2(self.linear1(x))
72
73
74 def create_components(tied_weights=False):
75 model = ModelWithTiedWeights() if tied_weights else torch.nn.Linear(2, 4)
76 optimizer = torch.optim.AdamW(model.parameters(), lr=1.0)
77 scheduler = torch.optim.lr_scheduler.OneCycleLR(optimizer, max_lr=0.01, steps_per_epoch=2, epochs=1)
78 train_dl = DataLoader(TensorDataset(torch.tensor([1, 2, 3])))
79 valid_dl = DataLoader(TensorDataset(torch.tensor([4, 5, 6])))
80 return model, optimizer, scheduler, train_dl, valid_dl
81
82
83 class ModelForTest(torch.nn.Module):
84 def __init__(self):
85 super().__init__()
86 self.linear1 = torch.nn.Linear(3, 4)
87 self.batchnorm = torch.nn.BatchNorm1d(4)
88 self.linear2 = torch.nn.Linear(4, 5)
89
90 def forward(self, x):
91 return self.linear2(self.batchnorm(self.linear1(x)))
92
93
94 def create_dataloaders_for_test(batch_size=3, n_train_batches: int = 12, n_valid_batches: int = 2, num_workers=0):
95 "Generates a tuple of dummy DataLoaders to test with"
96
97 def get_dataset(n_batches):
98 x = torch.randn(batch_size * n_batches, 3)
99 y = torch.randn(batch_size * n_batches, 5)
100 return TensorDataset(x, y)
101
102 train_dataset = get_dataset(n_train_batches)
103 valid_dataset = get_dataset(n_valid_batches)
104 train_dataloader = DataLoader(train_dataset, batch_size=batch_size, num_workers=num_workers)
105 valid_dataloader = DataLoader(valid_dataset, batch_size=batch_size, num_workers=num_workers)
106 return (train_dataloader, valid_dataloader)
107
108
109 def get_signature(model):
110 return sum(param.abs().sum().item() for param in model.parameters())
111
112
113 def load_random_weights(model):
114 if isinstance(model, torch.nn.Linear):
115 state = torch.nn.Linear(*tuple(model.weight.T.shape)).state_dict()
116 elif isinstance(model, ModelWithTiedWeights):
117 state = ModelWithTiedWeights().state_dict()
118 model.load_state_dict(state)
119
120
121 def parameterized_custom_name_func(func, param_num, param):
122 # customize the test name generator function as we want both params to appear in the sub-test
123 # name, as by default it shows only the first param
124 param_based_name = "use_safetensors" if param.args[0] is True else "use_pytorch"
125 if len(param.args) > 1:
126 param_based_name += "_tied_weights" if param.args[1] is True else ""
127 if len(param.args) > 2:
128 param_based_name += f"_num_workers_{param.args[2]}"
129 if len(param.args) > 3:
130 param_based_name += "_dispatch_batches" if param.args[3] is True else "_no_dispatch_batches"
131 return f"{func.__name__}_{param_based_name}"
132
133
134 class AcceleratorTester(AccelerateTestCase):
135 def test_partial_state_after_reset(self):
136 # Verifies that custom getattr errors will be thrown
137 # if the state is reset, but only if trying to
138 # get expected attributes
139 state = PartialState()
140 assert state.num_processes > 0
141
142 with self.assertRaises(AttributeError) as cm:
143 state.someotherthing
144 assert "'PartialState' object has no attribute" in str(cm.exception)
145 assert "This happens if `PartialState._reset_state()`" not in str(cm.exception)
146
147 with self.assertRaises(AttributeError) as cm:
148 state._reset_state()
149 state.num_processes
150 assert "`PartialState` object has no attribute" in str(cm.exception)
151 assert "This happens if `PartialState._reset_state()`" in str(cm.exception)
152
153 state.someotherthing = "MyValue"
154 assert state.someotherthing == "MyValue"
155
156 def test_accelerator_state_after_reset(self):
157 # Verifies that custom getattr errors will be thrown
158 # if the state is reset, but only if trying to
159 # get expected attributes
160 accelerator = Accelerator()
161 assert accelerator.num_processes > 0
162
163 with self.assertRaises(AttributeError) as cm:
164 accelerator.state.someotherthing
165 assert "'AcceleratorState' object has no attribute" in str(cm.exception)
166 assert "This happens if `AcceleratorState._reset_state()`" not in str(cm.exception)
167
168 with self.assertRaises(AttributeError) as cm:
169 accelerator.state._reset_state()
170 accelerator.num_processes
171 assert "`AcceleratorState` object has no attribute" in str(cm.exception)
172 assert "This happens if `AcceleratorState._reset_state()`" in str(cm.exception)
173
174 accelerator.state.someotherthing = "MyValue"
175 assert accelerator.state.someotherthing == "MyValue"
176
177 @require_non_cpu
178 def test_accelerator_can_be_reinstantiated(self):
179 _ = Accelerator()
180 assert PartialState._shared_state["_cpu"] is False
181 assert PartialState._shared_state["device"].type in ["cuda", "mps", "npu", "xpu", "xla", "hpu"]
182 with self.assertRaises(ValueError):
183 _ = Accelerator(cpu=True)
184
185 @require_cuda
186 def test_setting_cpu_affinity(self):
187 with patch_environment(accelerate_cpu_affinity=1, accelerate_debug_mode=1):
188 with self.assertLogs("accelerate.utils.environment", level="INFO") as cm:
189 _ = Accelerator()
190 assert any("Assigning" in log for log in cm.output)
191 assert any("cpu cores to process" in log for log in cm.output)
192
193 def test_mutable_states(self):
194 accelerator = Accelerator()
195 state = GradientState()
196 assert state.num_steps == 1
197 accelerator.gradient_accumulation_steps = 4
198 assert state.num_steps == 4
199
200 assert state.sync_gradients is True
201 accelerator.sync_gradients = False
202 assert state.sync_gradients is False
203 GradientState._reset_state()
204
205 def test_prepared_objects_are_referenced(self):
206 accelerator = Accelerator()
207 model, optimizer, scheduler, train_dl, valid_dl = create_components()
208
209 (
210 prepared_model,
211 prepared_optimizer,
212 prepared_scheduler,
213 prepared_train_dl,
214 prepared_valid_dl,
215 ) = accelerator.prepare(model, optimizer, scheduler, train_dl, valid_dl)
216
217 assert prepared_model in accelerator._models
218 assert prepared_optimizer in accelerator._optimizers
219 assert prepared_scheduler in accelerator._schedulers
220 assert prepared_train_dl in accelerator._dataloaders
221 assert prepared_valid_dl in accelerator._dataloaders
222
223 @require_non_hpu # hpu does not support empty_cache
224 def test_free_memory_dereferences_prepared_components(self):
225 accelerator = Accelerator()
226 # Free up refs with empty_cache() and gc.collect()
227 accelerator.free_memory()
228 model, optimizer, scheduler, train_dl, valid_dl = create_components()
229 free_cpu_ram_before = psutil.virtual_memory().available // 1024 // 1024
230 model, optimizer, scheduler, train_dl, valid_dl = accelerator.prepare(
231 model, optimizer, scheduler, train_dl, valid_dl
232 )
233
234 # Short sleep here makes this test more reliable
235 time.sleep(1e-3)
236
237 model, optimizer, scheduler, train_dl, valid_dl = accelerator.free_memory(
238 model, optimizer, scheduler, train_dl, valid_dl
239 )
240
241 free_cpu_ram_after = psutil.virtual_memory().available // 1024 // 1024
242
243 assert len(accelerator._models) == 0
244 assert len(accelerator._optimizers) == 0
245 assert len(accelerator._schedulers) == 0
246 assert len(accelerator._dataloaders) == 0
247
248 # The less-than comes *specifically* from device CPU things/won't be present on CPU builds
249 # Allow a small tolerance for OS-level memory fluctuations between measurements
250 assert free_cpu_ram_after <= free_cpu_ram_before + 50
251
252 @require_non_torch_xla
253 def test_env_var_device(self):
254 """Tests that setting the torch device with ACCELERATE_TORCH_DEVICE overrides default device."""
255 PartialState._reset_state()
256
257 # Mock torch's set_device call to avoid an exception as the device doesn't exist
258 def noop(*args, **kwargs):
259 pass
260
261 with (
262 # Some backends such as MPS do not expose a module-level `set_device`.
263 # This test only exercises env var parsing, so a synthetic attribute is enough.
264 patch(f"torch.{torch_device}.set_device", noop, create=True),
265 patch_environment(ACCELERATE_TORCH_DEVICE=f"{torch_device}:64"),
266 ):
267 accelerator = Accelerator()
268 assert str(accelerator.state.device) == f"{torch_device}:64"
269
270 @parameterized.expand([(True, True), (True, False), (False, False)], name_func=parameterized_custom_name_func)
271 def test_save_load_model(self, use_safetensors, tied_weights):
272 accelerator = Accelerator()
273 model, optimizer, scheduler, train_dl, valid_dl = create_components(tied_weights)
274 accelerator.prepare(model, optimizer, scheduler, train_dl, valid_dl)
275
276 model_signature = get_signature(model)
277
278 with tempfile.TemporaryDirectory() as tmpdirname:
279 accelerator.save_state(tmpdirname, safe_serialization=use_safetensors)
280
281 # make sure random weights don't match
282 load_random_weights(model)
283 assert abs(model_signature - get_signature(model)) > 1e-3
284
285 # make sure loaded weights match
286 accelerator.load_state(tmpdirname)
287 assert abs(model_signature - get_signature(model)) < 1e-3
288
289 @parameterized.expand([True, False], name_func=parameterized_custom_name_func)
290 def test_save_model(self, use_safetensors):
291 accelerator = Accelerator()
292 model = torch.nn.Linear(10, 10)
293
294 model_signature = get_signature(model)
295 with tempfile.TemporaryDirectory() as tmpdirname:
296 accelerator.save_model(model, tmpdirname, safe_serialization=use_safetensors)
297 # make sure loaded weights match
298 load_checkpoint_in_model(model, tmpdirname)
299 assert abs(model_signature - get_signature(model)) < 1e-3
300
301 @parameterized.expand([True, False], name_func=parameterized_custom_name_func)
302 def test_save_sharded_model(self, use_safetensors):
303 accelerator = Accelerator()
304 inputs = torch.randn(3, 3)
305 model = ModelForTest()
306 expected = model(inputs)
307
308 with tempfile.TemporaryDirectory() as tmpdirname:
309 # By setting it to 100, we will split the model int 3 shards
310 accelerator.save_model(model, tmpdirname, safe_serialization=use_safetensors, max_shard_size=100)
311 # make sure loaded weights match
312 load_checkpoint_in_model(model, tmpdirname)
313 output = model(inputs)
314
315 assert torch.allclose(expected, output, atol=1e-5)
316
317 @parameterized.expand([True, False], name_func=parameterized_custom_name_func)
318 def test_save_model_offload(self, use_safetensors):
319 accelerator = Accelerator()
320
321 device_map = {"linear1": "cpu", "batchnorm": "disk", "linear2": "cpu"}
322
323 inputs = torch.randn(3, 3)
324 model = ModelForTest()
325 expected = model(inputs)
326 with tempfile.TemporaryDirectory() as tmp_dir:
327 accelerator.save_model(model, tmp_dir, safe_serialization=use_safetensors)
328 # load and save offloaded model
329 load_checkpoint_and_dispatch(model, tmp_dir, device_map=device_map, offload_folder=tmp_dir)
330 accelerator.save_model(model, tmp_dir, safe_serialization=use_safetensors)
331
332 # load weights that were saved from the offloaded model
333 load_checkpoint_and_dispatch(model, tmp_dir)
334 output = model(inputs)
335 assert torch.allclose(expected, output, atol=1e-5)
336
337 @parameterized.expand([True, False], name_func=parameterized_custom_name_func)
338 @require_non_cpu
339 def test_get_state_dict_from_offload(self, use_safetensors):
340 accelerator = Accelerator()
341
342 device_map = {"linear1": "cpu", "batchnorm": "disk", "linear2": "disk"}
343 model = ModelForTest()
344 offloaded_layer_weight = model.linear2.weight
345 with tempfile.TemporaryDirectory() as tmp_dir:
346 accelerator.save_model(model, tmp_dir, safe_serialization=use_safetensors)
347 # load model with offloaded layers
348 load_checkpoint_and_dispatch(model, tmp_dir, device_map=device_map, offload_folder=tmp_dir)
349 cpu_onloaded_layer = get_state_dict_from_offload(
350 model.linear2, "linear2.weight", {"linear2.weight": ""}, device_to_put_offload="cpu"
351 )
352 device_onloaded_layer = get_state_dict_from_offload(
353 model.linear2, "linear2.weight", {"linear2.weight": ""}, device_to_put_offload=0
354 )
355 cpu_onloaded_layer_weight = cpu_onloaded_layer["linear2.weight"]
356 device_onloaded_layer_weight = device_onloaded_layer["linear2.weight"]
357
358 assert torch.allclose(offloaded_layer_weight, cpu_onloaded_layer_weight)
359 assert torch.allclose(
360 offloaded_layer_weight, device_onloaded_layer_weight.to("cpu")
361 ) # must be on the same device for torch.allclose()
362 assert cpu_onloaded_layer_weight.device.type == "cpu"
363 assert device_onloaded_layer_weight.device.type == torch_device
364
365 @parameterized.expand([True, False], name_func=parameterized_custom_name_func)
366 def test_save_load_model_with_hooks(self, use_safetensors):
367 accelerator = Accelerator()
368 model, optimizer, scheduler, train_dl, valid_dl = create_components()
369 accelerator.prepare(model, optimizer, scheduler, train_dl, valid_dl)
370
371 model_signature = get_signature(model)
372
373 # saving hook
374 def save_config(models, weights, output_dir):
375 config = {"class_name": models[0].__class__.__name__}
376
377 with open(os.path.join(output_dir, "data.json"), "w") as f:
378 json.dump(config, f)
379
380 # loading hook
381 def load_config(models, input_dir):
382 with open(os.path.join(input_dir, "data.json")) as f:
383 config = json.load(f)
384
385 models[0].class_name = config["class_name"]
386
387 save_hook = accelerator.register_save_state_pre_hook(save_config)
388 load_hook = accelerator.register_load_state_pre_hook(load_config)
389
390 with tempfile.TemporaryDirectory() as tmpdirname:
391 accelerator.save_state(tmpdirname, safe_serialization=use_safetensors)
392
393 # make sure random weights don't match with hooks
394 load_random_weights(model)
395 assert abs(model_signature - get_signature(model)) > 1e-3
396
397 # random class name to verify correct one is loaded
398 model.class_name = "random"
399
400 # make sure loaded weights match with hooks
401 accelerator.load_state(tmpdirname)
402 assert abs(model_signature - get_signature(model)) < 1e-3
403
404 # mode.class_name is loaded from config
405 assert model.class_name == model.__class__.__name__
406
407 # remove hooks
408 save_hook.remove()
409 load_hook.remove()
410
411 with tempfile.TemporaryDirectory() as tmpdirname:
412 accelerator.save_state(tmpdirname, safe_serialization=use_safetensors)
413
414 # make sure random weights don't match with hooks removed
415 load_random_weights(model)
416 assert abs(model_signature - get_signature(model)) > 1e-3
417
418 # random class name to verify correct one is loaded
419 model.class_name = "random"
420
421 # make sure loaded weights match with hooks removed
422 accelerator.load_state(tmpdirname)
423 assert abs(model_signature - get_signature(model)) < 1e-3
424
425 # mode.class_name is NOT loaded from config
426 assert model.class_name != model.__class__.__name__
427
428 def test_accelerator_none(self):
429 """Just test that passing None to accelerator.prepare() works."""
430 accelerator = Accelerator()
431 model, optimizer, scheduler, train_dl, valid_dl = create_components()
432 dummy_obj = None
433
434 # This should work
435 model, optimizer, scheduler, train_dl, valid_dl, dummy_obj = accelerator.prepare(
436 model, optimizer, scheduler, train_dl, valid_dl, dummy_obj
437 )
438 assert dummy_obj is None
439
440 def test_is_accelerator_prepared(self):
441 """Checks that `_is_accelerator_prepared` is set properly"""
442 accelerator = Accelerator()
443 model, optimizer, scheduler, train_dl, valid_dl = create_components()
444 dummy_obj = [1, 2, 3]
445
446 # This should work
447 model, optimizer, scheduler, train_dl, valid_dl, dummy_obj = accelerator.prepare(
448 model, optimizer, scheduler, train_dl, valid_dl, dummy_obj
449 )
450 assert getattr(dummy_obj, "_is_accelerate_prepared", False) is False, (
451 "Dummy object should have `_is_accelerate_prepared` set to `True`"
452 )
453 assert getattr(model, "_is_accelerate_prepared", False) is True, (
454 "Model is missing `_is_accelerator_prepared` or is set to `False`"
455 )
456 assert getattr(optimizer, "_is_accelerate_prepared", False) is True, (
457 "Optimizer is missing `_is_accelerator_prepared` or is set to `False`"
458 )
459 assert getattr(scheduler, "_is_accelerate_prepared", False) is True, (
460 "Scheduler is missing `_is_accelerator_prepared` or is set to `False`"
461 )
462 assert getattr(train_dl, "_is_accelerate_prepared", False) is True, (
463 "Train Dataloader is missing `_is_accelerator_prepared` or is set to `False`"
464 )
465 assert getattr(valid_dl, "_is_accelerate_prepared", False) is True, (
466 "Valid Dataloader is missing `_is_accelerator_prepared` or is set to `False`"
467 )
468
469 def test_prepare_model_twice_does_not_double_wrap(self):
470 accelerator = Accelerator()
471 model = torch.nn.Linear(10, 2)
472 prepared_model = accelerator.prepare_model(model)
473 num_models_before = len(accelerator._models)
474 reprepared_model = accelerator.prepare_model(prepared_model)
475 assert len(accelerator._models) == num_models_before, (
476 "prepare_model should not add duplicate entries to _models"
477 )
478 assert reprepared_model is prepared_model, "prepare_model should return the same object when called twice"
479
480 @require_cuda_or_xpu
481 @slow
482 @require_bnb
483 def test_accelerator_bnb(self):
484 """Tests that the accelerator can be used with the BNB library."""
485 from transformers import AutoModelForCausalLM, BitsAndBytesConfig
486
487 model = AutoModelForCausalLM.from_pretrained(
488 "EleutherAI/gpt-neo-125m",
489 quantization_config=BitsAndBytesConfig(load_in_8bit=True),
490 device_map={"": 0},
491 )
492 accelerator = Accelerator()
493
494 # This should work
495 model = accelerator.prepare(model)
496
497 @require_cuda_or_xpu
498 @slow
499 @require_bnb
500 @skip("Passing locally but not on CI. Also no one will try to train an offloaded bnb model")
501 def test_accelerator_bnb_cpu_error(self):
502 """Tests that the accelerator can be used with the BNB library. This should fail as we are trying to load a model
503 that is loaded between cpu and gpu"""
504 from transformers import AutoModelForCausalLM
505
506 accelerator = Accelerator()
507
508 with init_empty_weights():
509 model = AutoModelForCausalLM.from_pretrained(
510 "EleutherAI/gpt-neo-125m",
511 )
512 model.tie_weights()
513 device_map = infer_auto_device_map(model)
514 device_map["lm_head"] = "cpu"
515
516 from transformers import BitsAndBytesConfig
517
518 model = AutoModelForCausalLM.from_pretrained(
519 "EleutherAI/gpt-neo-125m",
520 device_map=device_map,
521 quantization_config=BitsAndBytesConfig(load_in_8bit=True, llm_int8_enable_fp32_cpu_offload=True),
522 )
523
524 # This should not work and get value error
525 with self.assertRaises(ValueError):
526 model = accelerator.prepare(model)
527
528 @require_non_torch_xla
529 @require_non_hpu # bnb is not supported on HPU
530 @slow
531 @require_bnb
532 @require_multi_device
533 def test_accelerator_bnb_multi_device(self):
534 """Tests that the accelerator can be used with the BNB library."""
535 from transformers import AutoModelForCausalLM, BitsAndBytesConfig
536
537 if torch_device == "cuda":
538 PartialState._shared_state = {"distributed_type": DistributedType.MULTI_GPU}
539 elif torch_device == "npu":
540 PartialState._shared_state = {"distributed_type": DistributedType.MULTI_NPU}
541 elif torch_device == "xpu":
542 PartialState._shared_state = {"distributed_type": DistributedType.MULTI_XPU}
543 else:
544 raise ValueError(f"{torch_device} is not supported in test_accelerator_bnb_multi_device.")
545
546 with init_empty_weights():
547 model = AutoModelForCausalLM.from_pretrained(
548 "EleutherAI/gpt-neo-125m",
549 )
550 model.tie_weights()
551 device_map = infer_auto_device_map(model)
552 device_map["lm_head"] = 1
553
554 model = AutoModelForCausalLM.from_pretrained(
555 "EleutherAI/gpt-neo-125m",
556 quantization_config=BitsAndBytesConfig(load_in_8bit=True),
557 device_map=device_map,
558 )
559 accelerator = Accelerator()
560
561 # This should not work and get value error
562 with self.assertRaises(ValueError):
563 _ = accelerator.prepare(model)
564
565 @require_non_torch_xla
566 @require_non_hpu # bnb is not supported on HPU
567 @slow
568 @require_bnb
569 @require_multi_device
570 def test_accelerator_bnb_multi_device_no_distributed(self):
571 """Tests that the accelerator can be used with the BNB library."""
572 from transformers import AutoModelForCausalLM, BitsAndBytesConfig
573
574 with init_empty_weights():
575 model = AutoModelForCausalLM.from_pretrained(
576 "EleutherAI/gpt-neo-125m",
577 )
578 device_map = infer_auto_device_map(model)
579 device_map["lm_head"] = 1
580
581 model = AutoModelForCausalLM.from_pretrained(
582 "EleutherAI/gpt-neo-125m",
583 quantization_config=BitsAndBytesConfig(load_in_8bit=True),
584 device_map=device_map,
585 )
586 accelerator = Accelerator()
587
588 # This should work
589 _ = accelerator.prepare(model)
590
591 @require_non_cpu
592 def test_accelerator_cpu_flag_prepare(self):
593 model = torch.nn.Linear(10, 10)
594 sgd = torch.optim.SGD(model.parameters(), lr=0.01)
595 accelerator = Accelerator(cpu=True)
596 _ = accelerator.prepare(sgd)
597
598 @require_fp8
599 @require_transformer_engine
600 def test_can_unwrap_model_te(self):
601 model, optimizer, *_ = create_components()
602 fp8_recipe = FP8RecipeKwargs(backend="TE")
603 accelerator = Accelerator(mixed_precision="fp8", kwargs_handlers=[fp8_recipe])
604 inputs = torch.randn(10, 2).to(torch_device)
605 model, optimizer = accelerator.prepare(model, optimizer)
606 model(inputs) # sanity check that this works
607
608 model = accelerator.unwrap_model(model, keep_fp32_wrapper=False)
609 model(inputs) # check that this still works
610
611 # check that pickle roundtrip works
612 model_loaded = pickle.loads(pickle.dumps(model))
613 model_loaded(inputs)
614
615 @require_fp16
616 @require_non_cpu
617 def test_can_unwrap_model_fp16(self):
618 # test for a regression introduced in #872
619 # before the fix, after unwrapping with keep_fp32_wrapper=False, there would be the following error:
620 # Linear.forward() missing 1 required positional argument: 'input'
621 model = create_components()[0]
622 accelerator = Accelerator(mixed_precision="fp16")
623 inputs = torch.randn(10, 2).to(torch_device)
624 model = accelerator.prepare(model)
625 model(inputs) # sanity check that this works
626
627 model = accelerator.unwrap_model(model, keep_fp32_wrapper=False)
628 model(inputs) # check that this still works
629
630 # check that pickle roundtrip works
631 model_loaded = pickle.loads(pickle.dumps(model))
632 model_loaded(inputs)
633
634 def test_can_unwrap_model(self):
635 model = create_components()[0]
636 accelerator = Accelerator(mixed_precision="no", cpu=True)
637 inputs = torch.randn(10, 2)
638 model = accelerator.prepare(model)
639 model(inputs) # sanity check that this works
640
641 model = accelerator.unwrap_model(model, keep_fp32_wrapper=False)
642 model(inputs) # check that this still works
643
644 # check that pickle roundtrip works
645 model_loaded = pickle.loads(pickle.dumps(model))
646 model_loaded(inputs)
647
648 def test_can_unwrap_distributed_compiled_model_keep_torch_compile(self):
649 model = create_components()[0]
650 accelerator = Accelerator()
651
652 compiled_model = torch.compile(model)
653
654 distributed_model = torch.nn.DataParallel(model)
655 distributed_compiled_model = torch.compile(distributed_model)
656 unwrapped_model = accelerator.unwrap_model(distributed_compiled_model, keep_torch_compile=True)
657
658 assert compiled_model._orig_mod == unwrapped_model._orig_mod
659
660 def test_can_unwrap_distributed_compiled_model_remove_torch_compile(self):
661 model = create_components()[0]
662 accelerator = Accelerator()
663
664 compiled_model = torch.compile(model)
665
666 distributed_model = torch.nn.DataParallel(model)
667 distributed_compiled_model = torch.compile(distributed_model)
668 unwrapped_model = accelerator.unwrap_model(distributed_compiled_model, keep_torch_compile=False)
669
670 assert compiled_model._orig_mod == unwrapped_model
671
672 @parameterized.expand([True, False])
673 def test_can_pickle_dataloader(self, dispatch_batches):
674 """
675 Test that pickling a prepared dataloader works.
676 """
677 data = torch.arange(10).to(torch_device)
678 ds = torch.utils.data.TensorDataset(data)
679 dl = torch.utils.data.DataLoader(ds)
680 skip_dl = skip_first_batches(dl, 2)
681
682 # Currently, StatefulDataLoader doesn't seem to support pickling, so we aren't testing that functionality
683 # TODO: Add support for pickling StatefulDataLoader
684 dataloader_config = DataLoaderConfiguration(dispatch_batches=dispatch_batches, use_stateful_dataloader=False)
685 accelerator = Accelerator(dataloader_config=dataloader_config)
686
687 original_dl, _ = accelerator.prepare(dl, skip_dl)
688 if dispatch_batches:
689 assert isinstance(original_dl, DataLoaderDispatcher)
690 else:
691 assert isinstance(original_dl, DataLoaderShard)
692
693 prepared_model_dumps = pickle.dumps(accelerator)
694
695 model_loaded = pickle.loads(prepared_model_dumps)
696 assert len(model_loaded._dataloaders) == 2
697
698 # Assert equality of recovered and original dataloader
699 loaded_dl = model_loaded._dataloaders[0]
700 assert isinstance(loaded_dl, DataLoader)
701 if dispatch_batches:
702 assert isinstance(loaded_dl, DataLoaderDispatcher)
703 else:
704 assert isinstance(loaded_dl, DataLoaderShard)
705 assert len(loaded_dl) == len(original_dl)
706 assert [i for i in loaded_dl] == [i for i in original_dl]
707
708 # Test skip dataloader works as expected as well
709 loaded_skip_dl = model_loaded._dataloaders[1]
710 assert isinstance(loaded_skip_dl, DataLoader)
711 if dispatch_batches:
712 assert isinstance(loaded_dl, DataLoaderDispatcher)
713 else:
714 assert isinstance(loaded_dl, DataLoaderShard)
715 assert len(loaded_skip_dl) == len(original_dl) - 2
716 assert [i for i in loaded_skip_dl] == [i for i in original_dl][2:]
717
718 # Ideally would be a parameterized test which works with either stateful or non-stateful dataloaders, but dependencies are a bit awkward.
719 @require_torchdata_stateful_dataloader
720 def test_prepared_objects_are_referenced_with_stateful_dataloader(self):
721 """Test that setting `use_stateful_dataloader=True` in `DataLoaderConfiguration` prepares a `StatefulDataLoader` object instead of a `DataLoader` object."""
722 dataloader_config = DataLoaderConfiguration(use_stateful_dataloader=True)
723 accelerator = Accelerator(dataloader_config=dataloader_config)
724 model, optimizer, scheduler, train_dl, valid_dl = create_components()
725
726 (
727 prepared_model,
728 prepared_optimizer,
729 prepared_scheduler,
730 prepared_train_dl,
731 prepared_valid_dl,
732 ) = accelerator.prepare(model, optimizer, scheduler, train_dl, valid_dl)
733
734 assert prepared_model in accelerator._models
735 assert prepared_optimizer in accelerator._optimizers
736 assert prepared_scheduler in accelerator._schedulers
737 assert prepared_train_dl in accelerator._dataloaders
738 assert prepared_valid_dl in accelerator._dataloaders
739 assert isinstance(prepared_train_dl, StatefulDataLoader)
740 assert isinstance(prepared_valid_dl, StatefulDataLoader)
741
742 @parameterized.expand(
743 itertools.product([True, False], [True, False], [0, 2], [True, False]),
744 name_func=parameterized_custom_name_func,
745 )
746 @require_torchdata_stateful_dataloader
747 def test_save_model_with_stateful_dataloader(self, use_safetensors, tied_weights, num_workers, dispatch_batches):
748 """
749 Test that saving and loading a model with a stateful dataloader returns the same model,
750 and that the dataloader's iterator is restored properly."""
751 set_seed(42)
752 n_train_batches = 64 # Use enough batches to ensure we can get partial iterations on large compute
753 dataloader_config = DataLoaderConfiguration(dispatch_batches=dispatch_batches, use_stateful_dataloader=True)
754 accelerator = Accelerator(dataloader_config=dataloader_config)
755
756 model, optimizer, scheduler, train_dl, valid_dl = create_components(tied_weights)
757 train_dl, valid_dl = create_dataloaders_for_test(n_train_batches=n_train_batches, num_workers=num_workers)
758 model = ModelForTest()
759
760 (
761 prepared_model,
762 prepared_optimizer,
763 prepared_scheduler,
764 prepared_train_dl,
765 prepared_valid_dl,
766 ) = accelerator.prepare(model, optimizer, scheduler, train_dl, valid_dl)
767
768 assert isinstance(prepared_train_dl, StatefulDataLoader)
769 assert isinstance(prepared_valid_dl, StatefulDataLoader)
770
771 # Perform 3 training iterations to ensure the dataloader's iterator is advanced
772 num_batches_to_skip = 3
773 model.train()
774 untrained_batches = []
775 with tempfile.TemporaryDirectory() as tmpdirname:
776 for step, batch in enumerate(prepared_train_dl):
777 x, y = batch
778 outputs = prepared_model(x)
779 loss = torch.nn.functional.mse_loss(outputs, y)
780 accelerator.backward(loss)
781 prepared_optimizer.step()
782 prepared_scheduler.step()
783 prepared_optimizer.zero_grad()
784 if step == num_batches_to_skip - 1:
785 # Save the state once we've gone through a few batches
786 accelerator.save_state(f"{tmpdirname}/state", safe_serialization=use_safetensors)
787 if step >= num_batches_to_skip:
788 untrained_batches.append(batch)
789
790 not_skipped_batches = accelerator.gather(untrained_batches)
791 # We then unwrap the trained model
792 unwrapped_model = accelerator.unwrap_model(prepared_model)
793
794 original_linear1 = unwrapped_model.linear1.weight.clone()
795 original_batchnorm = unwrapped_model.batchnorm.weight.clone()
796 original_linear2 = unwrapped_model.linear2.weight.clone()
797
798 # Resume the state
799 accelerator.load_state(f"{tmpdirname}/state")
800
801 # Train this to the end of the DataLoader
802 batches_seen_with_loaded_dl = 0
803 for batch in prepared_train_dl:
804 x, y = batch
805 outputs = prepared_model(x)
806 loss = torch.nn.functional.mse_loss(outputs, y)
807 accelerator.backward(loss)
808 prepared_optimizer.step()
809 prepared_scheduler.step()
810 prepared_optimizer.zero_grad()
811 batches_seen_with_loaded_dl += 1
812
813 unwrapped_model_2 = accelerator.unwrap_model(prepared_model)
814
815 new_linear1 = unwrapped_model_2.linear1.weight
816 new_batchnorm = unwrapped_model_2.batchnorm.weight
817 new_linear2 = unwrapped_model_2.linear2.weight
818
819 # Assert equalities
820 assert batches_seen_with_loaded_dl == len(not_skipped_batches)
821 assert torch.allclose(original_linear1, new_linear1)
822 assert torch.allclose(original_batchnorm, new_batchnorm)
823 assert torch.allclose(original_linear2, new_linear2)
824
825 @require_non_cpu
826 @require_huggingface_suite
827 def test_nested_hook(self):
828 from transformers import PretrainedConfig, PreTrainedModel
829
830 class MyLinear(torch.nn.Module):
831 def __init__(self, device=None, dtype=None):
832 factory_kwargs = {"device": device, "dtype": dtype}
833 super().__init__()
834 self.centroid = torch.nn.Embedding(1, 2)
835 self.indices = torch.nn.Parameter(torch.empty((1, 2, 2), **factory_kwargs))
836
837 def forward(self, x):
838 orig_shape = x.shape
839 x = torch.abs(x + self.indices).long()
840 x = x % 2
841 x = x.sum(-1)
842 x = (self.centroid.weight + x).reshape(orig_shape)
843 return x
844
845 class MySubModel(torch.nn.Module):
846 def __init__(self):
847 super().__init__()
848 self.layer = MyLinear()
849
850 def forward(self, x):
851 return self.layer(x)
852
853 class MyModel(PreTrainedModel):
854 def __init__(self, config):
855 super().__init__(config)
856 self.layer = torch.nn.ModuleList([MySubModel() for i in range(4)])
857
858 def forward(self, x):
859 for layer in self.layer:
860 x = layer(x)
861 return x
862
863 with tempfile.TemporaryDirectory() as tmpdirname:
864 check_point = tmpdirname
865 offload_folder = check_point + "/offload"
866 os.makedirs(offload_folder, exist_ok=True)
867 config = PretrainedConfig()
868 m = MyModel(config)
869 m.save_pretrained(check_point)
870
871 with init_empty_weights():
872 my_model = MyModel(config)
873 my_model = load_checkpoint_and_dispatch(
874 my_model,
875 checkpoint=check_point,
876 max_memory={"cpu": 60, 0: 60},
877 device_map="auto",
878 no_split_module_classes=["MySubModel"],
879 offload_folder=offload_folder,
880 preload_module_classes=["MyLinear"],
881 )
882 # before fix, this would raise an error
883 # weight is on the meta device, we need a `value` to put in on 0
884 x = torch.randn(1, 2)
885 my_model(x)
886
887 @require_non_torch_xla
888 def test_prepare_model_8bit_cpu_offload_raises_valueerror_not_typeerror(self):
889 class ModelForTest(torch.nn.Module):
890 def __init__(self):
891 super().__init__()
892 self.l = torch.nn.Linear(2, 2)
893
894 def forward(self, x):
895 return self.l(x)
896
897 accelerator = Accelerator()
898 model = ModelForTest()
899
900 # Trigger the 8-bit/4-bit + hf_device_map code path.
901 model.is_loaded_in_8bit = True
902 model.hf_device_map = {"": "cpu"}
903
904 with (
905 patch("accelerate.accelerator.is_bitsandbytes_multi_backend_available", return_value=False),
906 patch("accelerate.accelerator.is_xpu_available", return_value=False),
907 ):
908 with assert_exception(ValueError, "CPU or disk offload"):
909 accelerator.prepare_model(model)