Debian Codegraph @

tests/test_multidevice.py

raw
1 # Copyright 2021 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 unittest
17 from unittest import skip
18
19 import torch
20
21 from accelerate import Accelerator
22 from accelerate.big_modeling import dispatch_model
23 from accelerate.test_utils import (
24 DEFAULT_LAUNCH_COMMAND,
25 assert_exception,
26 device_count,
27 execute_subprocess_async,
28 get_launch_command,
29 path_in_accelerate_package,
30 require_huggingface_suite,
31 require_multi_device,
32 require_non_torch_xla,
33 require_pippy,
34 require_torchvision,
35 run_first,
36 torch_device,
37 )
38 from accelerate.utils import is_hpu_available, patch_environment
39
40
41 class MultiDeviceTester(unittest.TestCase):
42 test_file_path = path_in_accelerate_package("test_utils", "scripts", "test_script.py")
43 data_loop_file_path = path_in_accelerate_package("test_utils", "scripts", "test_distributed_data_loop.py")
44 operation_file_path = path_in_accelerate_package("test_utils", "scripts", "test_ops.py")
45 pippy_file_path = path_in_accelerate_package("test_utils", "scripts", "external_deps", "test_pippy.py")
46 merge_weights_file_path = path_in_accelerate_package("test_utils", "scripts", "test_merge_weights.py")
47
48 @run_first
49 @require_multi_device
50 def test_multi_device(self):
51 print(f"Found {device_count} {torch_device} devices.")
52 cmd = DEFAULT_LAUNCH_COMMAND + [self.test_file_path]
53 with patch_environment(omp_num_threads=1):
54 execute_subprocess_async(cmd)
55
56 @run_first
57 @require_multi_device
58 def test_multi_device_ops(self):
59 print(f"Found {device_count} {torch_device} devices.")
60 cmd = DEFAULT_LAUNCH_COMMAND + [self.operation_file_path]
61 with patch_environment(omp_num_threads=1):
62 execute_subprocess_async(cmd)
63
64 @run_first
65 @require_multi_device
66 def test_pad_across_processes(self):
67 print(f"Found {device_count} {torch_device} devices.")
68 cmd = DEFAULT_LAUNCH_COMMAND + [inspect.getfile(self.__class__)]
69 with patch_environment(omp_num_threads=1):
70 execute_subprocess_async(cmd)
71
72 @run_first
73 @require_multi_device
74 def test_multi_device_merge_fsdp_weights(self):
75 print(f"Found {device_count} {torch_device} devices.")
76 cmd = DEFAULT_LAUNCH_COMMAND + [self.merge_weights_file_path]
77
78 env_kwargs = dict(omp_num_threads=1)
79 with patch_environment(**env_kwargs):
80 execute_subprocess_async(cmd)
81
82 @run_first
83 @require_non_torch_xla
84 @require_multi_device
85 def test_distributed_data_loop(self):
86 """
87 This TestCase checks the behaviour that occurs during distributed training or evaluation,
88 when the batch size does not evenly divide the dataset size.
89 """
90 print(f"Found {device_count} devices, using 2 devices only")
91 cmd = get_launch_command(num_processes=2) + [self.data_loop_file_path]
92
93 env_kwargs = dict(omp_num_threads=1)
94 if torch_device == "xpu":
95 env_kwargs.update(ze_affinity_mask="0,1")
96 elif torch_device == "npu":
97 env_kwargs.update(ascend_rt_visible_devices="0,1")
98 elif torch_device == "mlu":
99 env_kwargs.update(mlu_visible_devices="0,1")
100 elif torch_device == "sdaa":
101 env_kwargs.update(sdaa_visible_devices="0,1")
102 else:
103 env_kwargs.update(cuda_visible_devices="0,1")
104
105 with patch_environment(**env_kwargs):
106 execute_subprocess_async(cmd)
107
108 @run_first
109 @require_pippy
110 @require_torchvision
111 @require_multi_device
112 @require_huggingface_suite
113 @skip("Will soon deprecate pippy")
114 def test_pippy(self):
115 """
116 Checks the integration with the pippy framework
117 """
118 print(f"Found {device_count} {torch_device} devices")
119 cmd = get_launch_command(multi_gpu=True, num_processes=device_count) + [self.pippy_file_path]
120 with patch_environment(omp_num_threads=1):
121 execute_subprocess_async(cmd)
122
123
124 if __name__ == "__main__":
125 accelerator = Accelerator()
126 shape = (accelerator.state.process_index + 2, 10)
127 tensor = torch.randint(0, 10, shape).to(accelerator.device)
128
129 error_msg = ""
130
131 tensor1 = accelerator.pad_across_processes(tensor)
132 if tensor1.shape[0] != accelerator.state.num_processes + 1:
133 error_msg += f"Found shape {tensor1.shape} but should have {accelerator.state.num_processes + 1} at dim 0."
134 index = accelerator.state.process_index + 2
135 if not torch.equal(tensor1[:index], tensor):
136 error_msg += "Tensors have different values."
137 if not torch.all(tensor1[index:] == 0):
138 error_msg += "Padding was not done with the right value (0)."
139
140 tensor2 = accelerator.pad_across_processes(tensor.clone(), pad_first=True)
141 if tensor2.shape[0] != accelerator.state.num_processes + 1:
142 error_msg += f"Found shape {tensor2.shape} but should have {accelerator.state.num_processes + 1} at dim 0."
143 index = accelerator.state.num_processes - accelerator.state.process_index - 1
144 if not torch.equal(tensor2[index:], tensor):
145 error_msg += "Tensors have different values."
146 if not torch.all(tensor2[:index] == 0):
147 error_msg += "Padding was not done with the right value (0)."
148
149 # Raise error at the end to make sure we don't stop at the first failure.
150 if len(error_msg) > 0:
151 raise ValueError(error_msg)
152
153 # Check device_map
154 accelerator.print("Test `device_map` cannot be prepared.")
155
156 class ModelForTest(torch.nn.Module):
157 def __init__(self):
158 super().__init__()
159 self.linear1 = torch.nn.Linear(3, 4)
160 self.batchnorm = torch.nn.BatchNorm1d(4)
161 self.linear2 = torch.nn.Linear(4, 5)
162
163 def forward(self, x):
164 return self.linear2(self.batchnorm(self.linear1(x)))
165
166 if is_hpu_available():
167 device_map = {"linear1": 0, "batchnorm": "cpu", "linear2": 0}
168 else:
169 device_map = {"linear1": 0, "batchnorm": "cpu", "linear2": 1}
170
171 model = ModelForTest()
172 dispatch_model(model, device_map=device_map)
173 with assert_exception(ValueError, "You can't train a model that has been loaded with"):
174 model = accelerator.prepare_model(model)