Debian Codegraph @

tests/test_big_modeling.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 copy
15 import gc
16 import itertools
17 import logging
18 import os
19 import unittest
20 from collections import OrderedDict
21 from tempfile import TemporaryDirectory
22
23 import torch
24 import torch.nn as nn
25 from transformers import AutoModelForCausalLM, AutoTokenizer
26
27 from accelerate.big_modeling import (
28 cpu_offload,
29 cpu_offload_with_hook,
30 disk_offload,
31 dispatch_model,
32 init_empty_weights,
33 init_on_device,
34 load_checkpoint_and_dispatch,
35 )
36 from accelerate.hooks import remove_hook_from_submodules
37 from accelerate.test_utils import (
38 require_bnb,
39 require_cuda_or_xpu,
40 require_multi_device,
41 require_multi_gpu_or_xpu,
42 require_non_cpu,
43 require_non_hpu,
44 require_non_torch_xla,
45 slow,
46 torch_device,
47 )
48 from accelerate.utils import is_hpu_available, is_xpu_available, offload_state_dict
49 from accelerate.utils.memory import clear_device_cache
50 from accelerate.utils.versions import is_torch_version
51
52
53 logger = logging.getLogger(__name__)
54 torch_device_type = torch_device
55 torch_device = f"{torch_device}:0" if torch_device != "cpu" else "cpu"
56
57 if is_hpu_available() or is_xpu_available():
58 ATOL = 1e-4
59 RTOL = 1e-4
60 else:
61 ATOL = 1e-5
62 RTOL = 1e-5
63
64
65 class ModelForTest(nn.Module):
66 def __init__(self):
67 super().__init__()
68 self.linear1 = nn.Linear(3, 4)
69 self.batchnorm = nn.BatchNorm1d(4)
70 self.linear2 = nn.Linear(4, 5)
71
72 def forward(self, x):
73 return self.linear2(self.batchnorm(self.linear1(x)))
74
75
76 class LinearWithNonPersistentBuffers(nn.Module):
77 def __init__(self, in_features: int, out_features: int, bias: bool = True, device=None, dtype=None) -> None:
78 factory_kwargs = {"device": device, "dtype": dtype}
79 super().__init__()
80 self.in_features = in_features
81 self.out_features = out_features
82 self.register_buffer("weight", torch.ones((out_features, in_features), **factory_kwargs))
83 if bias:
84 self.register_buffer("bias", torch.ones(out_features, **factory_kwargs), persistent=False)
85 else:
86 self.register_buffer("bias", None)
87
88 def forward(self, input: torch.Tensor) -> torch.Tensor:
89 return torch.nn.functional.linear(input, self.weight, self.bias)
90
91
92 class ModelForTestNonPersistentBuffers(nn.Module):
93 def __init__(self):
94 super().__init__()
95 self.linear1 = LinearWithNonPersistentBuffers(3, 4)
96 self.batchnorm = nn.BatchNorm1d(4)
97 self.linear2 = LinearWithNonPersistentBuffers(4, 5)
98
99 def forward(self, x):
100 return self.linear2(self.batchnorm(self.linear1(x)))
101
102
103 class ModelForTestCopy(nn.Module):
104 def __init__(self, id: int):
105 super().__init__()
106 self.id = id
107 self.linear1 = nn.Linear(3, 4)
108 self.batchnorm = nn.BatchNorm1d(4)
109 self.linear2 = nn.Linear(4, 5)
110
111 def forward(self, x):
112 return self.linear2(self.batchnorm(self.linear1(x))), self.id
113
114
115 class ModelForTestTiedWeights(nn.Module):
116 def __init__(self):
117 super().__init__()
118 self.linear1 = nn.Linear(4, 4)
119 self.batchnorm = nn.BatchNorm1d(4)
120 self.linear2 = nn.Linear(4, 4)
121
122 def forward(self, x):
123 return self.linear2(self.batchnorm(self.linear1(x)))
124
125
126 class BiggerModelForTest(nn.Module):
127 def __init__(self):
128 super().__init__()
129 self.linear1 = nn.Linear(3, 4)
130 self.linear2 = nn.Linear(4, 5)
131 self.batchnorm = nn.BatchNorm1d(5)
132 self.linear3 = nn.Linear(5, 6)
133 self.linear4 = nn.Linear(6, 5)
134
135 def forward(self, x):
136 return self.linear4(self.linear3(self.batchnorm(self.linear2(self.linear1(x)))))
137
138
139 # To test preload_module_classes
140 class ModuleWithUnusedSubModules(nn.Module):
141 def __init__(self, input_dim, output_dim):
142 super().__init__()
143 self.linear = nn.Linear(input_dim, output_dim)
144
145 def forward(self, x):
146 return x @ self.linear.weight.t() + self.linear.bias
147
148
149 class ModelWithUnusedSubModulesForTest(nn.Module):
150 def __init__(self):
151 super().__init__()
152 self.linear1 = ModuleWithUnusedSubModules(3, 4)
153 self.linear2 = ModuleWithUnusedSubModules(4, 5)
154 self.batchnorm = nn.BatchNorm1d(5)
155 self.linear3 = ModuleWithUnusedSubModules(5, 6)
156 self.linear4 = ModuleWithUnusedSubModules(6, 5)
157
158 def forward(self, x):
159 return self.linear4(self.linear3(self.batchnorm(self.linear2(self.linear1(x)))))
160
161
162 class BigModelingTester(unittest.TestCase):
163 def test_init_empty_weights(self):
164 # base use
165 with init_empty_weights():
166 module = nn.Linear(4, 5)
167 assert module.weight.device == torch.device("meta")
168
169 # base use with buffers, they are not touched
170 with init_empty_weights():
171 module = nn.BatchNorm1d(4)
172 assert module.weight.device == torch.device("meta")
173 assert module.running_mean.device == torch.device("cpu")
174
175 # Use with include_buffers=True
176 register_parameter_func = nn.Module.register_parameter
177 register_buffer_func = nn.Module.register_buffer
178 with init_empty_weights(include_buffers=True):
179 module = nn.BatchNorm1d(4)
180 # nn.Module.register_parameter/buffer shouldn't be changed with torch >= 2.0
181 assert register_parameter_func == nn.Module.register_parameter
182 assert register_buffer_func == nn.Module.register_buffer
183 assert module.weight.device == torch.device("meta")
184 assert module.running_mean.device == torch.device("meta")
185
186 # Double check we didn't break PyTorch
187 module = nn.BatchNorm1d(4)
188 assert module.weight.device == torch.device("cpu")
189 assert module.running_mean.device == torch.device("cpu")
190
191 def test_init_empty_weights_very_large_model(self):
192 # This is a 100 billion parameters model.
193 with init_empty_weights():
194 _ = nn.Sequential(*[nn.Linear(10000, 10000) for _ in range(1000)])
195
196 @require_non_cpu
197 def test_init_on_device(self):
198 device = torch.device(torch_device)
199 with init_on_device(device):
200 model = nn.Linear(10, 10)
201 assert model.weight.device == device
202 assert model.weight.device == device
203
204 def test_cpu_offload(self):
205 model = ModelForTest()
206 x = torch.randn(2, 3)
207 expected = model(x)
208
209 device = torch.device(torch_device)
210
211 cpu_offload(model, execution_device=device)
212 output = model(x)
213 torch.testing.assert_close(expected, output.cpu(), atol=ATOL, rtol=RTOL)
214
215 # Clean up for next test.
216 remove_hook_from_submodules(model)
217
218 cpu_offload(model, execution_device=device, offload_buffers=True)
219 output = model(x)
220 torch.testing.assert_close(expected, output.cpu(), atol=ATOL, rtol=RTOL)
221
222 def test_cpu_offload_with_unused_submodules(self):
223 model = ModelWithUnusedSubModulesForTest()
224 x = torch.randn(2, 3)
225 expected = model(x)
226
227 device = torch.device(torch_device)
228
229 cpu_offload(model, execution_device=device, preload_module_classes=["ModuleWithUnusedSubModules"])
230 output = model(x)
231 torch.testing.assert_close(expected, output.cpu(), atol=ATOL, rtol=RTOL)
232
233 # Clean up for next test.
234 remove_hook_from_submodules(model)
235
236 cpu_offload(
237 model,
238 execution_device=device,
239 offload_buffers=True,
240 preload_module_classes=["ModuleWithUnusedSubModules"],
241 )
242 output = model(x)
243 torch.testing.assert_close(expected, output.cpu(), atol=ATOL, rtol=RTOL)
244
245 @slow
246 @require_non_cpu
247 def test_cpu_offload_gpt2(self):
248 tokenizer = AutoTokenizer.from_pretrained("gpt2")
249 inputs = tokenizer("Hello world! My name is", return_tensors="pt").to(torch_device)
250
251 gpt2 = AutoModelForCausalLM.from_pretrained("gpt2")
252 cpu_offload(gpt2, execution_device=0)
253 outputs = gpt2.generate(inputs["input_ids"], max_new_tokens=10)
254 assert tokenizer.decode(outputs[0].tolist()) == "Hello world! My name is Kiyoshi, and I'm a student at"
255
256 def test_disk_offload(self):
257 model = ModelForTest()
258 x = torch.randn(2, 3)
259 expected = model(x)
260
261 device = torch.device(torch_device)
262
263 with TemporaryDirectory() as tmp_dir:
264 disk_offload(model, tmp_dir, execution_device=device)
265 output = model(x)
266 torch.testing.assert_close(expected, output.cpu(), atol=ATOL, rtol=RTOL)
267
268 # Clean up for next test.
269 remove_hook_from_submodules(model)
270
271 with TemporaryDirectory() as tmp_dir:
272 disk_offload(model, tmp_dir, execution_device=device, offload_buffers=True)
273 output = model(x)
274 torch.testing.assert_close(expected, output.cpu(), atol=ATOL, rtol=RTOL)
275
276 def test_disk_offload_with_unused_submodules(self):
277 model = ModelWithUnusedSubModulesForTest()
278 x = torch.randn(2, 3)
279 expected = model(x)
280
281 device = torch.device(torch_device)
282
283 with TemporaryDirectory() as tmp_dir:
284 disk_offload(
285 model, tmp_dir, execution_device=device, preload_module_classes=["ModuleWithUnusedSubModules"]
286 )
287 output = model(x)
288 torch.testing.assert_close(expected, output.cpu(), atol=ATOL, rtol=RTOL)
289
290 # Clean up for next test.
291 remove_hook_from_submodules(model)
292
293 with TemporaryDirectory() as tmp_dir:
294 disk_offload(
295 model,
296 tmp_dir,
297 execution_device=device,
298 offload_buffers=True,
299 preload_module_classes=["ModuleWithUnusedSubModules"],
300 )
301 output = model(x)
302 torch.testing.assert_close(expected, output.cpu(), atol=ATOL, rtol=RTOL)
303
304 @slow
305 @require_non_cpu
306 def test_disk_offload_gpt2(self):
307 tokenizer = AutoTokenizer.from_pretrained("gpt2")
308 inputs = tokenizer("Hello world! My name is", return_tensors="pt").to(torch_device)
309
310 gpt2 = AutoModelForCausalLM.from_pretrained("gpt2")
311 with TemporaryDirectory() as tmp_dir:
312 disk_offload(gpt2, tmp_dir, execution_device=0)
313 outputs = gpt2.generate(inputs["input_ids"], max_new_tokens=10)
314 assert tokenizer.decode(outputs[0].tolist()) == "Hello world! My name is Kiyoshi, and I'm a student at"
315
316 @require_non_cpu
317 def test_dispatch_model_and_remove_hook(self):
318 model = ModelForTest()
319 device_map = {"linear1": "cpu", "batchnorm": "cpu", "linear2": 0}
320 x = torch.randn(2, 3)
321 expected = model(x)
322
323 with TemporaryDirectory() as tmp_dir:
324 dispatch_model(model, device_map, offload_dir=tmp_dir)
325 output = model(x)
326 remove_hook_from_submodules(model)
327 # need to check if we get any warning
328 with self.assertLogs(level="WARNING") as cm:
329 # We want to assert there are no warnings, but the 'assertLogs' method does not support that.
330 # Therefore, we are adding a dummy warning, and then we will assert it is the only warning.
331 model.to(torch_device)
332 logger.warning("Dummy warning")
333 self.assertEqual(len(cm.records), 1)
334 self.assertIn(
335 "Dummy warning",
336 cm.records[0].message,
337 )
338 output_bis = model(x.to(torch_device))
339 torch.testing.assert_close(expected, output.cpu(), atol=ATOL, rtol=RTOL)
340 torch.testing.assert_close(expected, output_bis.cpu(), atol=ATOL, rtol=RTOL)
341
342 @require_non_cpu
343 def test_dispatch_model(self):
344 model = ModelForTest()
345 device_map = {"linear1": "disk", "batchnorm": "cpu", "linear2": 0}
346
347 x = torch.randn(2, 3)
348 expected = model(x)
349
350 with TemporaryDirectory() as tmp_dir:
351 dispatch_model(model, device_map, offload_dir=tmp_dir)
352 output = model(x)
353 torch.testing.assert_close(expected, output.cpu(), atol=ATOL, rtol=RTOL)
354
355 @require_non_cpu
356 def test_dispatch_model_with_non_persistent_buffers(self):
357 model = ModelForTestNonPersistentBuffers()
358 device_map = {"linear1": 0, "batchnorm": "cpu", "linear2": "disk"}
359 x = torch.randn(2, 3)
360 expected = model(x)
361
362 with TemporaryDirectory() as tmp_dir:
363 dispatch_model(model, device_map, offload_dir=tmp_dir, offload_buffers=True)
364 output = model(x)
365 torch.testing.assert_close(expected, output.cpu(), atol=ATOL, rtol=RTOL)
366
367 @require_non_cpu
368 def test_dispatch_model_tied_weights(self):
369 model = ModelForTestTiedWeights()
370 model.linear1.weight = model.linear2.weight
371 device_map = {"linear1": 0, "batchnorm": 0, "linear2": 0}
372
373 dispatch_model(model, device_map)
374 assert model.linear2.weight is model.linear1.weight
375
376 @require_multi_gpu_or_xpu
377 def test_dispatch_model_tied_weights_memory(self):
378 # Test that we do not duplicate tied weights at any point during dispatch_model call.
379
380 torch_accelerator_module = getattr(torch, torch_device_type)
381
382 clear_device_cache() # Needed in case we run several tests in a row.
383
384 model = nn.Sequential(
385 OrderedDict(
386 [
387 ("linear0", nn.Linear(5000, 5000, bias=False)),
388 ("linear1", nn.Linear(5000, 5000, bias=False)),
389 ("linear2", nn.Linear(5000, 5000, bias=False)),
390 ("linear3", nn.Linear(5000, 5000, bias=False)),
391 ("linear4", nn.Linear(5000, 5000, bias=False)),
392 ]
393 )
394 )
395 model.linear2.weight = model.linear0.weight
396 model.linear3.weight = model.linear0.weight
397 model.linear4.weight = model.linear0.weight
398
399 x = torch.randn(5, 5000)
400 with torch.no_grad():
401 expected = model(x)
402
403 # We should need only 5000 * 5000 * 32 // 8 * 1e-6 = 100 MB on the device 0 for the four linear weights.
404 device_0 = f"{torch_device_type}:0" if torch_device != "cpu" else "cpu"
405 device_1 = f"{torch_device_type}:1" if torch_device != "cpu" else "cpu"
406 device_map = {
407 "linear0": device_0,
408 "linear1": device_1,
409 "linear2": device_0,
410 "linear3": device_0,
411 "linear4": device_0,
412 }
413
414 # Just to initialize device context.
415 a = torch.rand(5).to(device_0) # noqa: F841
416
417 free_memory_bytes = torch_accelerator_module.mem_get_info(device_0)[0]
418 required_memory_bytes = 5000 * 5000 * (32 // 8)
419
420 # Leaving 50 MB of free memory for possible buffers, etc.
421 n_vals = (free_memory_bytes - required_memory_bytes - int(50e6)) // (32 // 8)
422 foo = torch.rand(n_vals, device=device_0) # noqa: F841
423
424 # If this does OOM: there is an issue in somewhere in dispatch_model, memory of tied weights is duplicated.
425 oom_error = (
426 torch.OutOfMemoryError if is_torch_version(">=", "2.5.0") else torch_accelerator_module.OutOfMemoryError
427 )
428 try:
429 dispatch_model(model, device_map)
430 except oom_error as e:
431 raise oom_error(
432 f"OOM error in dispatch_model. This is a bug and should not happen, see test_dispatch_model_tied_weights_memory. {e}"
433 )
434 except Exception as e:
435 raise e
436
437 with torch.no_grad():
438 output = model(x)
439 torch.testing.assert_close(expected, output.cpu(), atol=ATOL, rtol=RTOL)
440
441 @require_cuda_or_xpu
442 def test_dispatch_model_tied_weights_memory_with_nested_offload_cpu(self):
443 # Test that we do not duplicate tied weights at any point during dispatch_model call.
444
445 torch_accelerator_module = getattr(torch, torch_device_type)
446 clear_device_cache() # Needed in case we run several tests in a row.
447
448 class SubModule(torch.nn.Module):
449 def __init__(self, ref_to_parameter):
450 super().__init__()
451 self.parameter = ref_to_parameter
452
453 def forward(self, x):
454 return x + torch.max(self.parameter)
455
456 class LinearModuleAndSubModule(torch.nn.Linear):
457 def __init__(self, in_features, out_features):
458 super().__init__(in_features, out_features, bias=False)
459 self.weight_submodule = SubModule(self.weight)
460 self.weight_submodule2 = SubModule(self.weight)
461 self.weight_submodule3 = SubModule(self.weight)
462 self.weight_submodule4 = SubModule(self.weight)
463
464 def forward(self, x):
465 a = torch.nn.functional.linear(self.weight_submodule(x), self.weight)
466 b = torch.nn.functional.linear(self.weight_submodule2(x), self.weight)
467 c = torch.nn.functional.linear(self.weight_submodule3(x), self.weight)
468 d = torch.nn.functional.linear(self.weight_submodule4(x), self.weight)
469 return a + b + c + d
470
471 class ModelWithSubmodules(torch.nn.Module):
472 def __init__(self):
473 super().__init__()
474 self.compute = LinearModuleAndSubModule(5000, 5000)
475 self.compute1 = LinearModuleAndSubModule(5000, 5000)
476
477 def forward(self, x):
478 a = self.compute(x)
479 b = self.compute1(x)
480 return a + b
481
482 # We should need only 2 * 5000 * 5000 * 32 // 8 * 1e-6 = 200 MB on the device 0 for the whole model forward, and not 600 MB.
483 device_map = {"compute": torch_device, "compute1": "cpu"}
484
485 model = ModelWithSubmodules()
486
487 x = torch.randn(1, 5000)
488 with torch.no_grad():
489 expected = model(x)
490
491 # Just to initialize accelerator context.
492 a = torch.rand(5).to(torch_device) # noqa: F841
493
494 free_memory_bytes = torch_accelerator_module.mem_get_info(torch_device)[0]
495 required_memory_bytes = 2 * 5000 * 5000 * (32 // 8) # 200 MB
496
497 # Leaving 150 MB of free memory for possible buffers, etc.
498 n_vals = (free_memory_bytes - required_memory_bytes - int(150e6)) // (32 // 8)
499 foo = torch.rand(n_vals, device=torch_device) # noqa: F841
500
501 free_memory_bytes_before_dispatch = torch_accelerator_module.mem_get_info(torch_device)[0]
502 dispatch_model(model, device_map)
503 free_memory_bytes_after_dispatch = torch_accelerator_module.mem_get_info(torch_device)[0]
504
505 assert (free_memory_bytes_after_dispatch - free_memory_bytes_before_dispatch) * 1e-6 < 130
506
507 original_pointer = model.compute1._hf_hook.weights_map["weight"].data_ptr()
508
509 oom_error = (
510 torch.OutOfMemoryError if is_torch_version(">=", "2.5.0") else torch_accelerator_module.OutOfMemoryError
511 )
512 with torch.no_grad():
513 try:
514 output = model(x)
515 except oom_error as e:
516 raise oom_error(
517 f"OOM error in dispatch_model. This is a bug and should not happen, see test_dispatch_model_tied_weights_memory_with_nested_offload_cpu. {e}"
518 )
519 except Exception as e:
520 raise e
521
522 torch.testing.assert_close(expected, output.cpu(), atol=ATOL, rtol=RTOL)
523
524 clear_device_cache()
525
526 free_memory_bytes_after_infer = torch_accelerator_module.mem_get_info(torch_device)[0]
527
528 # Check that we have no more references on GPU for the offloaded tied weight.
529 assert len(model.compute1.weight_submodule._hf_hook.tied_params_map[original_pointer]) == 0
530 assert len(model.compute1._hf_hook.tied_params_map[original_pointer]) == 0
531 assert (free_memory_bytes_after_infer - free_memory_bytes_after_dispatch) * 1e-6 < 130
532
533 # Test is flacky otherwise.
534 del model
535 gc.collect()
536
537 # This test fails because sometimes data_ptr() of compute2.weight is the same as compute1.weight.
538 # I checked that the values are not the same but it gives the same address. This does not happen on my local machine.
539 @require_cuda_or_xpu
540 @unittest.skip(
541 "Flaky test, we should have enough coverage with test_dispatch_model_tied_weights_memory_with_nested_offload_cpu test"
542 )
543 def test_dispatch_model_tied_weights_memory_with_nested_offload_disk(self):
544 # Test that we do not duplicate tied weights at any point during dispatch_model call.
545
546 torch_accelerator_module = getattr(torch, torch_device_type)
547
548 clear_device_cache() # Needed in case we run several tests in a row.
549
550 class SubModule(torch.nn.Module):
551 def __init__(self, ref_to_parameter):
552 super().__init__()
553 self.parameter = ref_to_parameter
554
555 def forward(self, x):
556 return x + torch.max(self.parameter)
557
558 class LinearModuleAndSubModule(torch.nn.Linear):
559 def __init__(self, in_features, out_features):
560 super().__init__(in_features, out_features, bias=False)
561 self.weight_submodule = SubModule(self.weight)
562 self.weight_submodule2 = SubModule(self.weight)
563 self.weight_submodule3 = SubModule(self.weight)
564 self.weight_submodule4 = SubModule(self.weight)
565
566 def forward(self, x):
567 a = torch.nn.functional.linear(self.weight_submodule(x), self.weight)
568 b = torch.nn.functional.linear(self.weight_submodule2(x), self.weight)
569 c = torch.nn.functional.linear(self.weight_submodule3(x), self.weight)
570 d = torch.nn.functional.linear(self.weight_submodule4(x), self.weight)
571 return a + b + c + d
572
573 class ModelWithSubmodules(torch.nn.Module):
574 def __init__(self):
575 super().__init__()
576 self.compute = LinearModuleAndSubModule(5000, 5000)
577 self.compute1 = LinearModuleAndSubModule(5000, 5000)
578
579 def forward(self, x):
580 a = self.compute(x)
581 b = self.compute1(x)
582 return a + b
583
584 # We should need only 2 * 5000 * 5000 * 32 // 8 * 1e-6 = 200 MB on the device 0 for the whole model forward, and not 600 MB.
585 device_map = {"compute": 0, "compute1": "disk"}
586
587 model = ModelWithSubmodules()
588
589 x = torch.randn(1, 5000)
590 with torch.no_grad():
591 expected = model(x)
592
593 # Just to initialize CUDA context.
594 device_0 = f"{torch_device_type}:0"
595 a = torch.rand(5).to(device_0) # noqa: F841
596
597 free_memory_bytes = torch_accelerator_module.mem_get_info(device_0)[0]
598 required_memory_bytes = 2 * 5000 * 5000 * (32 // 8) # 200 MB
599
600 # Leaving 150 MB of free memory for possible buffers, etc.
601 n_vals = (free_memory_bytes - required_memory_bytes - int(200e6)) // (32 // 8)
602 foo = torch.rand(n_vals, device=device_0) # noqa: F841
603
604 free_memory_bytes_before_dispatch = torch_accelerator_module.mem_get_info(device_0)[0]
605 with TemporaryDirectory() as tmp_dir:
606 dispatch_model(model, device_map, offload_dir=tmp_dir)
607 free_memory_bytes_after_dispatch = torch_accelerator_module.mem_get_info(device_0)[0]
608
609 assert (free_memory_bytes_after_dispatch - free_memory_bytes_before_dispatch) * 1e-6 < 130
610
611 oom_error = (
612 torch.OutOfMemoryError
613 if hasattr(torch, "OutOfMemoryError")
614 else torch_accelerator_module.OutOfMemoryError
615 )
616 with torch.no_grad():
617 try:
618 output = model(x)
619 except oom_error as e:
620 raise oom_error(
621 f"OOM error in dispatch_model. This is a bug and should not happen, see test_dispatch_model_tied_weights_memory_with_nested_offload_disk. {e}"
622 )
623 except Exception as e:
624 raise e
625
626 torch.testing.assert_close(expected, output.cpu(), atol=ATOL, rtol=RTOL)
627
628 clear_device_cache()
629
630 free_memory_bytes_after_infer = torch_accelerator_module.mem_get_info(device_0)[0]
631
632 # Check that we have no more references on GPU for the offloaded tied weight.
633 n_non_empty = 0
634 for pointer, pointer_dict in model.compute1.weight_submodule._hf_hook.tied_params_map.items():
635 if len(pointer_dict) > 0:
636 n_non_empty += 1
637 assert n_non_empty == 1 # `compute` layer one.
638
639 n_non_empty = 0
640 for pointer, pointer_dict in model.compute1._hf_hook.tied_params_map.items():
641 if len(pointer_dict) > 0:
642 n_non_empty += 1
643 assert n_non_empty == 1 # `compute` layer one.
644
645 assert (free_memory_bytes_after_infer - free_memory_bytes_after_dispatch) * 1e-6 < 130
646
647 @require_non_hpu # hpu does not support device indexing "hpu:1"
648 @require_multi_device
649 def test_dispatch_model_multi_devices(self):
650 model = BiggerModelForTest()
651
652 device_map = {"linear1": "cpu", "linear2": "disk", "batchnorm": "cpu", "linear3": 0, "linear4": 1}
653
654 x = torch.randn(2, 3)
655 expected = model(x)
656
657 with TemporaryDirectory() as tmp_dir:
658 dispatch_model(model, device_map, offload_dir=tmp_dir)
659 output = model(x)
660 torch.testing.assert_close(expected, output.cpu(), atol=ATOL, rtol=RTOL)
661
662 @require_non_cpu
663 def test_dispatch_model_copy(self):
664 original_model = ModelForTestCopy(id=1)
665 device_map = {"linear1": 0, "batchnorm": "cpu", "linear2": 0}
666
667 x = torch.randn(2, 3)
668 expected, original_output_id = original_model(x)
669
670 dispatch_model(original_model, device_map)
671
672 copied_model = copy.deepcopy(original_model)
673 copied_model.id = 2
674 output, copied_output_id = copied_model(x)
675
676 assert original_model.id == original_output_id
677 assert copied_model.id == copied_output_id
678 assert copied_model.linear1.forward is not original_model.linear1.forward
679 torch.testing.assert_close(expected, output.cpu(), atol=ATOL, rtol=RTOL)
680
681 @require_non_cpu
682 def test_dispatch_model_move_offloaded_model(self):
683 model = ModelForTest()
684 device_map = {"linear1": "disk", "batchnorm": "cpu", "linear2": 0}
685 with TemporaryDirectory() as tmp_dir:
686 dispatch_model(model, device_map, offload_dir=tmp_dir)
687 with self.assertRaises(RuntimeError):
688 model.to(0)
689
690 @require_non_hpu # hpu does not support device indexing "hpu:1"
691 @require_multi_device
692 def test_dispatch_model_move_model_warning(self):
693 model = ModelForTest()
694 device_map = {"linear1": 0, "batchnorm": 0, "linear2": 1}
695 with TemporaryDirectory() as tmp_dir:
696 dispatch_model(model, device_map, offload_dir=tmp_dir)
697 with self.assertLogs("accelerate.big_modeling", level="WARNING"):
698 model.to("cpu")
699 with self.assertLogs("accelerate.big_modeling", level="WARNING"):
700 model.to(torch_device)
701 with self.assertRaises(RuntimeError):
702 x = torch.randn(2, 3)
703 model(x)
704
705 @slow
706 @require_non_hpu # hpu does not support device indexing "hpu:1"
707 @require_multi_device
708 def test_dispatch_model_gpt2_on_two_devices(self):
709 tokenizer = AutoTokenizer.from_pretrained("gpt2")
710 inputs = tokenizer("Hello world! My name is", return_tensors="pt").to(torch_device)
711
712 gpt2 = AutoModelForCausalLM.from_pretrained("gpt2")
713 # Dispatch on GPUs 0 and 1
714 device_map = {
715 "transformer.wte": 0,
716 "transformer.wpe": 0,
717 "transformer.ln_f": 1,
718 "lm_head": 0,
719 }
720 for i in range(12):
721 device_map[f"transformer.h.{i}"] = 0 if i <= 5 else 1
722
723 gpt2 = dispatch_model(gpt2, device_map)
724 outputs = gpt2.generate(inputs["input_ids"], max_new_tokens=10)
725 assert tokenizer.decode(outputs[0].tolist()) == "Hello world! My name is Kiyoshi, and I'm a student at"
726
727 # Dispatch with a bit of CPU offload
728 gpt2 = AutoModelForCausalLM.from_pretrained("gpt2")
729 for i in range(4):
730 device_map[f"transformer.h.{i}"] = "cpu"
731 gpt2 = dispatch_model(gpt2, device_map)
732 outputs = gpt2.generate(inputs["input_ids"], max_new_tokens=10)
733 assert tokenizer.decode(outputs[0].tolist()) == "Hello world! My name is Kiyoshi, and I'm a student at"
734 # Dispatch with a bit of CPU and disk offload
735 gpt2 = AutoModelForCausalLM.from_pretrained("gpt2")
736 for i in range(2):
737 device_map[f"transformer.h.{i}"] = "disk"
738
739 with TemporaryDirectory() as tmp_dir:
740 state_dict = {
741 k: p for k, p in gpt2.state_dict().items() if "transformer.h.0" in k or "transformer.h.1" in k
742 }
743 offload_state_dict(tmp_dir, state_dict)
744 gpt2 = dispatch_model(gpt2, device_map, offload_dir=tmp_dir)
745 outputs = gpt2.generate(inputs["input_ids"], max_new_tokens=10)
746 assert tokenizer.decode(outputs[0].tolist()) == "Hello world! My name is Kiyoshi, and I'm a student at"
747
748 @require_non_cpu
749 def test_dispatch_model_with_unused_submodules(self):
750 model = ModelWithUnusedSubModulesForTest()
751 device_map = {"linear1": "cpu", "linear2": "disk", "batchnorm": "cpu", "linear3": 0, "linear4": 0}
752
753 x = torch.randn(2, 3)
754 expected = model(x)
755
756 with TemporaryDirectory() as tmp_dir:
757 dispatch_model(
758 model, device_map, offload_dir=tmp_dir, preload_module_classes=["ModuleWithUnusedSubModules"]
759 )
760 output = model(x)
761 torch.testing.assert_close(expected, output.cpu(), atol=ATOL, rtol=RTOL)
762
763 @require_non_hpu # hpu does not support device indexing "hpu:1"
764 @require_multi_device
765 def test_dispatch_model_with_unused_submodules_multi_device(self):
766 model = ModelWithUnusedSubModulesForTest()
767
768 device_map = {"linear1": "cpu", "linear2": "disk", "batchnorm": "cpu", "linear3": 0, "linear4": 1}
769
770 x = torch.randn(2, 3)
771 expected = model(x)
772
773 with TemporaryDirectory() as tmp_dir:
774 dispatch_model(
775 model, device_map, offload_dir=tmp_dir, preload_module_classes=["ModuleWithUnusedSubModules"]
776 )
777 output = model(x)
778 torch.testing.assert_close(expected, output.cpu(), atol=ATOL, rtol=RTOL)
779
780 @require_non_cpu
781 def test_dispatch_model_force_hooks(self):
782 model = ModelForTest()
783 device_map = {"": 0}
784
785 x = torch.randn(2, 3)
786 expected = model(x)
787
788 dispatch_model(model, device_map, force_hooks=True)
789 output = model(x)
790 torch.testing.assert_close(expected, output.cpu(), atol=ATOL, rtol=RTOL)
791
792 @require_non_cpu
793 def test_load_checkpoint_and_dispatch(self):
794 model = ModelForTest()
795 device_map = {"linear1": "cpu", "batchnorm": "cpu", "linear2": 0}
796
797 x = torch.randn(2, 3)
798 expected = model(x)
799
800 with TemporaryDirectory() as tmp_dir:
801 checkpoint = os.path.join(tmp_dir, "pt_model.bin")
802 torch.save(model.state_dict(), checkpoint)
803
804 new_model = ModelForTest()
805 new_model = load_checkpoint_and_dispatch(new_model, checkpoint, device_map=device_map)
806
807 # CPU-offloaded weights are on the meta device while waiting for the forward pass.
808 assert new_model.linear1.weight.device == torch.device("meta")
809 assert new_model.linear2.weight.device == torch.device(torch_device)
810
811 output = new_model(x)
812 torch.testing.assert_close(expected, output.cpu(), atol=ATOL, rtol=RTOL)
813
814 def test_load_checkpoint_and_dispatch_device_map_none(self):
815 model = ModelForTest()
816
817 with TemporaryDirectory() as tmp_dir:
818 checkpoint = os.path.join(tmp_dir, "pt_model.bin")
819 torch.save(model.state_dict(), checkpoint)
820
821 new_model = ModelForTest()
822 new_model = load_checkpoint_and_dispatch(new_model, checkpoint, device_map=None)
823
824 for (name, tensor), (new_name, new_tensor) in zip(
825 itertools.chain(model.named_parameters(), model.named_buffers()),
826 itertools.chain(new_model.named_parameters(), new_model.named_buffers()),
827 ):
828 assert name == new_name
829 torch.testing.assert_close(tensor, new_tensor, msg=new_name)
830
831 @require_non_hpu # hpu does not support device indexing "hpu:1"
832 @require_multi_device
833 def test_load_checkpoint_and_dispatch_multi_device(self):
834 model = BiggerModelForTest()
835
836 device_map = {"linear1": "cpu", "linear2": "cpu", "batchnorm": 0, "linear3": 0, "linear4": 1}
837
838 x = torch.randn(2, 3)
839 expected = model(x)
840
841 with TemporaryDirectory() as tmp_dir:
842 checkpoint = os.path.join(tmp_dir, "pt_model.bin")
843 torch.save(model.state_dict(), checkpoint)
844
845 new_model = BiggerModelForTest()
846 new_model = load_checkpoint_and_dispatch(new_model, checkpoint, device_map=device_map)
847
848 # CPU-offloaded weights are on the meta device while waiting for the forward pass.
849 assert new_model.linear1.weight.device == torch.device("meta")
850 assert new_model.linear2.weight.device == torch.device("meta")
851 assert new_model.linear3.weight.device == torch.device(torch_device)
852 assert new_model.linear4.weight.device == torch.device(torch_device.replace(":0", ":1"))
853
854 output = new_model(x)
855 torch.testing.assert_close(expected, output.cpu(), atol=ATOL, rtol=RTOL)
856
857 @require_non_cpu
858 def test_load_checkpoint_and_dispatch_with_unused_submodules(self):
859 model = ModelWithUnusedSubModulesForTest()
860 device_map = {"linear1": "cpu", "linear2": "cpu", "batchnorm": 0, "linear3": 0, "linear4": 0}
861
862 x = torch.randn(2, 3)
863 expected = model(x)
864
865 with TemporaryDirectory() as tmp_dir:
866 checkpoint = os.path.join(tmp_dir, "pt_model.bin")
867 torch.save(model.state_dict(), checkpoint)
868
869 new_model = ModelWithUnusedSubModulesForTest()
870 new_model = load_checkpoint_and_dispatch(
871 new_model, checkpoint, device_map=device_map, preload_module_classes=["ModuleWithUnusedSubModules"]
872 )
873
874 # CPU-offloaded weights are on the meta device while waiting for the forward pass.
875 assert new_model.linear1.linear.weight.device == torch.device("meta")
876 assert new_model.linear2.linear.weight.device == torch.device("meta")
877 assert new_model.linear3.linear.weight.device == torch.device(torch_device)
878 assert new_model.linear4.linear.weight.device == torch.device(torch_device)
879
880 output = new_model(x)
881 torch.testing.assert_close(expected, output.cpu(), atol=ATOL, rtol=RTOL)
882
883 @require_non_hpu # hpu does not support device indexing "hpu:1"
884 @require_multi_device
885 def test_load_checkpoint_and_dispatch_multi_device_with_unused_submodules(self):
886 model = ModelWithUnusedSubModulesForTest()
887
888 device_map = {"linear1": "cpu", "linear2": "cpu", "batchnorm": 0, "linear3": 0, "linear4": 1}
889
890 x = torch.randn(2, 3)
891 expected = model(x)
892
893 with TemporaryDirectory() as tmp_dir:
894 checkpoint = os.path.join(tmp_dir, "pt_model.bin")
895 torch.save(model.state_dict(), checkpoint)
896
897 new_model = ModelWithUnusedSubModulesForTest()
898 new_model = load_checkpoint_and_dispatch(
899 new_model, checkpoint, device_map=device_map, preload_module_classes=["ModuleWithUnusedSubModules"]
900 )
901
902 # CPU-offloaded weights are on the meta device while waiting for the forward pass.
903 assert new_model.linear1.linear.weight.device == torch.device("meta")
904 assert new_model.linear2.linear.weight.device == torch.device("meta")
905 assert new_model.linear3.linear.weight.device == torch.device(torch_device)
906 assert new_model.linear4.linear.weight.device == torch.device(torch_device.replace(":0", ":1"))
907
908 output = new_model(x)
909 torch.testing.assert_close(expected, output.cpu(), atol=ATOL, rtol=RTOL)
910
911 @require_non_cpu
912 def test_cpu_offload_with_hook(self):
913 model1 = torch.nn.Linear(4, 5)
914 model1, hook1 = cpu_offload_with_hook(model1)
915 assert model1.weight.device == torch.device("cpu")
916
917 inputs = torch.randn(3, 4)
918 outputs = model1(inputs)
919 assert outputs.device == torch.device(torch_device)
920 assert model1.weight.device == torch.device(torch_device)
921
922 hook1.offload()
923 assert model1.weight.device == torch.device("cpu")
924
925 model2 = torch.nn.Linear(5, 5)
926 model2, hook2 = cpu_offload_with_hook(model2, prev_module_hook=hook1)
927 assert model2.weight.device == torch.device("cpu")
928
929 outputs = model1(inputs)
930 assert outputs.device == torch.device(torch_device)
931 assert model1.weight.device == torch.device(torch_device)
932
933 outputs = model2(outputs)
934 assert outputs.device == torch.device(torch_device)
935 assert model1.weight.device == torch.device("cpu")
936 assert model2.weight.device == torch.device(torch_device)
937
938 hook2.offload()
939 assert model2.weight.device == torch.device("cpu")
940
941 @slow
942 @require_bnb
943 @require_non_hpu # bnb is not supported on hpu
944 @require_non_torch_xla
945 @require_multi_device
946 def test_dispatch_model_bnb(self):
947 """Tests that `dispatch_model` quantizes int8 layers"""
948 from huggingface_hub import hf_hub_download
949 from transformers import AutoConfig, AutoModel, BitsAndBytesConfig
950 from transformers.integrations.bitsandbytes import replace_with_bnb_linear
951
952 with init_empty_weights():
953 model = AutoModel.from_config(AutoConfig.from_pretrained("bigscience/bloom-560m"))
954
955 quantization_config = BitsAndBytesConfig(load_in_8bit=True)
956 model = replace_with_bnb_linear(
957 model, modules_to_not_convert=["lm_head"], quantization_config=quantization_config
958 )
959
960 model_path = hf_hub_download("bigscience/bloom-560m", "pytorch_model.bin")
961
962 model = load_checkpoint_and_dispatch(
963 model,
964 checkpoint=model_path,
965 device_map="balanced",
966 )
967
968 assert model.h[0].self_attention.query_key_value.weight.dtype == torch.int8
969 assert model.h[0].self_attention.query_key_value.weight.device.index == 0
970
971 assert model.h[(-1)].self_attention.query_key_value.weight.dtype == torch.int8
972 assert model.h[(-1)].self_attention.query_key_value.weight.device.index == 1
973
974 @require_cuda_or_xpu
975 @slow
976 @require_bnb
977 def test_dispatch_model_int8_simple(self):
978 """Tests that `dispatch_model` quantizes int8 layers"""
979 from huggingface_hub import hf_hub_download
980 from transformers import AutoConfig, AutoModel, BitsAndBytesConfig
981 from transformers.integrations.bitsandbytes import replace_with_bnb_linear
982
983 with init_empty_weights():
984 model = AutoModel.from_config(AutoConfig.from_pretrained("bigscience/bloom-560m"))
985
986 quantization_config = BitsAndBytesConfig(load_in_8bit=True)
987 model = replace_with_bnb_linear(
988 model, modules_to_not_convert=["lm_head"], quantization_config=quantization_config
989 )
990
991 model_path = hf_hub_download("bigscience/bloom-560m", "pytorch_model.bin")
992
993 # test with auto
994 model = load_checkpoint_and_dispatch(
995 model,
996 checkpoint=model_path,
997 device_map="auto",
998 )
999
1000 assert model.h[0].self_attention.query_key_value.weight.dtype == torch.int8
1001 assert model.h[0].self_attention.query_key_value.weight.device.index == 0
1002
1003 with init_empty_weights():
1004 model = AutoModel.from_config(AutoConfig.from_pretrained("bigscience/bloom-560m"))
1005
1006 model = replace_with_bnb_linear(
1007 model, modules_to_not_convert=["lm_head"], quantization_config=quantization_config
1008 )
1009
1010 # test with str device map
1011 model = load_checkpoint_and_dispatch(
1012 model,
1013 checkpoint=model_path,
1014 device_map={"": torch_device},
1015 )
1016
1017 assert model.h[0].self_attention.query_key_value.weight.dtype == torch.int8
1018 assert model.h[0].self_attention.query_key_value.weight.device.index == 0
1019
1020 with init_empty_weights():
1021 model = AutoModel.from_config(AutoConfig.from_pretrained("bigscience/bloom-560m"))
1022
1023 model = replace_with_bnb_linear(
1024 model, modules_to_not_convert=["lm_head"], quantization_config=quantization_config
1025 )
1026
1027 # test with torch.device device map
1028 model = load_checkpoint_and_dispatch(
1029 model,
1030 checkpoint=model_path,
1031 device_map={"": torch_device},
1032 )
1033
1034 assert model.h[0].self_attention.query_key_value.weight.dtype == torch.int8
1035 assert model.h[0].self_attention.query_key_value.weight.device.index == 0
1036
1037 @require_cuda_or_xpu
1038 @slow
1039 @require_bnb
1040 def test_dipatch_model_fp4_simple(self):
1041 """Tests that `dispatch_model` quantizes fp4 layers"""
1042 from huggingface_hub import hf_hub_download
1043 from transformers import AutoConfig, AutoModel, BitsAndBytesConfig
1044 from transformers.integrations.bitsandbytes import replace_with_bnb_linear
1045
1046 with init_empty_weights():
1047 model = AutoModel.from_config(AutoConfig.from_pretrained("bigscience/bloom-560m"))
1048
1049 quantization_config = BitsAndBytesConfig(load_in_4bit=True)
1050
1051 model = replace_with_bnb_linear(
1052 model, modules_to_not_convert=["lm_head"], quantization_config=quantization_config
1053 )
1054
1055 model_path = hf_hub_download("bigscience/bloom-560m", "pytorch_model.bin")
1056
1057 # test with auto
1058 model = load_checkpoint_and_dispatch(
1059 model,
1060 checkpoint=model_path,
1061 device_map="auto",
1062 )
1063
1064 assert model.h[0].self_attention.query_key_value.weight.dtype == torch.uint8
1065 assert model.h[0].self_attention.query_key_value.weight.device.index == 0
1066
1067 with init_empty_weights():
1068 model = AutoModel.from_config(AutoConfig.from_pretrained("bigscience/bloom-560m"))
1069
1070 model = replace_with_bnb_linear(
1071 model, modules_to_not_convert=["lm_head"], quantization_config=quantization_config
1072 )
1073
1074 # test with str device map
1075 model = load_checkpoint_and_dispatch(
1076 model,
1077 checkpoint=model_path,
1078 device_map={"": torch_device},
1079 )
1080
1081 assert model.h[0].self_attention.query_key_value.weight.dtype == torch.uint8
1082 assert model.h[0].self_attention.query_key_value.weight.device.index == 0
1083
1084 with init_empty_weights():
1085 model = AutoModel.from_config(AutoConfig.from_pretrained("bigscience/bloom-560m"))
1086
1087 model = replace_with_bnb_linear(
1088 model, modules_to_not_convert=["lm_head"], quantization_config=quantization_config
1089 )
1090
1091 # test with torch.device device map
1092 model = load_checkpoint_and_dispatch(
1093 model,
1094 checkpoint=model_path,
1095 device_map={"": torch_device},
1096 )
1097
1098 assert model.h[0].self_attention.query_key_value.weight.dtype == torch.uint8
1099 assert model.h[0].self_attention.query_key_value.weight.device.index == 0