Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions deepspeed/runtime/zero/parameter_offload.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from deepspeed.runtime.zero.partition_parameters import *
from deepspeed.runtime.zero.partitioned_param_coordinator import PartitionedParameterCoordinator, InflightParamRegistry, iter_params
from deepspeed.accelerator import get_accelerator
from deepspeed import comm as dist
from deepspeed import utils
from deepspeed.utils.pin_memory_tracker import pinned_memory_summary

Expand Down Expand Up @@ -221,6 +222,7 @@ def __init__(
zero_quantized_nontrainable_weights=self.zero_quantized_nontrainable_weights,
fast_sharding_for_leaf_module=self.fast_sharding_for_leaf_module,
log_trace_cache_warnings=self.log_trace_cache_warnings,
process_group=self._trace_group(module),
)

self.forward_hooks = []
Expand Down Expand Up @@ -255,6 +257,24 @@ def get_param_coordinator(self):
def empty_partition_cache(self):
self.partition_all_parameters()

@staticmethod
def _trace_group(module):
"""The ranks whose parameter traces must agree: the parameters' partition group when they all share one,
``None`` (the world) otherwise or when that group is the world. The coordinator gathers the parameters over
their partition group (or, with hpZ, a subgroup of it), so this covers every rank a gather involves. It is
not the optimizer's data-parallel group: a model partitioned by ``zero.Init`` before AutoTP keeps the world
as its partition group while the optimizer works over a smaller one."""
found = {} # id(group) -> (group, its global ranks)
for param in module.parameters():
group = getattr(param, "ds_process_group", None)
if group is not None and id(group) not in found:
size = dist.get_world_size(group=group)
found[id(group)] = (group, tuple(dist.get_global_rank(group, i) for i in range(size)))
if len({ranks for _, ranks in found.values()}) != 1:
return None
group, ranks = next(iter(found.values()))
return None if len(ranks) == dist.get_world_size() else group

