-
Notifications
You must be signed in to change notification settings - Fork 128
Expand file tree
/
Copy pathtest_distributed_strategies.py
More file actions
300 lines (251 loc) · 11.1 KB
/
test_distributed_strategies.py
File metadata and controls
300 lines (251 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: LicenseRef-Apache2
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse
import logging
import os
import subprocess
import pytest
import torch
from transformers import DataCollatorForLanguageModeling
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
requires_multi_gpu = pytest.mark.skipif(
not torch.cuda.is_available() or torch.cuda.device_count() < 2,
reason="Test requires at least 2 GPUs",
)
@pytest.mark.parametrize(
"strategy",
[
"fsdp2",
pytest.param(
"mfsdp", marks=pytest.mark.xfail(reason="BIO-146: mFSDP currently failing on latest torch container.")
),
],
)
@pytest.mark.parametrize("backend", ["te", "eager"])
def test_ddp_vs_fsdp_single_gpu(strategy, backend, unused_tcp_port):
cmd = [
"torchrun",
"--nproc_per_node=1",
"--rdzv-backend=c10d",
f"--rdzv-endpoint=localhost:{unused_tcp_port}",
os.path.relpath(__file__),
"--strategy",
strategy,
]
if backend == "te":
cmd.append("--test_te")
result = subprocess.run(
cmd,
check=False,
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
timeout=240,
)
if result.returncode != 0:
print(f"STDOUT:\n{result.stdout}")
print(f"STDERR:\n{result.stderr}")
pytest.fail(f"Command failed with exit code {result.returncode}")
@requires_multi_gpu
@pytest.mark.parametrize("strategy", ["fsdp2", pytest.param("mfsdp", marks=pytest.mark.xfail(reason="BIONEMO-2726"))])
@pytest.mark.parametrize("backend", ["te", "eager"])
def test_ddp_vs_fsdp_multi_gpu(strategy, backend, unused_tcp_port):
cmd = [
"torchrun",
"--nproc_per_node=2",
"--rdzv-backend=c10d",
f"--rdzv-endpoint=localhost:{unused_tcp_port}",
os.path.relpath(__file__),
"--strategy",
strategy,
]
if backend == "te":
cmd.append("--test_te")
result = subprocess.run(
cmd,
check=False,
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
timeout=240,
)
if result.returncode != 0:
print(f"STDOUT:\n{result.stdout}")
print(f"STDERR:\n{result.stderr}")
pytest.fail(f"Command failed with exit code {result.returncode}")
if __name__ == "__main__":
import argparse
import enum
import sys
from dataclasses import dataclass, field
from pathlib import Path
# Ensure the model directory is on sys.path for bare module imports.
sys.path.insert(0, Path(__file__).resolve().parent.parent.as_posix())
import torch.distributed as dist
import transformer_engine.pytorch
import transformers
from megatron_fsdp.fully_shard import fully_shard as megatron_fsdp_fully_shard
from torch.distributed.device_mesh import init_device_mesh
from torch.distributed.fsdp import fully_shard
from torch.optim import AdamW
from transformers import AutoModelForMaskedLM, AutoTokenizer
class Strategy(enum.StrEnum):
DDP = "ddp"
FSDP2 = "fsdp2"
MFSDP = "mfsdp"
parser = argparse.ArgumentParser()
parser.add_argument("--test_te", action="store_true", default=False)
parser.add_argument("--strategy", type=Strategy, default=Strategy.FSDP2, choices=[Strategy.FSDP2, Strategy.MFSDP])
args = parser.parse_args()
tokenizer = AutoTokenizer.from_pretrained("facebook/esm2_t6_8M_UR50D")
test_proteins = [
"MLSATEKLSDYISSLFASVSIINSISTEDLFFLKLTCQTFSKDSEEYKAAYRILRGVQRGKVQIIEEALVS",
"MFVFFAGTLVNQDTLNFRDQLNINVVGTVRGIAQDASKYLEYAIDSV",
"MAATGSLILSDEEQAELIALAVRIVLACAGGSQNKELAAQLGVIETTVGEWRRRFAQNRVEGLRDEARPGAPSDDQ",
"MSAVLSAVASDDWTAFAKLVHPYVHWTADGITTRGRTRVMARLSGHDGVKPASSYELRDGQVYRWTS",
"MSDPAAEPPADTSGIAWRKSSYSGPNGNCVELAQISGDHVGIRNSRDLHGSVLTCTRAEFAALLCDIKAGRFDSLIL",
"MRRPKLRRSGVLMSHPARGQPIKDASTEAAAERRPHVTSSERQDVSDQDTR",
"MQTITVAGGNLFQIAAQYLGDATQWIRIAQLNGLADPVLSGVVTLTIPQPNPLAGGGVVGQ",
"MVFSLEQFVRGQGWQSITSNSDNEVPKPRQVYEVKAVCHPGAWRVKARVFGTSQGIPFDYSQASMERRVAQDECDRRPQ",
"AGDGTGCNPTLSKAAGVELDNSDSGEVFVIYLHIIIAIIVLISINLIGFLYF",
"MKVGVDPSVCEAHGACMSILPEVFDLDDDEVLQIRDGELAPSEEESAERAVASCPMGALRLSR",
"MWISERPPSRMALGSQSQMSLPGIPARCLHS",
"MIDNSIRLFDADDSELFSLAEVPLDNKPIQRDTDSLSQWGDTWLREIQHS",
"MVKNLFFNKIKNATLKVANISRCYLPFPPPPCPPPEPLEPPEPPAPLEPAPDPPPLPPFPVPDILPAI",
"MSYINDITQSNSSILNVNVKINDHNSDEMYRNETKWYGEQFRYQSNPRFSRSSTSKNEKGFVQKKT",
"MQILILPIPDQLQNPNKISQHLICITFVSEQTLPI",
]
data_collator = DataCollatorForLanguageModeling(
tokenizer=tokenizer,
mlm_probability=0.15,
pad_to_multiple_of=1024,
seed=42,
)
input_data = data_collator([tokenizer(p, truncation=True, max_length=1024) for p in test_proteins])
@dataclass
class DistributedConfig:
"""Class to track distributed ranks."""
rank: int = field(default_factory=dist.get_rank)
local_rank: int = field(default_factory=lambda: int(os.environ["LOCAL_RANK"]))
world_size: int = field(default_factory=dist.get_world_size)
def is_main_process(self) -> bool:
"""This is the global rank 0 process, to be used for wandb logging, etc."""
return self.rank == 0
def run_forward_backward(use_te: bool, strategy: Strategy, input_data: dict, dist_config: DistributedConfig):
# Set seed for reproducible model initialization across strategies
torch.manual_seed(42)
torch.cuda.manual_seed_all(42)
device_mesh = init_device_mesh(
"cuda",
mesh_shape=(dist_config.world_size, 1),
mesh_dim_names=("dp", "tp"), # mfsdp requires us to give a tp mesh dimension.
)
device = f"cuda:{dist_config.local_rank}"
if use_te:
# Import local model classes to avoid using outdated code from HF Hub
from modeling_esm_te import NVEsmConfig, NVEsmForMaskedLM
config = NVEsmConfig.from_pretrained(
"facebook/esm2_t6_8M_UR50D",
dtype=torch.bfloat16,
revision="c731040f",
)
model = NVEsmForMaskedLM(config)
transformer_layers = model.model.encoder.layers
else:
model = AutoModelForMaskedLM.from_pretrained(
"facebook/esm2_t6_8M_UR50D",
dtype=torch.bfloat16,
)
transformer_layers = model.esm.encoder.layer
del model.esm.contact_head # Unused in backwards pass.
if strategy is Strategy.FSDP2:
for layer in transformer_layers:
fully_shard(layer, mesh=device_mesh["dp"])
fully_shard(model, mesh=device_mesh["dp"])
model.to(device)
elif strategy is Strategy.DDP:
model.to(device)
model = torch.nn.parallel.DistributedDataParallel(
model,
device_ids=[dist_config.local_rank],
output_device=dist_config.local_rank,
device_mesh=device_mesh["dp"],
)
optimizer = AdamW(model.parameters())
if strategy is Strategy.MFSDP:
model, optimizer = megatron_fsdp_fully_shard(
module=model,
optimizer=optimizer,
fsdp_unit_modules=[
transformer_engine.pytorch.TransformerLayer,
transformer_engine.pytorch.LayerNorm,
transformer_engine.pytorch.LayerNormLinear,
transformers.models.esm.modeling_esm.EsmLayer,
],
device_mesh=device_mesh,
dp_shard_dim="dp",
tp_dim="tp",
sync_model_each_microbatch=True,
preserve_fp32_weights=False, # TODO: cory, any idea why this is needed?
)
model.train()
input_data = {k: v.to(device) for k, v in input_data.items()}
optimizer.zero_grad()
outputs = model(**input_data)
outputs.loss.backward()
# get gradients
if strategy is Strategy.FSDP2:
grads = {name: p.grad.full_tensor() for name, p in model.named_parameters() if p.grad is not None}
elif strategy is Strategy.DDP:
grads = {name: p.grad for name, p in model.module.named_parameters() if p.grad is not None}
elif strategy is Strategy.MFSDP:
# Because of uneven sharding, we need to manually gather the gradients.
sharded_grads = [(name, p.grad) for name, p in model.module.named_parameters()]
grads = {}
for name, grad in sharded_grads:
grad_shards = [None] * device_mesh["dp"].size()
# For FSDP, we are not strided sharding, so gathering across dp_shard_cp is sufficient.
# For HSDP, we need to first gather across dp_shard_cp, then gather across dp_inter,
# not the other way around or you'll get wrong zig-zags.
torch.distributed.all_gather_object(grad_shards, grad, group=device_mesh["dp"].get_group())
all_valid_shards = [shard for shard in grad_shards if shard is not None]
# Megatron-FSDP is always sharded across dim=0.
grads[name] = torch.cat([s.to_local().to(device) for s in all_valid_shards], dim=0)
del model
torch.cuda.empty_cache()
return outputs, grads
dist.init_process_group(backend="nccl")
dist_config = DistributedConfig()
logger.info(f"Distributed config: {dist_config}")
torch.cuda.set_device(dist_config.local_rank)
ddp, ddp_grads = run_forward_backward(
use_te=args.test_te, strategy=Strategy.DDP, input_data=input_data, dist_config=dist_config
)
fsdp, fsdp_grads = run_forward_backward(
use_te=args.test_te, strategy=args.strategy, input_data=input_data, dist_config=dist_config
)
torch.testing.assert_close(fsdp.loss, ddp.loss, msg=lambda x: f"Loss mismatch: {x}")
torch.testing.assert_close(fsdp.logits, ddp.logits, msg=lambda x: f"Logits mismatch: {x}")
shared_grads = set(ddp_grads) & set(fsdp_grads)
missing_grads = set(ddp_grads) ^ set(fsdp_grads)
assert not missing_grads, f"Missing gradients: {missing_grads}"
for name in shared_grads:
ddp_grad = ddp_grads[name]
fsdp_grad = fsdp_grads[name]
torch.testing.assert_close(ddp_grad, fsdp_grad, msg=lambda x: f"Gradient mismatch for {name}: {x}")
# Check that the gradients are different when the last dimension is shuffled
assert not torch.allclose(ddp_grad, torch.roll(fsdp_grad, -1, -1))
dist.destroy_process_group()