From b1e4c22f00100174057447d28c776463f4f5716e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BC=A0=E9=93=AD?= <15084926143@163.com> Date: Wed, 25 Nov 2026 17:58:24 +0800 Subject: [PATCH 1/2] Align each fused FSDP collective rank payload to 512 bytes --- .../core/fully_shard/param_group.py | 38 ++++++++++++++----- 1 file changed, 28 insertions(+), 10 deletions(-) diff --git a/hyper_parallel/core/fully_shard/param_group.py b/hyper_parallel/core/fully_shard/param_group.py index e844b13e7b..d61241b05f 100644 --- a/hyper_parallel/core/fully_shard/param_group.py +++ b/hyper_parallel/core/fully_shard/param_group.py @@ -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.""" @@ -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() @@ -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, ) @@ -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)}" @@ -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) @@ -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)}" @@ -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( @@ -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, @@ -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 @@ -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 From 62abd12fecb2e076436f645a621f71efe2794834 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BC=A0=E9=93=AD?= <15084926143@163.com> Date: Wed, 25 Nov 2026 17:58:37 +0800 Subject: [PATCH 2/2] Validate padded FSDP buffers and packed gradient values --- tests/ut/core/fully_shard/test_param_group.py | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/tests/ut/core/fully_shard/test_param_group.py b/tests/ut/core/fully_shard/test_param_group.py index 11dab30b1d..574cdced6f 100644 --- a/tests/ut/core/fully_shard/test_param_group.py +++ b/tests/ut/core/fully_shard/test_param_group.py @@ -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), @@ -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): @@ -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) @@ -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] @@ -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()