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
17 changes: 17 additions & 0 deletions hyper_parallel/core/fully_shard/hsdp_param.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,8 @@ def __init__(
"""
self._module_info: ParamModuleInfo = module_info
self.mesh_info = mesh_info
self._gather_group_ref = None
self.mp_policy = mp_policy
self._src_parameter_id = id(param)
self.device = device
self.orig_dtype = None
Expand Down Expand Up @@ -663,8 +665,16 @@ def _init_sharded_param(
self.param_dtype = None
self.reduce_dtype = None

def _mark_gather_layout_dirty(self):
if self._gather_group_ref is not None:
group = self._gather_group_ref()
if group is not None:
group.gather_layout_dirty = True

def init_dtype_attrs(self, mp_policy: MixedPrecisionPolicy) -> None:
"""Initialize dtype attributes, applying source-parameter overrides before policy defaults."""
previous_dtype = self.param_dtype or self.orig_dtype
self.mp_policy = mp_policy
custom_dtypes = (mp_policy.custom_params or {}).get(self._src_parameter_id, {})
param_dtype = custom_dtypes.get("param_dtype", mp_policy.param_dtype)
reduce_dtype = custom_dtypes.get("reduce_dtype", mp_policy.reduce_dtype)
Expand All @@ -675,6 +685,8 @@ def init_dtype_attrs(self, mp_policy: MixedPrecisionPolicy) -> None:
param_dtype = None
self.param_dtype = param_dtype
self.reduce_dtype = reduce_dtype
if (param_dtype or self.orig_dtype) != previous_dtype:
self._mark_gather_layout_dirty()
self.apply_grad_on_fp32_main_grad = mp_policy.apply_grad_on_fp32_main_grad

def init_unsharded_param_buffers(
Expand Down Expand Up @@ -930,6 +942,8 @@ def _is_same_sharded_local_tensor(self, local_tensor: torch.Tensor) -> bool:
# Empty shards may have a zero data pointer and must still be rebuilt.
sharded_data_ptr > 0
and sharded_data_ptr == local_tensor.untyped_storage().data_ptr()
and self._sharded_param_data.storage_offset() == local_tensor.storage_offset()
and self._sharded_param_data.dtype == local_tensor.dtype
)

def _validate_reset_local_tensor(
Expand Down Expand Up @@ -1021,6 +1035,9 @@ def reset_sharded_param(self) -> None:
raise AssertionError(f"Expected DTensor, got {type(self.sharded_param)}")
if not same_local_tensor or pinned_local_tensor:
self._refresh_sharded_local_tensor(local_tensor, shard_dim)
if self._gather_group_ref is not None:
self.init_dtype_attrs(self.mp_policy)
self._mark_gather_layout_dirty()
self._sharding_spec.set_tensor_meta(
self._sharding_spec.tensor_shape,
self._sharding_spec.tensor_stride,
Expand Down
54 changes: 48 additions & 6 deletions hyper_parallel/core/fully_shard/param_group.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
from contextlib import ExitStack
from dataclasses import dataclass
from typing import List, Optional
from weakref import ref

import torch
import torch.distributed as dist
Expand Down Expand Up @@ -142,10 +143,15 @@ def is_flat_buffer_valid(self) -> bool:
if self.flat_param_buffer is None:
return False
flat_storage_ptr = self.flat_param_buffer.untyped_storage().data_ptr()
return all(
hsdp_param._sharded_param_data.untyped_storage().data_ptr() == flat_storage_ptr
for hsdp_param in self.hsdp_params
)
offset = 0
for param, numel in zip(self.hsdp_params, self.metadata.inp_split_sizes):
shard = param._sharded_param_data
if (shard.untyped_storage().data_ptr() != flat_storage_ptr
or shard.storage_offset() != offset or shard.numel() != numel
or shard.dtype != self.flat_param_buffer.dtype or not shard.is_contiguous()):
return False
offset += numel
return offset == self.flat_param_buffer.numel()

@torch.no_grad()
def copy_out(self) -> None:
Expand Down Expand Up @@ -478,13 +484,44 @@ def __init__(
self.hsdp_params = hsdp_params
self.comm_ctx = comm_ctx or ParamGroupCommCtx()
self.enable_zero_copy = enable_zero_copy
self.gather_layout_dirty = True
for param in hsdp_params:
param._gather_group_ref = ref(self)
self.gradient_scaling_factor = None
self.requires_all_reduce = True
self.all_gather_buckets: list[AllGatherBucket] = []
self.reduce_scatter_buckets: list[ReduceScatterBucket] = []
self.all_reduce_buckets: list[AllReduceBucket] = []
self.reduce_partial_outputs: dict[tuple, torch.Tensor] = {}

def refresh_all_gather_layout(self) -> None:
"""Expire the gather plan after reset or mixed-precision reconfiguration."""
if not self.gather_layout_dirty:
return
if not self.all_gather_buckets or self._gather_layout == self._current_gather_layout():
self.gather_layout_dirty = False
return
if any(bucket.all_gather_result is not None for bucket in self.all_gather_buckets):
raise RuntimeError("Finish the pending all-gather before changing parameter layout.")
for param in self.hsdp_params:
buffers = param.unsharded_param_buffers
if buffers and (buffers[0].dtype != (param.param_dtype or param.orig_dtype)
or buffers[0].numel() != param._sharded_param_data.numel() * param.shard_world_size):
# The stable unsharded Parameter is a view of this output storage.
# Recreate both together on the next unshard after the reset.
if hasattr(param, "_unsharded_param"):
del param._unsharded_param
buffers.clear()
self.all_gather_buckets.clear()
self.gather_layout_dirty = False

def _current_gather_layout(self):
return tuple(
(id(p), id(p.mesh_info.shard_process_group), p.param_dtype or p.orig_dtype,
p.padded_sharded_param_size, p.hsdp_placement.dim, p.shard_world_size)
for p in self.hsdp_params if p.shard_world_size > 1
)

def _init_all_gather_buckets(self) -> None:
"""Build ordered all-gather buckets from each parameter's communication facts."""
params_by_bucket = {}
Expand All @@ -504,6 +541,7 @@ def _init_all_gather_buckets(self) -> None:
bucket_groups[bucket_key] = shard_group
params_by_bucket[bucket_key].append(hsdp_param)

self._gather_layout = self._current_gather_layout()
self.all_gather_buckets = []
for bucket_key, hsdp_params in params_by_bucket.items():
shard_group = bucket_groups[bucket_key]
Expand Down Expand Up @@ -531,6 +569,7 @@ def _init_all_gather_buckets(self) -> None:

def unshard(self, async_op: bool = False) -> None:
"""Launch fused all-gathers for every communication bucket."""
self.refresh_all_gather_layout()
if self.all_gather_buckets and any(
bucket.all_gather_result is not None for bucket in self.all_gather_buckets
):
Expand All @@ -541,6 +580,7 @@ def unshard(self, async_op: bool = False) -> None:
@torch.no_grad()
def foreach_all_gather(self, async_op: bool = False) -> None:
"""Initialize ordered buckets and launch their all-gathers."""
self.refresh_all_gather_layout()
if not self.all_gather_buckets:
self._init_all_gather_buckets()
for hsdp_param in self.hsdp_params:
Expand All @@ -550,16 +590,18 @@ 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.enable_zero_copy and not all_gather_bucket.is_flat_buffer_valid():
use_flat = self.enable_zero_copy and all_gather_bucket.is_flat_buffer_valid()
if self.enable_zero_copy and not use_flat:
all_gather_bucket.init_flat_param_buffer(self.device)
use_flat = all_gather_bucket.is_flat_buffer_valid()

metadata = all_gather_bucket.metadata
all_gather_output = torch.empty(
metadata.total_input_numel * all_gather_bucket.shard_world_size,
dtype=all_gather_bucket.dtype,
device=self.device,
)
if self.enable_zero_copy and all_gather_bucket.is_flat_buffer_valid():
if use_flat:
if all_gather_bucket.flat_param_buffer.dtype == all_gather_bucket.dtype:
all_gather_input = all_gather_bucket.flat_param_buffer
else:
Expand Down