Debian Codegraph @

tests/test_dataclasses.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 from unittest.mock import Mock, patch
16
17 import pytest
18
19 from accelerate.parallelism_config import ParallelismConfig
20 from accelerate.utils import patch_environment
21 from accelerate.utils.constants import (
22 BETA_CP_AVAILABLE_PYTORCH_VERSION,
23 BETA_SP_AVAILABLE_DEEPSPEED_VERSION,
24 BETA_TP_AVAILABLE_PYTORCH_VERSION,
25 BETA_TP_AVAILABLE_TRANSFORMERS_VERSION,
26 )
27 from accelerate.utils.imports import is_deepspeed_available, is_transformers_available
28 from accelerate.utils.versions import compare_versions, is_torch_version
29
30
31 def _should_skip_cp_test(cp_size):
32 """Check if CP test should be skipped based on cp_size and torch version."""
33 return cp_size > 1 and not is_torch_version(">=", BETA_CP_AVAILABLE_PYTORCH_VERSION)
34
35
36 def _should_skip_sp_test(sp_size):
37 """Check if SP test should be skipped based on sp_size and deepspeed version."""
38 if sp_size <= 1:
39 return False
40 if not is_deepspeed_available():
41 return True
42 return not compare_versions("deepspeed", ">=", BETA_SP_AVAILABLE_DEEPSPEED_VERSION)
43
44
45 def _should_skip_tp_test(tp_size):
46 """Check if TP test should be skipped based on tp_size, torch version, and transformers availability."""
47 if tp_size <= 1:
48 return False
49
50 if not is_torch_version(">=", BETA_TP_AVAILABLE_PYTORCH_VERSION):
51 return True
52
53 if not is_transformers_available():
54 return True
55
56 if not compare_versions("transformers", ">=", BETA_TP_AVAILABLE_TRANSFORMERS_VERSION):
57 return True
58
59 return False
60
61
62 class TestParallelismConfig:
63 @pytest.fixture(autouse=True)
64 def mock_init_device_mesh(self):
65 def mock_init_mesh(device_type, mesh_shape, mesh_dim_names):
66 mesh = Mock()
67 mesh.size.return_value = 1
68 for dim in mesh_shape:
69 mesh.size.return_value *= dim
70 mesh.shape = mesh_shape
71 mesh.mesh_dim_names = mesh_dim_names
72
73 # mock device_mesh._flatten
74 mesh.flattened_dims = []
75
76 def mock_getitem(key):
77 submesh = Mock()
78
79 def mock_flatten(name):
80 mesh.flattened_dims.append((key, name))
81
82 submesh._flatten = Mock(side_effect=mock_flatten)
83 return submesh
84
85 mesh.__getitem__ = Mock(side_effect=mock_getitem)
86
87 return mesh
88
89 with patch("torch.distributed.device_mesh.init_device_mesh", side_effect=mock_init_mesh):
90 yield mock_init_mesh
91
92 @pytest.mark.parametrize(
93 "dp_replicate_size, dp_shard_size, tp_size, cp_size, expected_shape, expected_dim_names",
94 [
95 (8, 1, 1, 1, (8,), ("dp_replicate",)), # DDP
96 (1, 8, 1, 1, (8,), ("dp_shard",)), # FSDP
97 (2, 4, 1, 1, (2, 4), ("dp_replicate", "dp_shard")), # HSDP
98 (1, 4, 2, 1, (4, 2), ("dp_shard", "tp")), # FSDP + TP
99 (2, 2, 2, 1, (2, 2, 2), ("dp_replicate", "dp_shard", "tp")), # HSDP + TP
100 (1, 1, 8, 1, (8,), ("tp",)), # TP only
101 (1, 1, 1, 4, (4,), ("cp",)), # CP only
102 (1, 4, 1, 2, (4, 2), ("dp_shard", "cp")), # FSDP + CP
103 (1, 2, 2, 2, (2, 2, 2), ("dp_shard", "cp", "tp")), # FSDP + CP + TP
104 (2, 2, 2, 2, (2, 2, 2, 2), ("dp_replicate", "dp_shard", "cp", "tp")), # HSDP + CP + TP
105 ],
106 )
107 def test_get_mesh(
108 self,
109 dp_replicate_size,
110 dp_shard_size,
111 tp_size,
112 cp_size,
113 expected_shape,
114 expected_dim_names,
115 ):
116 # Skip tests based on version requirements
117 if _should_skip_cp_test(cp_size):
118 pytest.skip(f"tests with `cp_size>1` require torch >= {BETA_CP_AVAILABLE_PYTORCH_VERSION}")
119 if _should_skip_tp_test(tp_size):
120 pytest.skip(
121 f"tests with `tp_size>1` require torch >= {BETA_TP_AVAILABLE_PYTORCH_VERSION}, transformers available and >= {BETA_TP_AVAILABLE_TRANSFORMERS_VERSION}"
122 )
123
124 config = ParallelismConfig(
125 dp_replicate_size=dp_replicate_size, dp_shard_size=dp_shard_size, tp_size=tp_size, cp_size=cp_size
126 )
127 mesh_dim_names, mesh_shape = config._get_mesh()
128 assert mesh_shape == expected_shape
129 assert mesh_dim_names == expected_dim_names
130
131 @pytest.mark.parametrize(
132 "dp_replicate_size, dp_shard_size, tp_size, cp_size, expected_shape, expected_dim_names",
133 [
134 (8, 1, 1, 1, (8,), ("dp_replicate",)),
135 (1, 8, 1, 1, (8,), ("dp_shard",)),
136 (2, 4, 1, 1, (2, 4), ("dp_replicate", "dp_shard")),
137 (1, 4, 2, 1, (4, 2), ("dp_shard", "tp")),
138 (2, 2, 2, 1, (2, 2, 2), ("dp_replicate", "dp_shard", "tp")),
139 (1, 1, 8, 1, (8,), ("tp",)),
140 (1, 1, 1, 4, (4,), ("cp",)),
141 (1, 4, 1, 2, (4, 2), ("dp_shard", "cp")),
142 (1, 2, 2, 2, (2, 2, 2), ("dp_shard", "cp", "tp")),
143 (2, 2, 2, 2, (2, 2, 2, 2), ("dp_replicate", "dp_shard", "cp", "tp")),
144 ],
145 )
146 def test_build_device_mesh(
147 self,
148 dp_replicate_size,
149 dp_shard_size,
150 tp_size,
151 cp_size,
152 expected_shape,
153 expected_dim_names,
154 ):
155 """Test build_device_mesh creates correct mesh and applies flattening."""
156 # Skip tests based on version requirements
157 if _should_skip_cp_test(cp_size):
158 pytest.skip(f"tests with `cp_size>1` require torch >= {BETA_CP_AVAILABLE_PYTORCH_VERSION}")
159 if _should_skip_tp_test(tp_size):
160 pytest.skip(
161 f"tests with `tp_size>1` require torch >= {BETA_TP_AVAILABLE_PYTORCH_VERSION}, transformers available and >= {BETA_TP_AVAILABLE_TRANSFORMERS_VERSION}"
162 )
163
164 config = ParallelismConfig(
165 dp_replicate_size=dp_replicate_size, dp_shard_size=dp_shard_size, tp_size=tp_size, cp_size=cp_size
166 )
167 device_mesh = config.build_device_mesh("cpu")
168
169 # Check mesh shape and dimension names match expected
170 assert device_mesh.shape == expected_shape
171 assert device_mesh.mesh_dim_names == expected_dim_names
172
173 # Check that correct flattening operations were called
174 expected_flattened = []
175 if config.dp_dim_names:
176 expected_flattened.append((config.dp_dim_names, "dp"))
177 if config.dp_shard_cp_dim_names:
178 expected_flattened.append((config.dp_shard_cp_dim_names, "dp_shard_cp"))
179 if config.dp_cp_dim_names:
180 expected_flattened.append((config.dp_cp_dim_names, "dp_cp"))
181
182 assert device_mesh.flattened_dims == expected_flattened
183
184 @pytest.mark.parametrize(
185 "dp_replicate_size, dp_shard_size, tp_size, cp_size",
186 [
187 (8, 1, 1, 1),
188 (1, 8, 1, 1),
189 (2, 4, 1, 1),
190 (1, 4, 2, 1),
191 (2, 2, 2, 1),
192 (1, 1, 8, 1),
193 (1, 1, 1, 4),
194 (1, 4, 1, 2),
195 (1, 2, 2, 2),
196 (2, 2, 2, 2),
197 ],
198 )
199 def test_from_env(
200 self,
201 dp_replicate_size,
202 dp_shard_size,
203 tp_size,
204 cp_size,
205 ):
206 if _should_skip_cp_test(cp_size):
207 pytest.skip(f"tests with `cp_size>1` require torch >= {BETA_CP_AVAILABLE_PYTORCH_VERSION}")
208 if _should_skip_tp_test(tp_size):
209 pytest.skip(
210 f"tests with `tp_size>1` require torch >= {BETA_TP_AVAILABLE_PYTORCH_VERSION}, transformers available and >= {BETA_TP_AVAILABLE_TRANSFORMERS_VERSION}"
211 )
212
213 new_env = {
214 "PARALLELISM_CONFIG_DP_REPLICATE_SIZE": dp_replicate_size,
215 "PARALLELISM_CONFIG_DP_SHARD_SIZE": dp_shard_size,
216 "PARALLELISM_CONFIG_TP_SIZE": tp_size,
217 "PARALLELISM_CONFIG_CP_SIZE": cp_size,
218 }
219
220 with patch_environment(**new_env):
221 config = ParallelismConfig()
222 for key, value in new_env.items():
223 assert getattr(config, key.split("PARALLELISM_CONFIG_")[-1].lower()) == value
224
225 def test_cp_torch_handler(self):
226 """Test CP Torch/FSDP2 handler with various configurations."""
227
228 # Any cp_size > 1 requires torch >= BETA_CP_AVAILABLE_PYTORCH_VERSION, we use placeholder for this check as this test doesn't depend on a specific size
229 if _should_skip_cp_test(2):
230 pytest.skip(f"tests with `cp_size>1` require torch >= {BETA_CP_AVAILABLE_PYTORCH_VERSION}")
231
232 from accelerate.utils import TorchContextParallelConfig
233
234 for setting in ("allgather", "alltoall"):
235 cp_handler = TorchContextParallelConfig(cp_comm_strategy=setting)
236 pc = ParallelismConfig(cp_size=2, cp_handler=cp_handler)
237
238 assert pc.cp_handler is not None, "CP handler should be set"
239 assert pc.cp_handler.cp_comm_strategy == setting, (
240 f"CP handler strategy should be {setting} but got {pc.cp_handler.cp_comm_strategy}"
241 )
242
243 for setting in ("allgather", "alltoall"):
244 with patch_environment(PARALLELISM_CONFIG_CP_COMM_STRATEGY=setting):
245 pc = ParallelismConfig(cp_size=2)
246 assert pc.cp_handler is not None, "CP handler should be set from environment"
247 assert pc.cp_handler.cp_comm_strategy == setting, (
248 f"CP handler strategy should be {setting} but got {pc.cp_handler.cp_comm_strategy}"
249 )
250
251 for setting in ("invalid", "unsupported"):
252 with pytest.raises(ValueError, match=f"Invalid cp_comm_strategy: {setting}"):
253 TorchContextParallelConfig(cp_comm_strategy=setting)
254
255 with patch_environment(PARALLELISM_CONFIG_CP_COMM_STRATEGY=setting):
256 with pytest.raises(ValueError, match=f"Invalid cp_comm_strategy: {setting}"):
257 pc = ParallelismConfig(cp_size=2)
258
259 def test_sp_deepspeed_handler(self):
260 """Test SP DeepSpeed/ALST/UlyssesSP handler with various configurations."""
261
262 # Any sp_size > 1 requires torch >= BETA_SP_AVAILABLE_PYTORCH_VERSION, we use placeholder for this check as this test doesn't depend on a specific size
263 if _should_skip_sp_test(2):
264 pytest.skip(f"tests with `sp_size>1` require deepspeed >= {BETA_SP_AVAILABLE_DEEPSPEED_VERSION}")
265
266 from accelerate.utils import DeepSpeedSequenceParallelConfig
267
268 sp_handler = DeepSpeedSequenceParallelConfig()
269 pc = ParallelismConfig(sp_backend="deepspeed", sp_size=2, sp_handler=sp_handler)
270 assert pc.sp_handler is not None, "SP handler should be set"
271 assert pc.sp_handler.sp_seq_length_is_variable is True, "by default we set to expect a variable seqlen"
272
273 with pytest.raises(ValueError, match="Invalid sp_attn_implementation"):
274 DeepSpeedSequenceParallelConfig(sp_attn_implementation="foobar")
275
276 def test_tp_handler(self):
277 assert True, "Tensor parallelism handler doesn't hold any logic yet"