Debian Codegraph @

tests/test_hooks.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
15 import inspect
16 import re
17 import unittest
18
19 import torch
20 import torch.nn as nn
21 from parameterized import parameterized
22 from torch.fx import symbolic_trace
23
24 from accelerate.big_modeling import attach_layerwise_casting_hooks
25 from accelerate.hooks import (
26 AlignDevicesHook,
27 CpuOffload,
28 ModelHook,
29 SequentialHook,
30 UserCpuOffloadHook,
31 add_hook_to_module,
32 attach_align_device_hook,
33 remove_hook_from_module,
34 remove_hook_from_submodules,
35 )
36 from accelerate.test_utils import require_multi_device, require_non_hpu, torch_device
37 from accelerate.utils import is_xpu_available
38 from accelerate.utils.constants import SUPPORTED_PYTORCH_LAYERS_FOR_UPCASTING
39
40
41 torch_device = f"{torch_device}:0" if torch_device != "cpu" else "cpu"
42
43
44 class ModelForTest(nn.Module):
45 def __init__(self):
46 super().__init__()
47 self.linear1 = nn.Linear(3, 4)
48 self.batchnorm = nn.BatchNorm1d(4)
49 self.linear2 = nn.Linear(4, 5)
50
51 def forward(self, x):
52 return self.linear2(self.batchnorm(self.linear1(x)))
53
54
55 class PreForwardHook(ModelHook):
56 def pre_forward(self, module, *args, **kwargs):
57 return (args[0] + 1,) + args[1:], kwargs
58
59
60 class PostForwardHook(ModelHook):
61 def post_forward(self, module, output):
62 return output + 1
63
64
65 class HooksModelTester(unittest.TestCase):
66 def check_dtype_for_layerwise_upcasting(
67 self,
68 module,
69 storage_dtype,
70 loading_type,
71 patterns_to_check=None,
72 ):
73 for name, submodule in module.named_modules():
74 attrs = []
75 if getattr(submodule, "weight", None) is not None:
76 attrs.append(("weight", submodule.weight))
77 if getattr(submodule, "bias", None) is not None:
78 attrs.append(("bias", submodule.bias))
79
80 if not isinstance(submodule, SUPPORTED_PYTORCH_LAYERS_FOR_UPCASTING):
81 if patterns_to_check is None:
82 for _, tensor in attrs:
83 self.assertEqual(tensor.dtype, loading_type)
84 continue
85
86 if patterns_to_check and any(re.search(pat, name) for pat in patterns_to_check):
87 expected = loading_type
88 else:
89 expected = storage_dtype
90
91 for _, tensor in attrs:
92 self.assertEqual(tensor.dtype, expected)
93
94 def test_add_and_remove_hooks(self):
95 test_model = ModelForTest()
96 test_hook = ModelHook()
97
98 add_hook_to_module(test_model, test_hook)
99 assert test_model._hf_hook == test_hook
100 assert hasattr(test_model, "_old_forward")
101
102 # Check adding the hook did not change the name or the signature
103 assert test_model.forward.__name__ == "forward"
104 assert list(inspect.signature(test_model.forward).parameters) == ["x"]
105
106 remove_hook_from_module(test_model)
107 assert not hasattr(test_model, "_hf_hook")
108 assert not hasattr(test_model, "_old_forward")
109
110 def test_append_and_remove_hooks(self):
111 test_model = ModelForTest()
112 test_hook = ModelHook()
113
114 add_hook_to_module(test_model, test_hook)
115 add_hook_to_module(test_model, test_hook, append=True)
116
117 assert isinstance(test_model._hf_hook, SequentialHook) is True
118 assert len(test_model._hf_hook.hooks) == 2
119 assert hasattr(test_model, "_old_forward")
120
121 # Check adding the hook did not change the name or the signature
122 assert test_model.forward.__name__ == "forward"
123 assert list(inspect.signature(test_model.forward).parameters) == ["x"]
124
125 remove_hook_from_module(test_model)
126 assert not hasattr(test_model, "_hf_hook")
127 assert not hasattr(test_model, "_old_forward")
128
129 def test_pre_forward_hook_is_executed(self):
130 test_model = ModelForTest()
131 x = torch.randn(2, 3)
132 expected = test_model(x + 1)
133 expected2 = test_model(x + 2)
134
135 test_hook = PreForwardHook()
136 add_hook_to_module(test_model, test_hook)
137 output1 = test_model(x)
138 assert torch.allclose(output1, expected, atol=1e-5)
139
140 # Attaching a hook to a model when it already has one replaces, does not chain
141 test_hook = PreForwardHook()
142 add_hook_to_module(test_model, test_hook)
143 output1 = test_model(x)
144 assert torch.allclose(output1, expected, atol=1e-5)
145
146 # You need to use the sequential hook to chain two or more hooks
147 test_hook = SequentialHook(PreForwardHook(), PreForwardHook())
148 add_hook_to_module(test_model, test_hook)
149
150 output2 = test_model(x)
151 assert torch.allclose(output2, expected2, atol=1e-5)
152
153 def test_post_forward_hook_is_executed(self):
154 test_model = ModelForTest()
155 x = torch.randn(2, 3)
156 output = test_model(x)
157
158 test_hook = PostForwardHook()
159 add_hook_to_module(test_model, test_hook)
160 output1 = test_model(x)
161 assert torch.allclose(output1, (output + 1), atol=1e-5)
162
163 # Attaching a hook to a model when it already has one replaces, does not chain
164 test_hook = PostForwardHook()
165 add_hook_to_module(test_model, test_hook)
166 output1 = test_model(x)
167 assert torch.allclose(output1, (output + 1), atol=1e-5)
168
169 # You need to use the sequential hook to chain two or more hooks
170 test_hook = SequentialHook(PostForwardHook(), PostForwardHook())
171 add_hook_to_module(test_model, test_hook)
172
173 output2 = test_model(x)
174 assert torch.allclose(output2, output + 2, atol=1e-5)
175
176 def test_no_grad_in_hook(self):
177 test_model = ModelForTest()
178 x = torch.randn(2, 3)
179 output = test_model(x)
180
181 test_hook = PostForwardHook()
182 add_hook_to_module(test_model, test_hook)
183 output1 = test_model(x)
184 assert torch.allclose(output1, (output + 1))
185 assert output1.requires_grad
186
187 test_hook.no_grad = True
188 output1 = test_model(x)
189 assert not output1.requires_grad
190
191 @require_non_hpu # hpu does not support device indexing "hpu:1"
192 @require_multi_device
193 def test_align_devices_as_model_parallelism(self):
194 model = ModelForTest()
195 # Everything is on CPU
196 assert model.linear1.weight.device == torch.device("cpu")
197 assert model.batchnorm.weight.device == torch.device("cpu")
198 assert model.linear2.weight.device == torch.device("cpu")
199
200 # This will move each submodule on different devices
201 add_hook_to_module(model.linear1, AlignDevicesHook(execution_device=0))
202 add_hook_to_module(model.batchnorm, AlignDevicesHook(execution_device=0))
203 add_hook_to_module(model.linear2, AlignDevicesHook(execution_device=1))
204
205 assert model.linear1.weight.device == torch.device(torch_device)
206 assert model.batchnorm.weight.device == torch.device(torch_device)
207 assert model.batchnorm.running_mean.device == torch.device(torch_device)
208 assert model.linear2.weight.device == torch.device(torch_device.replace(":0", ":1"))
209
210 # We can still make a forward pass. The input does not need to be on any particular device
211 x = torch.randn(2, 3)
212 output = model(x)
213 assert output.device == torch.device(torch_device.replace(":0", ":1"))
214
215 # We can add a general hook to put back output on same device as input.
216 add_hook_to_module(model, AlignDevicesHook(io_same_device=True))
217 x = torch.randn(2, 3).to(torch_device)
218 output = model(x)
219 assert output.device == torch.device(torch_device)
220
221 def test_align_devices_as_cpu_offload(self):
222 model = ModelForTest()
223
224 # Everything is on CPU
225 assert model.linear1.weight.device == torch.device("cpu")
226 assert model.batchnorm.weight.device == torch.device("cpu")
227 assert model.linear2.weight.device == torch.device("cpu")
228
229 # This will move each submodule on different devices
230 hook_kwargs = {"execution_device": torch_device, "offload": True}
231
232 add_hook_to_module(model.linear1, AlignDevicesHook(**hook_kwargs))
233 add_hook_to_module(model.batchnorm, AlignDevicesHook(**hook_kwargs))
234 add_hook_to_module(model.linear2, AlignDevicesHook(**hook_kwargs))
235
236 # Parameters have been offloaded, so on the meta device
237 assert model.linear1.weight.device == torch.device("meta")
238 assert model.batchnorm.weight.device == torch.device("meta")
239 assert model.linear2.weight.device == torch.device("meta")
240 # Buffers are not included in the offload by default, so are on the execution device
241 device = torch.device(hook_kwargs["execution_device"])
242 assert model.batchnorm.running_mean.device == device
243
244 x = torch.randn(2, 3)
245 output = model(x)
246 assert output.device == device
247
248 # Removing hooks loads back the weights in the model.
249 remove_hook_from_module(model.linear1)
250 remove_hook_from_module(model.batchnorm)
251 remove_hook_from_module(model.linear2)
252 assert model.linear1.weight.device == torch.device("cpu")
253 assert model.batchnorm.weight.device == torch.device("cpu")
254 assert model.linear2.weight.device == torch.device("cpu")
255
256 # Now test with buffers included in the offload
257 hook_kwargs = {
258 "execution_device": torch_device,
259 "offload": True,
260 "offload_buffers": True,
261 }
262
263 add_hook_to_module(model.linear1, AlignDevicesHook(**hook_kwargs))
264 add_hook_to_module(model.batchnorm, AlignDevicesHook(**hook_kwargs))
265 add_hook_to_module(model.linear2, AlignDevicesHook(**hook_kwargs))
266
267 # Parameters have been offloaded, so on the meta device, buffers included
268 assert model.linear1.weight.device == torch.device("meta")
269 assert model.batchnorm.weight.device == torch.device("meta")
270 assert model.linear2.weight.device == torch.device("meta")
271 assert model.batchnorm.running_mean.device == torch.device("meta")
272
273 x = torch.randn(2, 3)
274 output = model(x)
275 assert output.device == device
276
277 # Removing hooks loads back the weights in the model.
278 remove_hook_from_module(model.linear1)
279 remove_hook_from_module(model.batchnorm)
280 remove_hook_from_module(model.linear2)
281 assert model.linear1.weight.device == torch.device("cpu")
282 assert model.batchnorm.weight.device == torch.device("cpu")
283 assert model.linear2.weight.device == torch.device("cpu")
284
285 def test_attach_align_device_hook_as_cpu_offload(self):
286 model = ModelForTest()
287
288 # Everything is on CPU
289 assert model.linear1.weight.device == torch.device("cpu")
290 assert model.batchnorm.weight.device == torch.device("cpu")
291 assert model.linear2.weight.device == torch.device("cpu")
292
293 # This will move each submodule on different devices
294 execution_device = torch_device
295 attach_align_device_hook(model, execution_device=execution_device, offload=True)
296
297 # Parameters have been offloaded, so on the meta device
298 assert model.linear1.weight.device == torch.device("meta")
299 assert model.batchnorm.weight.device == torch.device("meta")
300 assert model.linear2.weight.device == torch.device("meta")
301 # Buffers are not included in the offload by default, so are on the execution device
302 device = torch.device(execution_device)
303 assert model.batchnorm.running_mean.device == device
304
305 x = torch.randn(2, 3)
306 output = model(x)
307 assert output.device == device
308
309 # Removing hooks loads back the weights in the model.
310 remove_hook_from_submodules(model)
311 assert model.linear1.weight.device == torch.device("cpu")
312 assert model.batchnorm.weight.device == torch.device("cpu")
313 assert model.linear2.weight.device == torch.device("cpu")
314
315 # Now test with buffers included in the offload
316 attach_align_device_hook(model, execution_device=execution_device, offload=True, offload_buffers=True)
317
318 # Parameters have been offloaded, so on the meta device, buffers included
319 assert model.linear1.weight.device == torch.device("meta")
320 assert model.batchnorm.weight.device == torch.device("meta")
321 assert model.linear2.weight.device == torch.device("meta")
322 assert model.batchnorm.running_mean.device == torch.device("meta")
323
324 x = torch.randn(2, 3)
325 output = model(x)
326 assert output.device == device
327
328 # Removing hooks loads back the weights in the model.
329 remove_hook_from_submodules(model)
330 assert model.linear1.weight.device == torch.device("cpu")
331 assert model.batchnorm.weight.device == torch.device("cpu")
332 assert model.linear2.weight.device == torch.device("cpu")
333
334 def test_attach_align_device_hook_as_cpu_offload_with_weight_map(self):
335 model = ModelForTest()
336
337 # Everything is on CPU
338 assert model.linear1.weight.device == torch.device("cpu")
339 assert model.batchnorm.weight.device == torch.device("cpu")
340 assert model.linear2.weight.device == torch.device("cpu")
341
342 # This will move each submodule on different devices
343 execution_device = torch_device
344 attach_align_device_hook(
345 model, execution_device=execution_device, offload=True, weights_map=model.state_dict()
346 )
347
348 # Parameters have been offloaded, so on the meta device
349 assert model.linear1.weight.device == torch.device("meta")
350 assert model.batchnorm.weight.device == torch.device("meta")
351 assert model.linear2.weight.device == torch.device("meta")
352 # Buffers are not included in the offload by default, so are on the execution device
353 device = torch.device(execution_device)
354 assert model.batchnorm.running_mean.device == device
355
356 x = torch.randn(2, 3)
357 output = model(x)
358 assert output.device == device
359
360 # Removing hooks loads back the weights in the model.
361 remove_hook_from_submodules(model)
362 assert model.linear1.weight.device == torch.device("cpu")
363 assert model.batchnorm.weight.device == torch.device("cpu")
364 assert model.linear2.weight.device == torch.device("cpu")
365
366 # Now test with buffers included in the offload
367 attach_align_device_hook(
368 model,
369 execution_device=execution_device,
370 offload=True,
371 weights_map=model.state_dict(),
372 offload_buffers=True,
373 )
374
375 # Parameters have been offloaded, so on the meta device, buffers included
376 assert model.linear1.weight.device == torch.device("meta")
377 assert model.batchnorm.weight.device == torch.device("meta")
378 assert model.linear2.weight.device == torch.device("meta")
379 assert model.batchnorm.running_mean.device == torch.device("meta")
380
381 x = torch.randn(2, 3)
382 output = model(x)
383 assert output.device == device
384
385 # Removing hooks loads back the weights in the model.
386 remove_hook_from_submodules(model)
387 assert model.linear1.weight.device == torch.device("cpu")
388 assert model.batchnorm.weight.device == torch.device("cpu")
389 assert model.linear2.weight.device == torch.device("cpu")
390
391 def test_add_remove_hook_fx_graph_module(self):
392 with torch.no_grad():
393 test_model = ModelForTest()
394 test_hook = ModelHook()
395
396 x = torch.randn(2, 3)
397 output1 = test_model(x)
398
399 graph_model = symbolic_trace(test_model)
400
401 output2 = graph_model(x)
402
403 assert torch.allclose(output1, output2)
404
405 add_hook_to_module(graph_model, test_hook)
406 remove_hook_from_module(graph_model, recurse=True)
407
408 # We want to make sure that `add_hook_to_module` and `remove_hook_from_module` yields back an fx.GraphModule
409 # that behaves correctly (for example that is not frozen, see https://github.com/huggingface/accelerate/pull/2369).
410 # For that, we add a sigmoid node to the FX graph and make sure that the new output (output3 below) is different than
411 # the original model's output.
412 linear2_node = None
413 for node in graph_model.graph.nodes:
414 if node.name == "linear2":
415 linear2_node = node
416 assert linear2_node is not None
417
418 graph_model.graph.inserting_after(linear2_node)
419 new_node = graph_model.graph.create_node(
420 op="call_function", target=torch.sigmoid, args=(linear2_node,), name="relu"
421 )
422
423 output_node = None
424 for node in graph_model.graph.nodes:
425 if node.name == "output":
426 output_node = node
427 assert output_node is not None
428
429 output_node.replace_input_with(linear2_node, new_node)
430
431 graph_model.graph.lint()
432 graph_model.recompile()
433
434 output3 = graph_model(x)
435
436 # Now the output is expected to be different since we modified the graph.
437 assert not torch.allclose(output1, output3)
438
439 @parameterized.expand(
440 [
441 (torch.float16, torch.float32),
442 (torch.float8_e4m3fn, torch.float32),
443 (torch.float8_e4m3fn, torch.float32, ["batchnorm"]),
444 ]
445 )
446 def test_layerwise_upcasting_inference(self, storage_dtype, compute_dtype, skip_modules_pattern=None):
447 test_model = ModelForTest()
448 loading_dtype = next(test_model.parameters()).data.dtype
449 inputs = torch.randn(2, 3)
450 inputs = inputs.to(compute_dtype) if inputs.dtype == torch.float32 else inputs
451
452 attach_layerwise_casting_hooks(
453 test_model,
454 storage_dtype=storage_dtype,
455 compute_dtype=compute_dtype,
456 skip_modules_pattern=skip_modules_pattern,
457 )
458 patterns_to_check = skip_modules_pattern if skip_modules_pattern else None
459 self.check_dtype_for_layerwise_upcasting(test_model, storage_dtype, loading_dtype, patterns_to_check)
460
461 with torch.no_grad():
462 _ = test_model(inputs)
463
464 def test_cpu_offload_hook_moves_model(self):
465 if not torch.cuda.is_available() and not is_xpu_available():
466 self.skipTest("CUDA or XPU not available for offload test.")
467
468 model = ModelForTest()
469 device = torch.device(torch_device)
470 hook = CpuOffload(execution_device=device)
471 add_hook_to_module(model, hook)
472
473 x = torch.randn(2, 3).to(device)
474 output = model(x)
475 self.assertEqual(output.device, device)
476
477 remove_hook_from_module(model)
478 output2 = model(x)
479 self.assertEqual(output2.device, device)
480
481 # should be on the device
482 assert model.linear1.weight.device == device
483 assert model.batchnorm.weight.device == device
484 assert model.linear2.weight.device == device
485
486 def test_cpu_offload_hook_with_prev_module(self):
487 if not torch.cuda.is_available() and not is_xpu_available():
488 self.skipTest("CUDA or XPU not available for offload test.")
489
490 model1 = ModelForTest()
491 model2 = ModelForTest()
492 device = torch.device(torch_device)
493 cpu_device = torch.device("cpu")
494
495 hook1 = CpuOffload(execution_device=device)
496 add_hook_to_module(model1, hook1)
497 user_hook1 = UserCpuOffloadHook(model1, hook1)
498
499 hook2 = CpuOffload(execution_device=device, prev_module_hook=user_hook1)
500 add_hook_to_module(model2, hook2)
501
502 x = torch.randn(2, 3).to(device)
503 output1 = model1(x)
504 self.assertEqual(output1.device, device)
505
506 output2 = model2(x)
507 self.assertEqual(output2.device, device)
508
509 # should be on the cpu
510 assert model1.linear1.weight.device == cpu_device
511 assert model1.batchnorm.weight.device == cpu_device
512 assert model1.linear2.weight.device == cpu_device
513
514 # should be on the device still
515 assert model2.linear1.weight.device == device
516 assert model2.batchnorm.weight.device == device
517 assert model2.linear2.weight.device == device