Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / core / optimizer / muon_shard.py: 72%
300 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
1# Copyright 2026 Huawei Technologies Co., Ltd
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ============================================================================
16"""Shard function of muon."""
18__all__ = [
19 "build_param_shard_metadata_for_group",
20 "build_pad_ns_inputs",
21 "chunk_update_by_layout",
22 "fused_allgather_dtensor_params",
23 "get_or_alloc_buffer",
24]
26import math
27import logging
29from collections.abc import Callable
30from dataclasses import dataclass
31from typing import Any, Dict, List, Optional, Sequence, Tuple
33import torch
34import torch.distributed as dist
36from hyper_parallel.core.optimizer.dtensor_compat import to_local_if_dtensor
37from hyper_parallel.core.utils import communication
38from hyper_parallel.core.optimizer.sharding_category import (
39 HSDPCommGroup,
40 ParamLayoutSpec,
41 ParamShardMeta,
42 ParamShardStageMeta,
43)
45logger = logging.getLogger(__name__)
48def make_param_shard_meta(
49 param: torch.Tensor,
50 stage_metas: List[ParamShardStageMeta],
51) -> ParamShardMeta:
52 """Construct shard metadata from real local-shape plans."""
53 global_shape = tuple(param.shape)
54 local_shape = tuple(to_local_if_dtensor(param.data).shape)
55 return ParamShardMeta(
56 global_shape=global_shape,
57 global_numel=math.prod(global_shape),
58 local_shape=local_shape,
59 local_numel=math.prod(local_shape),
60 stage_metas=tuple(stage_metas),
61 )
64def _get_mesh_shape(device_mesh) -> Tuple[int, ...]:
65 """Get mesh shape."""
66 mesh = getattr(device_mesh, "mesh", None)
67 if mesh is not None:
68 return tuple(mesh.shape)
69 mesh_shape = getattr(device_mesh, "mesh_shape", None)
70 if mesh_shape is not None:
71 return tuple(mesh_shape)
72 return ()
75def _get_local_shape_kinds(global_shape: Tuple[int, ...], shard_meta: ParamShardMeta) -> List[Tuple[int, ...]]:
76 """Collect all distinct local shapes implied by the shard metadata."""
77 dim_size_options: Dict[int, List[int]] = {}
78 for stage_meta in shard_meta.stage_metas:
79 tensor_dim = stage_meta.tensor_dim
80 seen_sizes = []
81 for split_size in stage_meta.split_sizes:
82 if split_size not in seen_sizes:
83 seen_sizes.append(split_size)
84 dim_size_options[tensor_dim] = seen_sizes
86 shape_kinds = [list(global_shape)]
87 for tensor_dim, size_options in sorted(dim_size_options.items()):
88 next_shape_kinds = []
89 for shape_kind in shape_kinds:
90 for size in size_options:
91 next_shape = list(shape_kind)
92 next_shape[tensor_dim] = size
93 next_shape_kinds.append(next_shape)
94 shape_kinds = next_shape_kinds
96 unique_shape_kinds = []
97 seen = set()
98 for shape_kind in shape_kinds:
99 shape_kind = tuple(shape_kind)
100 if shape_kind in seen:
101 continue
102 seen.add(shape_kind)
103 unique_shape_kinds.append(shape_kind)
104 return unique_shape_kinds
107def _debug_param_shard_metadata(hsdp_group, param_to_meta: Dict[torch.nn.Parameter, ParamShardMeta]) -> None:
108 """Log shard metadata for the group on rank 0 when distributed is ready."""
109 if not dist.is_available() or not dist.is_initialized():
110 return
112 rank = dist.get_rank()
113 if rank != 0:
114 return
116 for record in hsdp_group.records:
117 param = record.param
118 shard_meta = param_to_meta.get(param)
119 if shard_meta is None:
120 continue
121 local_shape_kinds = _get_local_shape_kinds(shard_meta.global_shape, shard_meta)
122 logger.debug_rank0(
123 "name=%s, placements=%s, mesh_shape=%s, global_shape=%s, local_shapes=%s",
124 getattr(param, "model_name", f"param_{record.index}"),
125 [str(placement) for placement in param.placements],
126 _get_mesh_shape(param.device_mesh),
127 shard_meta.global_shape,
128 local_shape_kinds,
129 )
132def _comm_device_for_group(
133 shard_pg: Optional[dist.ProcessGroup],
134 device: torch.device,
135) -> torch.device:
136 """Return a device the group's backend can run collectives on.
138 With CPU offload the parameter locals live on host while the shard group
139 is an accelerator backend (HCCL/NCCL) with no CPU path; the metadata
140 gather must then run on the accelerator. Under logical simulation the
141 group is a fake backend and the simulated accelerator plays that role, so
142 the staging allocations land where a real run puts them.
143 """
144 if device.type != "cpu" or shard_pg is None:
145 return device
146 device_type = communication.comm_device_type(dist.get_backend(shard_pg))
147 if device_type is None:
148 return device
149 return torch.device(device_type, torch.get_device_module(device_type).current_device())
152def _allgather_shapes_for_group(
153 local_shapes: List[Tuple[int, ...]],
154 shard_pg: Optional[dist.ProcessGroup],
155 shard_size: int,
156 device: torch.device,
157) -> List[List[Tuple[int, ...]]]:
158 """All-gather per-parameter shapes within one shard process group."""
159 if shard_pg is None or shard_size <= 1:
160 return [[tuple(shape) for shape in local_shapes]]
162 device = _comm_device_for_group(shard_pg, device)
163 shape_tensor = torch.tensor(local_shapes, dtype=torch.int64, device=device)
164 gathered = torch.empty((shard_size, *shape_tensor.shape), dtype=torch.int64, device=device)
165 dist.all_gather_into_tensor(gathered.view(-1), shape_tensor.contiguous().view(-1), group=shard_pg)
166 gathered_cpu = gathered.cpu().tolist()
167 return [
168 [tuple(shape) for shape in rank_shapes]
169 for rank_shapes in gathered_cpu
170 ]
173def build_param_shard_metadata_for_group(
174 hsdp_group: HSDPCommGroup,
175) -> Dict[torch.Tensor, ParamShardMeta]:
176 """Build per-parameter shard metadata and refresh existing records in place."""
177 # pylint: disable=too-many-locals
178 layout_spec = hsdp_group.layout_spec
179 shard_pgs = hsdp_group.shard_pgs
180 if layout_spec is None or not layout_spec.shard_axes or not hsdp_group.records:
181 return {}
183 current_shapes = [tuple(to_local_if_dtensor(record.param.data).shape) for record in hsdp_group.records]
184 stage_metas_per_param: List[List[ParamShardStageMeta]] = [[] for _ in hsdp_group.records]
185 local_device = to_local_if_dtensor(hsdp_group.records[0].param.data).device
187 for (_, tensor_dim), shard_pg in zip(layout_spec.shard_axes, shard_pgs):
188 shard_size = dist.get_world_size(shard_pg) if shard_pg is not None else 1
189 gathered_shapes = _allgather_shapes_for_group(current_shapes, shard_pg, shard_size, local_device)
190 cur_rank = dist.get_rank(shard_pg) if shard_pg is not None and shard_size > 1 else 0
191 next_shapes: List[Tuple[int, ...]] = []
193 for record_idx, _ in enumerate(hsdp_group.records):
194 rank_shapes = tuple(
195 tuple(gathered_shapes[rank_idx][record_idx])
196 for rank_idx in range(shard_size)
197 )
198 tensor_dim_norm = tensor_dim % len(rank_shapes[0])
199 split_sizes = tuple(shape[tensor_dim_norm] for shape in rank_shapes)
200 pad_shape = tuple(max(shape[dim] for shape in rank_shapes) for dim in range(len(rank_shapes[0])))
201 stage_metas_per_param[record_idx].append(
202 ParamShardStageMeta(
203 tensor_dim=tensor_dim_norm,
204 shard_size=shard_size,
205 cur_rank_in_shard_group=cur_rank,
206 rank_shapes=rank_shapes,
207 split_sizes=split_sizes,
208 pad_shape=pad_shape,
209 )
210 )
212 output_shape = list(rank_shapes[cur_rank])
213 if shard_size > 1:
214 output_shape[tensor_dim_norm] = sum(split_sizes)
215 next_shapes.append(tuple(output_shape))
217 current_shapes = next_shapes
219 param_to_meta: Dict[torch.Tensor, ParamShardMeta] = {}
220 for record, stage_metas in zip(hsdp_group.records, stage_metas_per_param):
221 shard_meta = make_param_shard_meta(record.param, stage_metas)
222 record.shard_meta = shard_meta
223 param_to_meta[record.param] = shard_meta
224 return param_to_meta
227def build_pad_ns_inputs(
228 comm_params: List[torch.Tensor],
229 param_to_ns_input: Dict[torch.Tensor, torch.Tensor],
230 param_shard_metadata: Optional[Dict[torch.Tensor, ParamShardMeta]] = None,
231 *,
232 fallback_dtype: Optional[torch.dtype] = None,
233) -> List[torch.Tensor]:
234 """Build aligned local NS inputs for all communication params."""
235 if not comm_params:
236 return []
238 ref_tensor = next(iter(param_to_ns_input.values()), None)
239 default_dtype = ref_tensor.dtype if ref_tensor is not None else fallback_dtype
240 if default_dtype is None:
241 default_dtype = to_local_if_dtensor(comm_params[0].data).dtype
242 local_inputs: List[torch.Tensor] = []
244 for param in comm_params:
245 ns_input = param_to_ns_input.get(param)
246 if ns_input is not None:
247 local_inputs.append(ns_input)
248 continue
250 shard_meta = None
251 if param_shard_metadata is not None:
252 shard_meta = param_shard_metadata.get(param)
253 if shard_meta is None and hasattr(param, "shard_meta"):
254 shard_meta = getattr(param, "shard_meta")
255 if shard_meta is None:
256 local_shape = tuple(to_local_if_dtensor(param.data).shape)
257 else:
258 local_shape = shard_meta.local_shape
260 local_inputs.append(
261 torch.zeros(
262 local_shape,
263 dtype=default_dtype,
264 device=to_local_if_dtensor(param.data).device,
265 )
266 )
268 return local_inputs
271def chunk_update_by_layout(
272 global_update: torch.Tensor,
273 param: torch.Tensor,
274 layout_spec: ParamLayoutSpec,
275 param_shard_meta: Optional[ParamShardMeta] = None,
276) -> torch.Tensor:
277 """Slice a full update back to the local shard using narrow."""
278 if not hasattr(param, "device_mesh") or layout_spec is None or not layout_spec.shard_axes:
279 return global_update
281 device_mesh = param.device_mesh
282 mesh_coordinates = device_mesh.get_coordinate()
284 shard_axes = layout_spec.shard_axes
285 local_update = global_update
287 # ``stage_metas`` are built while all-gathering local shards back to the
288 # global tensor shape, so slicing a global update back to the local shard
289 # must reverse that order.
290 for axis_idx, (mesh_dim, tensor_dim) in reversed(list(enumerate(shard_axes))):
291 num_chunks = device_mesh.size(mesh_dim)
293 if num_chunks <= 1:
294 continue
296 local_rank = mesh_coordinates[mesh_dim]
297 if param_shard_meta is not None and axis_idx < len(param_shard_meta.stage_metas):
298 split_sizes = param_shard_meta.stage_metas[axis_idx].split_sizes
299 else:
300 full_chunk_size = (local_update.size(tensor_dim) + num_chunks - 1) // num_chunks
301 split_sizes = tuple(
302 min(full_chunk_size, max(local_update.size(tensor_dim) - rank * full_chunk_size, 0))
303 for rank in range(num_chunks)
304 )
305 local_update = local_update.narrow(tensor_dim, sum(split_sizes[:local_rank]), split_sizes[local_rank])
307 if not local_update.is_contiguous():
308 local_update = local_update.contiguous()
310 return local_update
313def get_or_alloc_buffer(
314 cache: Optional[Dict],
315 key: Any,
316 numel: int,
317 dtype: torch.dtype,
318 device: torch.device,
319) -> torch.Tensor:
320 """Return a cached buffer with at least `numel` elements."""
321 if cache is not None and key in cache:
322 buf = cache[key]
323 if buf.numel() >= numel:
324 return buf
325 buf = torch.empty(numel, dtype=dtype, device=device)
326 cache[key] = buf
327 return buf
329 buf = torch.empty(numel, dtype=dtype, device=device)
330 if cache is not None:
331 cache[key] = buf
332 return buf
335def _early_return_tensors(
336 local_tensors: List[torch.Tensor],
337 keep_indices: Optional[set],
338) -> List[Optional[torch.Tensor]]:
339 """Return tensors directly when no communication is needed."""
340 if keep_indices is None:
341 return list(local_tensors)
342 return [t if i in keep_indices else None for i, t in enumerate(local_tensors)]
345@dataclass(frozen=True)
346class _GatherParamMeta:
347 offset: int
348 actual_numel: int
349 padded_numel: int
350 rest_shape: Tuple[int, ...]
351 split_sizes: Tuple[int, ...]
354def _prepare_gather_inputs(
355 current_tensors: List[torch.Tensor],
356 tensor_dim: int,
357 alignment_elements: int,
358 shard_size: int,
359 stage_metas: Optional[List[Optional[ParamShardStageMeta]]] = None,
360) -> Tuple[List[torch.Tensor], List[_GatherParamMeta], int]:
361 """Move shard dim to dim0 and compute padding metadata."""
362 gather_inputs: List[torch.Tensor] = []
363 param_meta: List[_GatherParamMeta] = []
364 total_padded_numel = 0
366 for idx, gather_input in enumerate(current_tensors):
367 normalized_dim = tensor_dim % gather_input.dim()
368 if normalized_dim != 0 or not gather_input.is_contiguous():
369 gather_input = gather_input.movedim(normalized_dim, 0).contiguous()
370 stage_meta = stage_metas[idx] if stage_metas is not None else None
371 if stage_meta is None:
372 split_sizes = tuple(gather_input.shape[0] for _ in range(shard_size))
373 padded_numel_raw = gather_input.numel()
374 else:
375 split_sizes = stage_meta.split_sizes
376 pad_shape = list(stage_meta.pad_shape)
377 if normalized_dim != 0:
378 pad_shape[0], pad_shape[normalized_dim] = pad_shape[normalized_dim], pad_shape[0]
379 padded_numel_raw = math.prod(pad_shape)
380 param_meta.append(
381 _GatherParamMeta(
382 offset=total_padded_numel,
383 actual_numel=gather_input.numel(),
384 padded_numel=(
385 (padded_numel_raw + alignment_elements - 1) // alignment_elements * alignment_elements
386 ),
387 rest_shape=tuple(gather_input.shape[1:]),
388 split_sizes=split_sizes,
389 )
390 )
391 gather_inputs.append(gather_input)
392 total_padded_numel += param_meta[-1].padded_numel
394 return gather_inputs, param_meta, total_padded_numel
397def _pack_and_allgather(
398 gather_inputs: List[torch.Tensor],
399 param_meta: List[_GatherParamMeta],
400 total_padded_numel: int,
401 axis_idx: int,
402 dtype: torch.dtype,
403 device: torch.device,
404 shard_pg: dist.ProcessGroup,
405 shard_size: int,
406 buffer_cache: Optional[Dict],
407 while_gathering: Optional[Callable[[], None]],
408) -> torch.Tensor:
409 """Pack local shards into one buffer, all-gather, return gathered view.
411 The pack and gather buffers live on a device the group's backend supports:
412 with CPU offload the shards live on host while the shard group is an
413 accelerator backend, so the collective is staged there and the gathered
414 view is brought back to the shards' device for the NS computation.
415 """
416 comm_device = _comm_device_for_group(shard_pg, device)
417 pack_buffer = get_or_alloc_buffer(
418 buffer_cache, ("fused_allgather", axis_idx, dtype, comm_device), total_padded_numel,
419 dtype, comm_device,
420 )[:total_padded_numel]
422 destinations = []
423 for gi, meta in zip(gather_inputs, param_meta):
424 end = meta.offset + meta.actual_numel
425 destinations.append(pack_buffer[meta.offset:end])
426 if meta.actual_numel < meta.padded_numel:
427 pack_buffer[end:meta.offset + meta.padded_numel].zero_()
428 sources = [gi.view(-1) for gi in gather_inputs]
429 if comm_device == device:
430 # Keep one batched copy to avoid launching a copy per parameter.
431 # pylint: disable-next=protected-access
432 torch._foreach_copy_(destinations, sources)
433 else:
434 for destination, source in zip(destinations, sources):
435 destination.copy_(source)
437 gathered_buffer = get_or_alloc_buffer(
438 buffer_cache,
439 ("fused_allgather_out", axis_idx, dtype, comm_device),
440 total_padded_numel * shard_size,
441 dtype, comm_device,
442 )[:total_padded_numel * shard_size]
444 if while_gathering is None:
445 dist.all_gather_into_tensor(gathered_buffer, pack_buffer, group=shard_pg)
446 else:
447 work = dist.all_gather_into_tensor(gathered_buffer, pack_buffer, group=shard_pg, async_op=True)
448 try:
449 while_gathering()
450 finally:
451 work.wait()
452 if comm_device != device:
453 gathered_buffer = gathered_buffer.to(device)
454 return gathered_buffer.view(shard_size, total_padded_numel)
457def _get_owner_buffer(
458 gathered_view: torch.Tensor,
459 param_meta: List[_GatherParamMeta],
460 keep_indices: Optional[set],
461 cache: Optional[Dict],
462) -> Optional[torch.Tensor]:
463 """Reserve storage for the gathered parameters this rank will update."""
464 if cache is None:
465 return None
466 owner_numel = sum(
467 sum(meta.split_sizes) * math.prod(meta.rest_shape)
468 for idx, meta in enumerate(param_meta) if keep_indices is None or idx in keep_indices
469 )
470 if owner_numel == 0:
471 return None
472 dtype, device = gathered_view.dtype, gathered_view.device
473 return get_or_alloc_buffer(cache, (dtype, device), owner_numel, dtype, device)
476def _unpack_gathered_results(
477 gathered_view: torch.Tensor,
478 gather_inputs: List[torch.Tensor],
479 param_meta: List[_GatherParamMeta],
480 current_tensors: List[torch.Tensor],
481 tensor_dim: int,
482 is_last_axis: bool,
483 keep_indices: Optional[set],
484 owner_buffer_cache: Optional[Dict],
485) -> List[Optional[torch.Tensor]]:
486 """Slice gathered buffer back to per-parameter full tensors."""
487 owner_buffer = None
488 if is_last_axis:
489 owner_buffer = _get_owner_buffer(gathered_view, param_meta, keep_indices, owner_buffer_cache)
490 new_tensors: List[Optional[torch.Tensor]] = []
491 owner_offset = 0
492 for i, meta in enumerate(param_meta):
493 if is_last_axis and keep_indices is not None and i not in keep_indices:
494 new_tensors.append(None)
495 continue
497 rest_shape = meta.rest_shape
498 rest_numel = math.prod(rest_shape)
499 param_slice = gathered_view[:, meta.offset:meta.offset + meta.padded_numel]
501 full_rows = sum(meta.split_sizes)
502 count = full_rows * rest_numel
503 if count == 0:
504 param_data = gather_inputs[i].new_empty((0,))
505 elif owner_buffer is not None:
506 param_data = owner_buffer.narrow(0, owner_offset, count)
507 _unpack_into_owner_buffer(param_data, param_slice, meta.split_sizes, rest_numel)
508 owner_offset += count
509 else:
510 param_chunks = [param_slice[rank, :rows * rest_numel]
511 for rank, rows in enumerate(meta.split_sizes) if rows > 0]
512 param_data = torch.cat(param_chunks, dim=0)
514 result = param_data.view(full_rows, *rest_shape)
515 tensor_dim_norm = tensor_dim % current_tensors[i].dim()
516 if tensor_dim_norm == 0:
517 new_tensors.append(result)
518 else:
519 new_tensors.append(result.movedim(0, tensor_dim_norm))
521 return new_tensors
524def _unpack_into_owner_buffer(
525 output: torch.Tensor, gathered: torch.Tensor, split_sizes: Tuple[int, ...], rest_numel: int,
526) -> None:
527 """Copy even shards as one strided matrix, otherwise concatenate the valid rank slices."""
528 rows = split_sizes[0]
529 if split_sizes == (rows,) * len(split_sizes):
530 cols = rows * rest_numel
531 output.view(len(split_sizes), cols).copy_(gathered[:, :cols])
532 else:
533 chunks = [gathered[rank, :rows * rest_numel] for rank, rows in enumerate(split_sizes) if rows > 0]
534 torch.cat(chunks, dim=0, out=output)
537def fused_allgather_dtensor_params(
538 local_tensors: List[torch.Tensor],
539 shard_pgs: Sequence[dist.ProcessGroup],
540 layout_spec: ParamLayoutSpec,
541 param_shard_metadata: Optional[List[Optional[ParamShardMeta]]] = None,
542 buffer_cache: Optional[Dict] = None,
543 keep_indices: Optional[set] = None,
544 *,
545 while_gathering: Optional[Callable[[], None]] = None,
546 owner_buffer_cache: Optional[Dict] = None,
547) -> List[Optional[torch.Tensor]]:
548 """Fuse many parameter shards into one all-gather per shard axis."""
549 if not shard_pgs or not local_tensors:
550 return _early_return_tensors(local_tensors, keep_indices)
552 device = local_tensors[0].device
553 dtype = local_tensors[0].dtype
554 alignment_bytes = 512
555 element_size = local_tensors[0].element_size()
556 alignment_elements = max(1, alignment_bytes // element_size)
558 active_axes = []
559 for axis_idx, ((_, tensor_dim), shard_pg) in enumerate(zip(layout_spec.shard_axes, shard_pgs)):
560 if shard_pg is None:
561 continue
562 shard_size = dist.get_world_size(shard_pg)
563 if shard_size <= 1:
564 continue
565 active_axes.append((axis_idx, tensor_dim, shard_pg, shard_size))
567 if not active_axes:
568 return _early_return_tensors(local_tensors, keep_indices)
570 current_tensors: List[torch.Tensor] = list(local_tensors)
572 for active_pos, (axis_idx, tensor_dim, shard_pg, shard_size) in enumerate(active_axes):
573 is_last_axis = active_pos == len(active_axes) - 1
574 stage_metas: Optional[List[Optional[ParamShardStageMeta]]] = None
575 if param_shard_metadata is not None:
576 stage_metas = []
577 for meta in param_shard_metadata:
578 if meta is None or axis_idx >= len(meta.stage_metas):
579 stage_metas.append(None)
580 else:
581 stage_metas.append(meta.stage_metas[axis_idx])
583 gather_inputs, param_meta, total_padded_numel = _prepare_gather_inputs(
584 current_tensors, tensor_dim, alignment_elements, shard_size, stage_metas,
585 )
587 gathered_view = _pack_and_allgather(
588 gather_inputs, param_meta, total_padded_numel,
589 axis_idx, dtype, device, shard_pg, shard_size, buffer_cache, while_gathering,
590 )
592 new_tensors = _unpack_gathered_results(
593 gathered_view, gather_inputs, param_meta,
594 current_tensors, tensor_dim, is_last_axis, keep_indices, owner_buffer_cache,
595 )
597 if is_last_axis:
598 return new_tensors
600 current_tensors = new_tensors # type: ignore[assignment]
602 return current_tensors