Debian Codegraph @

tests/test_load_checkpoint_and_dispatch_with_broadcast.py

raw
1 # Copyright 2024 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 argparse
16 import functools
17 import itertools
18 import unittest
19 from typing import Any, Callable
20
21 import torch
22 from huggingface_hub import hf_hub_download
23 from torch import distributed as dist
24 from torch import nn
25 from torch.distributed._composable.fsdp import fully_shard
26 from torch.distributed._tensor import DTensor
27 from torch.distributed.device_mesh import init_device_mesh
28 from torch.distributed.fsdp.wrap import _recursive_wrap, transformer_auto_wrap_policy
29 from torch.nn.parallel import DistributedDataParallel
30
31 from accelerate import init_empty_weights, load_checkpoint_and_dispatch
32 from accelerate.test_utils import (
33 execute_subprocess_async,
34 get_torch_dist_unique_port,
35 require_multi_device,
36 run_first,
37 torch_device,
38 )
39 from accelerate.test_utils.testing import require_torch_min_version, require_transformers
40 from accelerate.utils.imports import is_hpu_available, is_transformers_available
41
42
43 if is_transformers_available():
44 from transformers import AutoConfig, AutoModel
45
46
47 def manage_process_group(func: Callable[..., Any]) -> Callable[..., Any]:
48 """Manage the creation and destruction of the distributed process group for the wrapped function."""
49
50 def wrapped(*args: Any, **kwargs: Any) -> Any:
51 torch_accelerator_module = getattr(torch, torch_device, torch.cuda)
52 initialized_here = False
53 if not dist.is_initialized():
54 if torch_device == "hpu" and is_hpu_available(init_hccl=True):
55 dist.init_process_group(backend="hccl", world_size=torch_accelerator_module.device_count())
56 elif torch_device == "xpu":
57 dist.init_process_group(
58 backend="cpu:gloo,xpu:xccl", world_size=torch_accelerator_module.device_count()
59 )
60 else:
61 dist.init_process_group(world_size=torch_accelerator_module.device_count())
62 initialized_here = True
63 try:
64 return func(*args, **kwargs)
65 finally:
66 if initialized_here:
67 dist.destroy_process_group()
68
69 return wrapped
70
71
72 @manage_process_group
73 def load_checkpoint_and_dispatch_fsdp2():
74 torch_accelerator_module = getattr(torch, torch_device, torch.cuda)
75 torch_accelerator_module.set_device(device := torch.device(dist.get_rank()))
76
77 pretrained_model_name_or_path = "bigscience/bloom-560m"
78 model_path = hf_hub_download("bigscience/bloom-560m", "pytorch_model.bin")
79
80 model = AutoModel.from_pretrained(pretrained_model_name_or_path, device_map=device, torch_dtype=torch.float32)
81 assert isinstance(model, nn.Module)
82
83 with init_empty_weights():
84 config = AutoConfig.from_pretrained(pretrained_model_name_or_path)
85 fsdp2_model = AutoModel.from_config(config)
86 fsdp2_model.tie_weights()
87 assert isinstance(fsdp2_model, nn.Module)
88
89 from transformers.models.gpt2.modeling_gpt2 import GPT2Block
90
91 mesh = init_device_mesh(device.type, (dist.get_world_size(),))
92 fsdp2_model, _ = _recursive_wrap(
93 fsdp2_model,
94 auto_wrap_policy=functools.partial(
95 transformer_auto_wrap_policy,
96 transformer_layer_cls={
97 GPT2Block,
98 type(fsdp2_model),
99 },
100 ),
101 wrapper_cls=functools.partial(
102 fully_shard,
103 mesh=mesh,
104 ),
105 ignored_modules=set(),
106 ignored_params=set(),
107 )
108
109 fsdp2_model._apply(
110 lambda t: torch.empty_like(t, device=device) if t.device == torch.device("meta") else t.to(device)
111 )
112
113 load_checkpoint_and_dispatch(fsdp2_model, model_path, strict=True, broadcast_from_rank0=True)
114
115 for (name, tensor), (fsdp2_name, fsdp2_tensor) in zip(
116 itertools.chain(model.named_parameters(), model.named_buffers()),
117 itertools.chain(fsdp2_model.named_parameters(), fsdp2_model.named_buffers()),
118 ):
119 assert name == fsdp2_name
120 assert isinstance(fsdp2_tensor, DTensor), fsdp2_name
121 torch.testing.assert_close(tensor, fsdp2_tensor.full_tensor(), msg=fsdp2_name)
122
123
124 @manage_process_group
125 def load_checkpoint_and_dispatch_no_broadcast_from_rank0():
126 torch_accelerator_module = getattr(torch, torch_device, torch.cuda)
127 torch_accelerator_module.set_device(device := torch.device(dist.get_rank()))
128
129 pretrained_model_name_or_path = "bigscience/bloom-560m"
130 model_path = hf_hub_download("bigscience/bloom-560m", "pytorch_model.bin")
131
132 with init_empty_weights():
133 config = AutoConfig.from_pretrained(pretrained_model_name_or_path)
134 broadcasted_model = AutoModel.from_config(config)
135 broadcasted_model.tie_weights()
136 assert isinstance(broadcasted_model, nn.Module)
137
138 broadcasted_model._apply(
139 lambda t: torch.empty_like(t, device=device) if t.device == torch.device("meta") else t.to(device)
140 )
141
142 load_checkpoint_and_dispatch(broadcasted_model, model_path, strict=True, broadcast_from_rank0=True)
143
144 with init_empty_weights():
145 config = AutoConfig.from_pretrained(pretrained_model_name_or_path)
146 non_broadcasted_model = AutoModel.from_config(config)
147 non_broadcasted_model.tie_weights()
148 assert isinstance(non_broadcasted_model, nn.Module)
149
150 non_broadcasted_model._apply(
151 lambda t: torch.empty_like(t, device=device) if t.device == torch.device("meta") else t.to(device)
152 )
153
154 load_checkpoint_and_dispatch(non_broadcasted_model, model_path, strict=True, broadcast_from_rank0=False)
155
156 for (broadcasted_name, broadcasted_tensor), (non_broadcasted_name, non_broadcasted_tensor) in zip(
157 itertools.chain(broadcasted_model.named_parameters(), broadcasted_model.named_buffers()),
158 itertools.chain(non_broadcasted_model.named_parameters(), non_broadcasted_model.named_buffers()),
159 ):
160 assert broadcasted_name == non_broadcasted_name
161 torch.testing.assert_close(broadcasted_tensor, non_broadcasted_tensor, msg=broadcasted_name)
162
163
164 @manage_process_group
165 def load_checkpoint_and_dispatch_ddp():
166 torch_accelerator_module = getattr(torch, torch_device, torch.cuda)
167 torch_accelerator_module.set_device(device := torch.device(dist.get_rank()))
168
169 pretrained_model_name_or_path = "bigscience/bloom-560m"
170 model_path = hf_hub_download("bigscience/bloom-560m", "pytorch_model.bin")
171
172 model = AutoModel.from_pretrained(pretrained_model_name_or_path, device_map=device, torch_dtype=torch.float32)
173 assert isinstance(model, nn.Module)
174
175 with init_empty_weights():
176 config = AutoConfig.from_pretrained(pretrained_model_name_or_path)
177 ddp_model = AutoModel.from_config(config)
178 ddp_model.tie_weights()
179 assert isinstance(ddp_model, nn.Module)
180
181 ddp_model._apply(
182 lambda t: torch.empty_like(t, device=device) if t.device == torch.device("meta") else t.to(device)
183 )
184 ddp_model = DistributedDataParallel(ddp_model)
185
186 load_checkpoint_and_dispatch(ddp_model.module, model_path, strict=True, broadcast_from_rank0=True)
187
188 for (name, tensor), (ddp_name, ddp_tensor) in zip(
189 itertools.chain(model.named_parameters(), model.named_buffers()),
190 itertools.chain(ddp_model.module.named_parameters(), ddp_model.module.named_buffers()),
191 ):
192 assert name == ddp_name
193 torch.testing.assert_close(tensor, ddp_tensor, msg=ddp_name)
194
195
196 @require_torch_min_version(version="2.4.0")
197 @require_transformers
198 @require_multi_device
199 @run_first
200 class TestLoadCheckpointAndDispatchWithBroadcast(unittest.TestCase):
201 def setUp(self):
202 self.torch_accelerator_module = getattr(torch, torch_device, torch.cuda)
203
204 def test_load_checkpoint_and_dispatch_fsdp2(self):
205 execute_subprocess_async(
206 cmd=[
207 "torchrun",
208 f"--nproc_per_node={self.torch_accelerator_module.device_count()}",
209 f"--master_port={get_torch_dist_unique_port()}",
210 __file__,
211 "--fsdp2",
212 ],
213 )
214 # successful return here == success - any errors would have caused an error in the sub-call
215
216 def test_load_checkpoint_and_dispatch_no_broadcast_from_rank0(self):
217 execute_subprocess_async(
218 cmd=[
219 "torchrun",
220 f"--nproc_per_node={self.torch_accelerator_module.device_count()}",
221 f"--master_port={get_torch_dist_unique_port()}",
222 __file__,
223 "--no_broadcast_from_rank0",
224 ],
225 )
226 # successful return here == success - any errors would have caused an error in the sub-call
227
228 def test_load_checkpoint_and_dispatch_ddp(self):
229 execute_subprocess_async(
230 cmd=[
231 "torchrun",
232 f"--nproc_per_node={self.torch_accelerator_module.device_count()}",
233 f"--master_port={get_torch_dist_unique_port()}",
234 __file__,
235 "--ddp",
236 ],
237 )
238 # successful return here == success - any errors would have caused an error in the sub-call
239
240
241 if __name__ == "__main__":
242 # The script below is meant to be run under torch.distributed, on a machine with multiple GPUs:
243 #
244 # PYTHONPATH="src" python -m torch.distributed.run --nproc_per_node 2 --output_dir output_dir ./tests/test_fsdp2.py --fsdp2
245
246 class CLIArgs(argparse.Namespace):
247 fsdp2: bool
248 ddp: bool
249 no_broadcast_from_rank0: bool
250
251 parser = argparse.ArgumentParser()
252 group = parser.add_mutually_exclusive_group()
253 group.add_argument("--fsdp2", action="store_true")
254 group.add_argument("--ddp", action="store_true")
255 group.add_argument("--no_broadcast_from_rank0", action="store_true")
256 args = parser.parse_args(namespace=CLIArgs())
257
258 if args.fsdp2:
259 load_checkpoint_and_dispatch_fsdp2()
260 elif args.ddp:
261 load_checkpoint_and_dispatch_ddp()
262 elif args.no_broadcast_from_rank0:
263 load_checkpoint_and_dispatch_no_broadcast_from_rank0()
264 else:
265 raise ValueError("Missing test selection")