Skip to content
Closed
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
38 changes: 28 additions & 10 deletions hyper_parallel/core/fully_shard/param_group.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,14 @@ class AllGatherMetadata:
total_input_numel: int


def aligned_numel(numel, dtype):
"""Round each rank's wire payload to a multiple of 512 bytes."""
width = dtype.itemsize
assert 512 % width == 0
quantum = 512 // width
return ((numel + quantum - 1) // quantum) * quantum


@dataclass
class AllGatherResult:
"""Keep one all-gather input, output, and handle alive until copy-out."""
Expand Down Expand Up @@ -109,8 +117,8 @@ def init_flat_param_buffer(self, device: Optional[torch.device]) -> None:
self.flat_param_buffer = None
return

total_numel = sum(hsdp_param._sharded_param_data.numel() for hsdp_param in self.hsdp_params)
flat_param_buffer = torch.empty(total_numel, dtype=storage_dtype, device=device)
total_numel = self.metadata.total_input_numel
flat_param_buffer = torch.zeros(total_numel, dtype=storage_dtype, device=device)
flat_offset = 0
for hsdp_param in self.hsdp_params:
param_numel = hsdp_param._sharded_param_data.numel()
Expand Down Expand Up @@ -194,9 +202,15 @@ def copy_out(self) -> None:
hsdp_param.hsdp_placement.dim == 0
for hsdp_param in self.hsdp_params
):
split_sizes = metadata.inp_split_sizes
padding = gathered_rows.size(1) - sum(split_sizes)
if padding:
# Consume the wire padding as a final split to keep the source contiguous.
split_sizes = [*split_sizes, padding]
output_rows.append(gathered_rows.new_empty((self.shard_world_size, padding)))
torch.split_with_sizes_copy(
gathered_rows,
metadata.inp_split_sizes,
split_sizes,
dim=1,
out=output_rows,
)
Expand Down Expand Up @@ -232,7 +246,7 @@ def copy_out(self) -> None:
out=output_buffer.view(hsdp_param._orig_size),
)
column_offset += input_numel
if column_offset != gathered_rows.size(1):
if column_offset != sum(metadata.inp_split_sizes):
raise AssertionError(
"Fused all-gather copy-out consumed an unexpected number of elements: "
f"{column_offset} != {gathered_rows.size(1)}"
Expand Down Expand Up @@ -387,7 +401,9 @@ def all_gather_copy_in(
all_gather_input_numel * rank,
all_gather_input_numel,
)
copy_destinations = torch.split(all_gather_input, inp_split_sizes)
used = sum(inp_split_sizes)
all_gather_input[used:].zero_()
copy_destinations = torch.split(all_gather_input[:used], inp_split_sizes)
with torch.no_grad():
# pylint: disable=W0212
torch._foreach_copy_(copy_destinations, all_gather_inputs)
Expand Down Expand Up @@ -426,7 +442,9 @@ def reduce_scatter_copy_in(
packed_grad = torch.cat(grad_chunks, dim=0).contiguous().view(world_size, -1)
packed_grad_slot.copy_(packed_grad)
column_offset += padded_shard_numel
if column_offset != packed_rows.size(1):
if column_offset < packed_rows.size(1):
packed_rows[:, column_offset:].zero_()
if aligned_numel(column_offset, packed_rows.dtype) != packed_rows.size(1):
raise AssertionError(
"reduce_scatter_copy_in packed an unexpected number of elements: "
f"{column_offset} != {packed_rows.size(1)}"
Expand Down Expand Up @@ -516,7 +534,7 @@ def _init_all_gather_buckets(self) -> None:
param_input_numels=param_input_numels,
dtype=bucket_key[1],
inp_split_sizes=inp_split_sizes,
total_input_numel=sum(inp_split_sizes),
total_input_numel=aligned_numel(sum(inp_split_sizes), bucket_key[1]),
)
self.all_gather_buckets.append(
AllGatherBucket(
Expand Down Expand Up @@ -652,7 +670,7 @@ def _build_reduce_scatter_buckets(
flat_offset += param_numel
reduce_scatter_buckets.append(
ReduceScatterBucket(
layout=self._build_gradient_bucket_layout_from(hsdp_params),
layout=self._build_gradient_bucket_layout_from(hsdp_params, bucket_key[1]),
unsharded_grads=grads_by_bucket[bucket_key],
shard_group=shard_group,
shard_world_size=shard_world_size,
Expand All @@ -663,7 +681,7 @@ def _build_reduce_scatter_buckets(
)
return reduce_scatter_buckets

def _build_gradient_bucket_layout_from(self, hsdp_params):
def _build_gradient_bucket_layout_from(self, hsdp_params, dtype):
param_offsets = []
param_numels = []
flat_offset = 0
Expand All @@ -676,7 +694,7 @@ def _build_gradient_bucket_layout_from(self, hsdp_params):
hsdp_params,
param_offsets,
param_numels,
flat_offset
aligned_numel(flat_offset, dtype)
)

@staticmethod
Expand Down
13 changes: 7 additions & 6 deletions tests/ut/core/fully_shard/test_param_group.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ def test_reduce_scatter_copy_in_supports_mixed_placements(self):
"""Reduce-scatter packing should support mixed shard dimensions."""
dim0_grad = torch.arange(8, dtype=torch.float32).view(4, 2)
dim1_grad = torch.arange(16, dtype=torch.float32).view(4, 4)
reduce_scatter_input = torch.empty(24)
reduce_scatter_input = torch.full((2 * 128,), float("nan"))
params = [
SimpleNamespace(
hsdp_placement=Shard(0),
Expand All @@ -209,7 +209,8 @@ def test_reduce_scatter_copy_in_supports_mixed_placements(self):
packed_rows = reduce_scatter_input.view(2, -1)
torch.testing.assert_close(packed_rows[:, :4], dim0_grad.view(2, 4))
expected_dim1 = torch.cat(torch.chunk(dim1_grad, 2, dim=1), dim=0).view(2, 8)
torch.testing.assert_close(packed_rows[:, 4:], expected_dim1)
torch.testing.assert_close(packed_rows[:, 4:12], expected_dim1)
self.assertEqual(torch.count_nonzero(packed_rows[:, 12:]).item(), 0)


class TestAllGatherBuckets(unittest.TestCase):
Expand Down Expand Up @@ -283,7 +284,7 @@ def test_flat_param_buffer_rebases_homogeneous_storage(self):
all_gather_bucket.init_flat_param_buffer(param_group.device)

self.assertTrue(all_gather_bucket.is_flat_buffer_valid())
self.assertEqual(all_gather_bucket.flat_param_buffer.numel(), 4)
self.assertEqual(all_gather_bucket.flat_param_buffer.numel(), 128)
flat_storage_ptr = all_gather_bucket.flat_param_buffer.untyped_storage().data_ptr()
self.assertEqual(param_a._sharded_param_data.untyped_storage().data_ptr(), flat_storage_ptr)
self.assertEqual(param_b._sharded_param_data.untyped_storage().data_ptr(), flat_storage_ptr)
Expand Down Expand Up @@ -507,7 +508,7 @@ def reduce_scatter(**collective_args):
param_group.wait_reduce_scatter_and_issue_all_reduce()
torch.testing.assert_close(
param_group.reduce_partial_outputs[bucket_key],
expected_partial,
torch.nn.functional.pad(expected_partial, (0, 128 - expected_partial.numel())),
)
if parked_output is None:
parked_output = param_group.reduce_partial_outputs[bucket_key]
Expand Down Expand Up @@ -545,8 +546,8 @@ def test_gradient_scaling_is_applied_to_packed_reduce_scatter_input(self, mock_r

def reduce_scatter(**collective_args):
torch.testing.assert_close(
collective_args["input"],
torch.tensor([0.5, 1.0, 1.5, 2.0]),
collective_args["input"].view(2, 128),
torch.nn.functional.pad(torch.tensor([[0.5, 1.0], [1.5, 2.0]]), (0, 126)),
)
collective_args["output"].copy_(collective_args["input"].view(2, -1).sum(dim=0))
return MagicMock()
Expand Down