Skip to content

Commit 3577b6f

Browse files
authored
Save replicated items on all shards (#1247)
1 parent 84e1f64 commit 3577b6f

2 files changed

Lines changed: 9 additions & 36 deletions

File tree

src/fairseq2/nn/data_parallel/_fsdp1.py

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@
1313
from typing import TypeAlias
1414

1515
import torch
16-
import torch.distributed as dist
1716
from torch import Tensor
1817
from torch.distributed import ProcessGroup
1918
from torch.distributed._shard.sharded_tensor import ShardedTensor
@@ -209,22 +208,17 @@ def fsdp1_local_state_dict(module: FSDP1) -> dict[str, object]:
209208
action="ignore", message=r".*Please use DTensor instead.*"
210209
)
211210

212-
sdp_rank = dist.get_rank(module.process_group)
213-
214211
for name, item in module.state_dict().items():
215212
if isinstance(item, ShardedTensor):
216213
local_shards = item.local_shards()
217214
if not local_shards:
218215
continue # means the tensor is sharded unevenly.
219216

220-
state_dict[name] = item.local_tensor().detach()
221-
# Save replicated items only on the first intra-node (i.e. sharded)
222-
# gang.
223-
elif sdp_rank == 0:
224-
if isinstance(item, Tensor):
225-
item = item.detach()
217+
item = item.local_tensor().detach()
218+
elif isinstance(item, Tensor):
219+
item = item.detach()
226220

227-
state_dict[name] = item
221+
state_dict[name] = item
228222

229223
return state_dict
230224

src/fairseq2/nn/data_parallel/_fsdp2.py

Lines changed: 5 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -195,36 +195,15 @@ def wrap(module: Module, reshard_after_forward: bool | None = None) -> FSDP2:
195195
def fsdp2_local_state_dict(module: FSDP2) -> dict[str, object]:
196196
sharded_state_dict = module.state_dict()
197197

198-
device_mesh = None
199-
200-
for value in sharded_state_dict.values():
201-
if isinstance(value, DTensor):
202-
device_mesh = value.device_mesh
203-
204-
break
205-
206-
if device_mesh is not None:
207-
try:
208-
sdp_rank = device_mesh.get_local_rank(mesh_dim="intra")
209-
except KeyError:
210-
raise ValueError(
211-
"The device mesh of `module` does not have a dimension named 'intra'."
212-
) from None
213-
else:
214-
sdp_rank = 0
215-
216198
state_dict: dict[str, object] = {}
217199

218200
for key, value in sharded_state_dict.items():
219201
if isinstance(value, DTensor):
220-
state_dict[key] = cast(DTensor, value.detach()).to_local()
221-
# Save replicated items only on the first intra-node (i.e. sharded)
222-
# gang.
223-
elif sdp_rank == 0:
224-
if isinstance(value, Tensor):
225-
value = value.detach()
226-
227-
state_dict[key] = value
202+
value = cast(DTensor, value.detach()).to_local()
203+
elif isinstance(value, Tensor):
204+
value = value.detach()
205+
206+
state_dict[key] = value
228207

229208
return state_dict
230209

0 commit comments

Comments
 (0)