def _convert_to_zero_parameters(self, ds_config, module, mpu):
non_zero_params = [p for p in module.parameters() if not is_zero_param(p)]
if non_zero_params:
Expand Down
4 changes: 2 additions & 2 deletions deepspeed/runtime/zero/partition_parameters.py
Original file line number Diff line number Diff line change
Expand Up @@ -1601,10 +1601,10 @@ def all_gather_coalesced(params: Iterable[Parameter],
# ensure that same list (with same ordering) of parameters are
# being allgathered across all ranks, otherwise could mix
# data between tensors.
assert_ints_same_as_other_ranks([p.ds_id for p in params])
assert_ints_same_as_other_ranks([p.ds_id for p in params], params[0].ds_process_group)
# ensure that tensors from each rank agree on the same ds_numel
# otherwise could mix data between tensors.
assert_ints_same_as_other_ranks([p.ds_tensor.ds_numel for p in params])
assert_ints_same_as_other_ranks([p.ds_tensor.ds_numel for p in params], params[0].ds_process_group)

if self.allgather_sequential or len(params) == 1:
return _all_gather_sequential(params, world_size, use_secondary_tensor, ds_process_group, quantize)
Expand Down
10 changes: 7 additions & 3 deletions deepspeed/runtime/zero/partitioned_param_coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,10 @@ def __init__(
zero_quantized_nontrainable_weights=False,
fast_sharding_for_leaf_module=False,
log_trace_cache_warnings=False,
process_group=None,
) -> None:
# the ranks whose traces must agree (the parameters' partition group; None: the world)
self.__process_group = process_group
# mapping of param -> handle for each param that is currently in flight
self.__inflight_param_registry = inflight_param_registry
# keeps track of the number of submodules invoked so far.
Expand Down Expand Up @@ -260,14 +263,15 @@ def reset_step(self) -> None:

if not self.is_complete_trace(): # not self.trace_complete:
# Make sure that recorded submodule orders are identical across ranks
assert_ints_same_as_other_ranks([m.ds_id for m in self.__submodule_order])
assert_ints_same_as_other_ranks([m.ds_id for m in self.__submodule_order], self.__process_group)

if self.is_record_trace():
# Successfully recorded a trace
self.construct_parameter_trace_from_module_trace()
# Make sure that recorded parameter orders are identical across ranks
assert_ints_same_as_other_ranks([p.param.ds_id for p in self.__param_order])
assert_ints_same_as_other_ranks([p.step_id_last_used_at for p in self.__param_order])
assert_ints_same_as_other_ranks([p.param.ds_id for p in self.__param_order], self.__process_group)
assert_ints_same_as_other_ranks([p.step_id_last_used_at for p in self.__param_order],
self.__process_group)

self.__submodule_order = tuple(self.__submodule_order) # freeze
self.__param_order = tuple(self.__param_order) # freeze
Expand Down
11 changes: 7 additions & 4 deletions deepspeed/runtime/zero/stage3.py
Original file line number Diff line number Diff line change
Expand Up @@ -771,7 +771,8 @@ def _setup_for_real_optimizer(self):
see_memory_usage("Before creating fp32 partitions", force=False)
self._create_fp32_partitions()
see_memory_usage("After creating fp32 partitions", force=False)
dist.barrier()
# Over the ranks of the partitions: a trainer on a subset of the world must not wait for the other ranks.
dist.barrier(group=self.dp_process_group)

# To support pipelined optimizer swapping
self._create_next_swappable_fp32_groups()
Expand All @@ -780,7 +781,7 @@ def _setup_for_real_optimizer(self):

self.initialize_optimizer_states()
see_memory_usage("After initializing optimizer states", force=False)
dist.barrier()
dist.barrier(group=self.dp_process_group)

if dist.get_rank() == 0:
logger.info("optimizer state initialized")
Expand Down Expand Up @@ -932,7 +933,7 @@ def _create_param_groups_fp16_flat_cpu_memory(self):
self.param_groups_fp16_flat_cpu_memory.append(torch.empty(1, dtype=self.dtype))

def _create_fp16_partitions_with_defragmentation(self, fp16_param_groups):
dist.barrier()
dist.barrier(group=self.dp_process_group)

param_groups: List[List[Parameter]] = tuple(
self._create_fp16_sub_groups(param_group["params"]) for param_group in fp16_param_groups)
Expand Down Expand Up @@ -1744,7 +1745,9 @@ def __reduce_and_partition_ipg_grads(self, communication_data_type: torch.dtype)

with get_accelerator().stream(self.reduce_and_partition_stream):
if self.enable_sanity_checks:
assert_ints_same_as_other_ranks([p.ds_id for p in params_in_bucket])
# over the ranks that reduce this bucket (its parameters' partition group, as the reduction below)
assert_ints_same_as_other_ranks([p.ds_id for p in params_in_bucket],
self._get_param_partition_group(params_in_bucket[0]))

if self.contiguous_gradients and bucket.elements <= self._ipg_bucket_capacity(
bucket) and not self.reduce_scatter:
Expand Down
26 changes: 16 additions & 10 deletions deepspeed/runtime/zero/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,50 +77,56 @@ def is_zero_supported_optimizer(optimizer):
return type(optimizer) in ZERO_SUPPORTED_OPTIMIZERS


def _first_rank(group):
"""Global rank of ``group``'s first rank (``group`` None: the world)."""
return 0 if group is None else dist.get_global_rank(group, 0)


@instrument_w_nvtx
def assert_lst_len_same_as_other_ranks(lst: List[int]) -> None:
def assert_lst_len_same_as_other_ranks(lst: List[int], group=None) -> None:
rank0_len_tensor = torch.tensor(
len(lst) if dist.get_rank() == 0 else -1,
len(lst) if dist.get_rank(group=group) == 0 else -1,
dtype=int,
device=torch.device(get_accelerator().device_name(os.environ["LOCAL_RANK"])),
requires_grad=False,
)
local_list_length = len(lst)
dist.broadcast(rank0_len_tensor, src=0, async_op=False)
dist.broadcast(rank0_len_tensor, src=_first_rank(group), group=group, async_op=False)
rank0_list_length = rank0_len_tensor.cpu().item()
if rank0_list_length != local_list_length:
raise RuntimeError(f"Detected a disagreement on list length between rank0 and rank{dist.get_rank()}: "
f"\n rank0: {rank0_list_length} "
f"\n rank{dist.get_rank()}: {local_list_length}")


def get_lst_from_rank0(lst: List[int]) -> None:
def get_lst_from_rank0(lst: List[int], group=None) -> None:
"""
NOTE: creates both communication and synchronization overhead so should be used
sparingly
"""
lst_tensor = torch.tensor(
lst if dist.get_rank() == 0 else [-1] * len(lst),
lst if dist.get_rank(group=group) == 0 else [-1] * len(lst),
dtype=int,
device=torch.device(get_accelerator().device_name(os.environ["LOCAL_RANK"])),
requires_grad=False,
)
dist.broadcast(lst_tensor, src=0, async_op=False)
dist.broadcast(lst_tensor, src=_first_rank(group), group=group, async_op=False)

return [t.item() for t in lst_tensor.cpu()]


@instrument_w_nvtx
def assert_ints_same_as_other_ranks(ints: List[int]) -> None:
def assert_ints_same_as_other_ranks(ints: List[int], group=None) -> None:
"""
NOTE: creates both communication and synchronization overhead so should be
used sparingly

takes a list of ints from each rank and ensures that they are the same
across ranks, throwing an exception if they are not.
across ranks, throwing an exception if they are not. ``group``: the ranks to compare (default: the world); a
ZeRO-3 model partitioned over a subgroup must pass its group, or the other ranks would have to take part.
"""
assert_lst_len_same_as_other_ranks(ints)
rank0_ints = get_lst_from_rank0(ints)
assert_lst_len_same_as_other_ranks(ints, group)
rank0_ints = get_lst_from_rank0(ints, group)
if ints != rank0_ints:
raise RuntimeError(f"Detected a disagreement on list contents between rank0 and rank{dist.get_rank()}: "
f"\n list length: {len(ints)}"
Expand Down
85 changes: 85 additions & 0 deletions tests/unit/v1/zero/test_zero.py
Original file line number Diff line number Diff line change
Expand Up @@ -2373,3 +2373,88 @@ def _storages_held_by_params(self, model):
if torch.is_tensor(value):
storages.add(value.untyped_storage().data_ptr())
return storages


class _SubgroupMPU:
"""An ``mpu`` whose data-parallel group is ``ranks``, a subset of the world, with no model parallelism."""

def __init__(self, ranks):
self.ranks = ranks
self.dp_group = dist.new_group(ranks)
# new_group is a collective over the world, so every rank creates every rank's own group.
own_groups = [dist.new_group([rank]) for rank in range(dist.get_world_size())]
self.mp_group = own_groups[dist.get_rank()]

def get_model_parallel_rank(self):
return 0

def get_model_parallel_world_size(self):
return 1

def get_data_parallel_rank(self):
return self.ranks.index(dist.get_rank())

def get_data_parallel_world_size(self):
return len(self.ranks)

def get_data_parallel_group(self):
return self.dp_group

def get_model_parallel_group(self):
return self.mp_group


class TestZero3OverSubgroup(DistributedTest):
world_size = 3

def test(self):
# ZeRO-3 over ranks 1-2 of a world of three; rank 0 holds no engine. A barrier or a rank-agreement check over
# the world would wait for rank 0, and one that broadcasts from global rank 0 would never get its data.
trainer_ranks = [1, 2]
mpu = _SubgroupMPU(trainer_ranks)
# Rank 0 waits for the trainers in a group of its own, so it cannot stand in for a world barrier of theirs.
everyone = dist.new_group(list(range(dist.get_world_size())))
try:
if dist.get_rank() in trainer_ranks:
self._train_like_plain_torch(mpu)
finally:
dist.barrier(group=everyone)

def _train_like_plain_torch(self, mpu):
# Oracle: the same model under plain torch SGD. Both trainer ranks see the same batch, so the gradient ZeRO
# averages over the subgroup is the reference's. SGD, because its update is linear in the gradient: Adam
# turns a rounding difference in a near-zero gradient into a difference of the size of the learning rate.
hidden_dim = 16
device = get_accelerator().current_device_name()
torch.manual_seed(1234)
model = SimpleModel(hidden_dim, nlayers=2)
reference = deepcopy(model).to(device)
reference_optimizer = torch.optim.SGD(reference.parameters(), lr=0.1)
config_dict = {
"train_micro_batch_size_per_gpu": 2,
"gradient_clipping": 0.0, # on by default; the reference does not clip
"zero_allow_untested_optimizer": True,
"zero_optimization": {
"stage": 3,
"stage3_param_persistence_threshold": 0
}
}
engine, _, _, _ = deepspeed.initialize(config=config_dict,
model=model,
model_parameters=model.parameters(),
optimizer=torch.optim.SGD(model.parameters(), lr=0.1),
mpu=mpu)
x = torch.randn(2, hidden_dim, generator=torch.Generator().manual_seed(7)).to(device)
y = torch.tensor([3, 5], device=device)
for _ in range(3):
loss = engine(x, y)
engine.backward(loss)
engine.step()
reference_optimizer.zero_grad()
reference(x, y).backward()
reference_optimizer.step()

for param, expected in zip(model.parameters(), reference.parameters()):
with deepspeed.zero.GatheredParameters([param]):
torch.testing.assert_close(param.data, expected.data, rtol=1e-4, atol=1e-6)
engine.destroy()
Loading