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
83 changes: 72 additions & 11 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 @@ -147,6 +155,41 @@ def is_flat_buffer_valid(self) -> bool:
for hsdp_param in self.hsdp_params
)

def supports_direct_output(self) -> bool:
"""Select uniformly sharded NPU inputs that need no layout or dtype conversion."""
return hasattr(self.shard_group, "allgather_into_tensor_coalesced") and all(
param.hsdp_placement.dim == 0
and param._orig_size[0] % self.shard_world_size == 0
and not param.offload_to_cpu
and param._sharded_param_data.device.type == "npu"
and param._sharded_param_data.dtype == self.dtype
and param._sharded_param_data.is_contiguous()
and param._sharded_param_data.numel() > 0
for param in self.hsdp_params
)

def gather_to_param_buffers(self, async_op: bool) -> None:
"""Gather each shard into its stable parameter buffer in one batch submission."""
inputs = []
outputs = []
with ExitStack() as stack:
for param in self.hsdp_params:
shard = param._sharded_param_data
param.init_unsharded_param_buffers([shard.numel()], [self.dtype], self.shard_world_size, shard.device)
param.alloc_unsharded_param_buffers()
output = param.unsharded_param_buffers[0]
if not output.is_inference():
stack.enter_context(torch.autograd._unsafe_preserve_version_counter(output))
inputs.append(shard)
outputs.append(output)
handle = self.shard_group.allgather_into_tensor_coalesced(outputs, inputs)
if not async_op:
handle.wait()
handle = None
# The parameters own both ends of the transfer. No intermediate flat
# allocation is required, but prefetch still needs a pending result.
self.all_gather_result = AllGatherResult(None, None, handle)

@torch.no_grad()
def copy_out(self) -> None:
"""Wait this bucket's all-gather and copy it into stable unsharded buffers.
Expand All @@ -156,12 +199,15 @@ def copy_out(self) -> None:
before the next bucket runs. No-op when the bucket has no pending result.
"""
all_gather_result = self.all_gather_result
if all_gather_result is None or all_gather_result.all_gather_output is None:
if all_gather_result is None:
return
if all_gather_result.handle is not None:
all_gather_result.handle.wait()
all_gather_result.handle = None
all_gather_output = all_gather_result.all_gather_output
if all_gather_output is None:
self.all_gather_result = None
return
metadata = self.metadata
split_with_sizes_out = []
for input_numels, input_dtypes, hsdp_param in zip(
Expand Down Expand Up @@ -194,9 +240,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 +284,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 +439,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 +480,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 @@ -473,11 +529,13 @@ def __init__(
device: Optional[torch.device] = None,
enable_zero_copy: bool = True,
comm_ctx: Optional[ParamGroupCommCtx] = None,
direct_all_gather: bool = False,
) -> None:
self.device = device
self.hsdp_params = hsdp_params
self.comm_ctx = comm_ctx or ParamGroupCommCtx()
self.enable_zero_copy = enable_zero_copy
self.direct_all_gather = direct_all_gather
self.gradient_scaling_factor = None
self.requires_all_reduce = True
self.all_gather_buckets: list[AllGatherBucket] = []
Expand Down Expand Up @@ -516,7 +574,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 @@ -550,6 +608,9 @@ def foreach_all_gather(self, async_op: bool = False) -> None:
for all_gather_bucket in self.all_gather_buckets:
if all_gather_bucket.all_gather_result is not None:
continue
if self.direct_all_gather and all_gather_bucket.supports_direct_output():
all_gather_bucket.gather_to_param_buffers(async_op)
continue
if self.enable_zero_copy and not all_gather_bucket.is_flat_buffer_valid():
all_gather_bucket.init_flat_param_buffer(self.device)

Expand Down Expand Up @@ -652,7 +713,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 @@ -664,7 +725,7 @@ def _build_reduce_scatter_buckets(
return reduce_scatter_buckets

@staticmethod
def _build_gradient_bucket_layout_from(hsdp_params):
def _build_gradient_bucket_layout_from(hsdp_params, dtype):
param_offsets = []
param_numels = []
flat_offset = 0
Expand All @@ -677,7 +738,7 @@ def _build_gradient_bucket_layout_from(hsdp_params):
hsdp_params,
param_offsets,
param_numels,
flat_offset
aligned_numel(flat_offset, dtype)
)

@staticmethod
Expand Down
46 changes: 40 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 @@ -335,6 +336,39 @@ def all_gather(output, input_tensor, **unused):
torch.tensor([1.0, 2.0, 3.0, 4.0]),
)

def test_direct_all_gather_waits_once_and_preserves_stable_output(self):
"""Repeated prefetch must not launch twice or invalidate a saved tensor."""
group = _FakeGroup()
mesh = _mesh_info(shard_group=group)
params = [_fake_param(values, mesh_info=mesh) for values in ([1., 2.], [3., 4., 5.])]
param_group = HSDPParamGroup(params, device=torch.device("cpu"), direct_all_gather=True)
param_group._init_all_gather_buckets()
bucket = param_group.all_gather_buckets[0]
self.assertFalse(bucket.supports_direct_output())

def gather(outputs, inputs):
for output, shard in zip(outputs, inputs):
output.copy_(torch.cat((shard, shard + 10)))
return handle

group.allgather_into_tensor_coalesced = MagicMock(side_effect=gather)
for async_op in (True, False):
handle = MagicMock()
with patch.object(bucket, "supports_direct_output", return_value=True):
param_group.unshard(async_op=async_op)
param_group.unshard(async_op=async_op)
group.allgather_into_tensor_coalesced.assert_called_once()
self.assertEqual(handle.wait.call_count, int(not async_op))
param_group.wait_for_unshard()
handle.wait.assert_called_once()
self.assertIsNone(bucket.all_gather_result)
for param in params:
output = param.unsharded_param_buffers[0]
self.assertEqual(output._version, 0)
shard = param._sharded_param_data
torch.testing.assert_close(output, torch.cat((shard, shard + 10)))
group.allgather_into_tensor_coalesced.reset_mock()

def test_copy_out_preserves_stable_buffer_version(self):
"""All-gather copy-out should preserve the persistent buffer version."""
hsdp_param = _fake_param([1.0, 2.0])
Expand Down Expand Up @@ -519,7 +553,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 @@ -557,8 +591,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