Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / core / optimizer / optimizer.py: 72%
572 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"""Base distributed optimizer and chain optimizer composition."""
18from collections import defaultdict
19from contextlib import contextmanager, nullcontext
20import logging
21from typing import Any, Dict, Iterator, List, Optional, Tuple
23import torch
24import torch.distributed as dist
25from torch.distributed.checkpoint.state_dict import (
26 StateDictOptions,
27 get_optimizer_state_dict,
28 set_optimizer_state_dict,
29)
31from hyper_parallel.high_availability.group_registry import recovery_optimizer_subgroup
32from hyper_parallel.core.optimizer.dtensor_compat import to_local_if_dtensor
33from hyper_parallel.core.optimizer.parameter_views import OptimizerParameterViews
34from hyper_parallel.core.optimizer.sharding_category import (
35 HSDPGroupAssignment,
36 build_owner_by_size,
37 get_multi_dim_logical_info,
38 select_owned_records,
39 group_parameters_for_hsdp
40)
41from hyper_parallel.core.optimizer.swap_optimizer import is_swap_optimizer
42from hyper_parallel.core.optimizer.swap_optimizer_base import _restore_dtensor_metadata
43from hyper_parallel.core.optimizer.utils import empty_accelerator_cache, get_current_device, get_device_count
45logger = logging.getLogger(__name__)
48class ChainedOptimizer:
49 """Composition wrapper that dispatches step/zero_grad to sub-optimizers."""
51 def __init__(
52 self,
53 model: torch.nn.Module,
54 optimizers: Dict[str, torch.optim.Optimizer],
55 flatten: bool = False,
56 ) -> None:
57 """Compose named optimizers over registered model parameters.
59 Args:
60 model: Module containing the registered model parameters.
61 optimizers: Leaf optimizers keyed by their configured names.
62 flatten: Whether leaf optimizer state uses flattened FQN keys.
63 """
64 self.parameter_views: Optional[OptimizerParameterViews] = None
65 self.optimizers_dict = optimizers
66 self.chained_optimizers = list(optimizers.values())
67 self.optimizers_keys = list(optimizers.keys())
68 self.model = model
69 # DCP must distinguish parameter-group membership on disjoint pipeline stages.
70 self.flatten = flatten or getattr(model, "_hp_pipeline_partition", None) is not None
71 self._is_multi_optimizer = flatten
72 self.model_param_by_optimizer_param: Dict[
73 torch.nn.Parameter, torch.nn.Parameter
74 ] = {}
75 self.optimizer_param_by_model_param: Dict[
76 torch.nn.Parameter, torch.nn.Parameter
77 ] = {}
79 self._rebind_param_attrs()
81 def defer_parameter_binding(self) -> None:
82 """Defer parameter-dependent state until the physical graph shards exist."""
83 if self.parameter_views is None:
84 self.parameter_views = OptimizerParameterViews()
86 def bind_parameter_layouts(self, layouts: Optional[dict]) -> None:
87 """Provide logical layouts and valid shard extents for the optimizer.
89 Args:
90 layouts: Compiler layouts keyed by model parameter, or None for an unsharded graph.
91 """
92 if self.parameter_views is not None:
93 self.parameter_views.bind(self, layouts, fp32_main_params=False)
95 def __iter__(self) -> Iterator[torch.optim.Optimizer]:
96 """Allow iteration over the underlying optimizers."""
97 return iter(self.chained_optimizers)
99 def _rebind_param_attrs(self) -> None:
100 """Restore model FQNs and optimizer-family name views."""
101 muon_param_ids: set = set()
102 adamw_param_ids: set = set()
103 self.muon_keys = []
104 self.no_muon_keys = []
105 for _, opt in self.optimizers_dict.items():
106 is_muon = hasattr(opt, "is_muon") and opt.is_muon
107 target = muon_param_ids if is_muon else adamw_param_ids
108 for group in opt.param_groups:
109 for p in group.get("params", []):
110 target.add(id(p))
112 for param_name, param in self.model.named_parameters():
113 optimizer_param = self.optimizer_param_by_model_param.get(param, param)
114 setattr(param, "model_name", param_name)
115 setattr(optimizer_param, "model_name", param_name)
116 if id(optimizer_param) in muon_param_ids:
117 self.muon_keys.append(param_name)
118 elif id(optimizer_param) in adamw_param_ids:
119 self.no_muon_keys.append(param_name)
121 def reset_optimizer_parameters(
122 self,
123 model_param_by_optimizer_param: Dict[
124 torch.nn.Parameter, torch.nn.Parameter
125 ],
126 ) -> None:
127 """Register replaced optimizer params and rebuild identity-based metadata.
129 Args:
130 model_param_by_optimizer_param: Main-to-model parameter identity map.
131 """
132 self.model_param_by_optimizer_param = dict(
133 model_param_by_optimizer_param
134 )
135 self.optimizer_param_by_model_param = {
136 model_param: optimizer_param
137 for optimizer_param, model_param in self.model_param_by_optimizer_param.items()
138 }
139 self._rebind_param_attrs()
140 for optimizer in self.chained_optimizers:
141 reset = getattr(optimizer, "reset_optimizer_parameters", None)
142 if callable(reset):
143 if is_swap_optimizer(optimizer):
144 reset(self.model_param_by_optimizer_param)
145 else:
146 reset()
148 @contextmanager
149 def _optimizer_parameter_view(self) -> Iterator[None]:
150 """Temporarily register optimizer params under their model FQNs."""
151 if not self.model_param_by_optimizer_param:
152 yield
153 return
155 registrations = []
156 for module in self.model.modules():
157 for parameter_name, model_param in module._parameters.items(): # pylint: disable=protected-access
158 if model_param is None:
159 continue
160 optimizer_param = self.optimizer_param_by_model_param.get(model_param)
161 if optimizer_param is None:
162 continue
163 registrations.append((module, parameter_name, model_param))
164 module._parameters[parameter_name] = optimizer_param # pylint: disable=protected-access
165 try:
166 yield
167 finally:
168 for module, parameter_name, model_param in registrations:
169 module._parameters[parameter_name] = model_param # pylint: disable=protected-access
171 def __str__(self) -> str:
172 """Return each named leaf optimizer's representation."""
173 if not self.optimizers_dict:
174 return f'{self.__class__.__name__}'
176 sections = []
177 for name, optimizer in self.optimizers_dict.items():
178 sections.append(f'{name}: {repr(optimizer)}')
179 return "\n\n".join(sections)
181 __repr__ = __str__
183 def step(self, closure: Any = None) -> None:
184 """Call each sub-optimizer's step in order.
186 Args:
187 closure: Optional callable forwarded to every sub-optimizer.
188 """
189 if self.parameter_views is not None:
190 self.parameter_views.prepare_grads()
191 self.step_with_ready_grads(closure)
193 def step_with_ready_grads(self, closure: Any = None) -> None:
194 """Update all leaves after gradient transfer or precision conversion.
196 Args:
197 closure: Optional loss closure forwarded to each leaf.
198 """
199 for opt in self.chained_optimizers:
200 opt.step(closure=closure)
201 if self.parameter_views is not None:
202 self.parameter_views.clear_padding()
204 def zero_grad(self, set_to_none: bool = True) -> None:
205 """Clear gradients for all sub-optimizers.
207 Args:
208 set_to_none: Whether gradients are reset to ``None``.
209 """
210 for opt in self.chained_optimizers:
211 opt.zero_grad(set_to_none=set_to_none)
212 if self.parameter_views is not None:
213 self.parameter_views.clear_grads(set_to_none)
215 @property
216 def optimizer(self) -> torch.optim.Optimizer:
217 """Access underlying optimizer when only one optimizer included for backward compatibility."""
218 if len(self.chained_optimizers) != 1:
219 raise ValueError("ChainedOptimizer has more than one optimizer when accessing self.optimizer")
220 return self.chained_optimizers[0]
222 @property
223 def defaults(self) -> Dict[str, Any]:
224 """Return the defaults of the first sub-optimizer."""
225 return self.chained_optimizers[0].defaults
227 def state_dict(self) -> Dict[str, Any]:
228 """Return state dicts with owning checkpoint tensor copies.
230 In HSDP, optimizer state is only populated on the owner rank for replicated
231 parameters. This method first broadcasts state to all replicate-group peers,
232 then clones exported values while preserving every DTensor layout.
233 """
234 if self.parameter_views is not None:
235 self.parameter_views.require_bound()
236 prepared = []
237 try:
238 # Swap optimizers must restore released device storage before the
239 # wrapped HSDP implementation reads its state tensors.
240 for opt in self.chained_optimizers:
241 prepare = getattr(opt, "_prepare_swap_checkpoint", None)
242 if callable(prepare):
243 prepared.append(opt)
244 prepare()
246 # Ensure all ranks have consistent optimizer state before snapshotting.
247 for opt in self.chained_optimizers:
248 if hasattr(opt, "_broadcast_state_fused_for_ckpt"):
249 opt._broadcast_state_fused_for_ckpt() # pylint: disable=protected-access
251 merged: Dict[str, Any] = {}
252 for name, optimizer in self.optimizers_dict.items():
253 with self._optimizer_parameter_view():
254 sd = get_optimizer_state_dict(
255 self.model,
256 optimizer,
257 options=StateDictOptions(flatten_optimizer_state_dict=self.flatten)
258 )
259 if optimizer in prepared:
260 # The swap lifecycle releases device storage once the
261 # checkpoint window closes, so the exported values must own
262 # their memory instead of aliasing the slot tensors.
263 self._localize_state_dict_tensors(sd)
264 overlap = set(merged.keys()) & set(sd.keys())
265 if overlap:
266 raise KeyError(
267 f"Key clash detected while merging state dict for optimizer '{name}': "
268 f"{', '.join(sorted(overlap))}"
269 )
270 merged.update(sd)
272 return merged
273 finally:
274 for opt in reversed(prepared):
275 cleanup = getattr(opt, "cleanup_synced_state", None)
276 if callable(cleanup):
277 cleanup()
278 continue
279 finish = getattr(opt, "_finish_swap_checkpoint", None)
280 if callable(finish):
281 finish()
283 @staticmethod
284 def _localize_state_dict_tensors(state_dict: Dict[str, Any]) -> None:
285 """Replace exported tensors with owning copies that retain DTensor layouts.
287 Swap-managed optimizer state lives in CPU mirrors while its device
288 storage is released, so a checkpoint entry must not alias a tensor whose
289 storage the swap runtime is about to free.
290 """
291 def localize(value: Any) -> Any:
292 """Clone tensors in one nested checkpoint value.
294 Args:
295 value: Checkpoint value or nested container to localize.
297 Returns:
298 The value with owning tensor copies and unchanged DTensor metadata.
299 """
300 if isinstance(value, torch.Tensor):
301 local_copy = to_local_if_dtensor(value).detach().cpu().clone()
302 return _restore_dtensor_metadata(value, local_copy)
303 if isinstance(value, dict):
304 return {key: localize(item) for key, item in value.items()}
305 if isinstance(value, list):
306 return [localize(item) for item in value]
307 if isinstance(value, tuple):
308 return tuple(localize(item) for item in value)
309 return value
311 for key, value in list(state_dict.items()):
312 if key == "param_groups":
313 continue
314 state_dict[key] = localize(value)
316 def _get_param_groups(self) -> List[Dict[str, Any]]:
317 """Get param_groups aggregated over underlying optimizers."""
318 param_groups: List[Dict[str, Any]] = []
319 for optimizer in self.chained_optimizers:
320 param_groups += optimizer.param_groups
321 return param_groups
323 def _set_param_groups(self, new_param_groups: List[Dict[str, Any]]) -> None:
324 """Set param_groups distributed across underlying optimizers."""
325 if not isinstance(new_param_groups, list):
326 raise TypeError("new_param_groups should be a list")
327 if len(new_param_groups) != len(self.param_groups):
328 raise ValueError("The size of new_param_groups must be equal to origin param_groups")
330 start = 0
331 for optimizer in self.chained_optimizers:
332 group_len = len(optimizer.param_groups)
333 optimizer.param_groups = new_param_groups[start: start + group_len]
334 start += group_len
336 param_groups = property(_get_param_groups, _set_param_groups)
338 def load_state_dict(self, state_dict: Dict[str, Any]) -> None:
339 """Load optimizer state dicts and synchronize steps.
341 Args:
342 state_dict: FQN-keyed optimizer state to restore.
343 """
344 if self.parameter_views is not None:
345 self.parameter_views.require_bound()
346 for optimizer in self.chained_optimizers:
347 load_context = getattr(optimizer, "_swap_checkpoint_load_context", None)
348 context = load_context(state_dict, self.flatten) if callable(load_context) else nullcontext()
349 with self._optimizer_parameter_view(), context:
350 set_optimizer_state_dict(
351 self.model,
352 optimizer,
353 optim_state_dict=state_dict,
354 options=StateDictOptions(flatten_optimizer_state_dict=self.flatten),
355 )
357 self._synchronize_steps()
359 def _synchronize_steps(self) -> Optional[int]:
360 """Synchronize the step of all optimizers.
362 Transformer Engine FusedAdam will not accumulate "step" for empty param groups,
363 so we need to align the step across param groups before saving and after loading.
364 """
365 steps = []
366 for optimizer in self.chained_optimizers:
367 actual_opt = getattr(optimizer, 'optimizer', optimizer)
368 for param_group in actual_opt.param_groups:
369 if len(param_group['params']) > 0 and 'step' in param_group:
370 steps.append(param_group['step'])
372 unique_steps = list(set(steps))
373 if len(unique_steps) > 1:
374 raise ValueError(f"steps should <= 1, but got {unique_steps}")
376 step = unique_steps[0] if len(unique_steps) == 1 else None
378 for optimizer in self.chained_optimizers:
379 actual_opt = getattr(optimizer, 'optimizer', optimizer)
380 for param_group in actual_opt.param_groups:
381 param_group['step'] = step
383 return step
386class BaseDistributedOptimizer(torch.optim.Optimizer):
387 """Base class for distributed optimizers with HSDP-aware topology communication.
389 Provides fused hierarchical broadcast for parameters and optimizer states.
390 """
392 def __init__(
393 self,
394 params: Any,
395 defaults: Dict[str, Any],
396 is_muon: bool,
397 hsdp_replica_count: Optional[int] = None,
398 ) -> None:
399 """Initialize topology-aware optimizer state and parameter groups.
401 Args:
402 params: Parameter groups optimized by this instance.
403 defaults: Default hyperparameters applied to every group.
404 is_muon: Whether parameters use the Muon update path.
405 hsdp_replica_count: Optional optimizer-state replica group size.
406 """
407 super().__init__(params, defaults)
408 self.is_muon = is_muon
409 self.hsdp_replica_count = hsdp_replica_count
410 self._param_to_broadcast_info: Dict[
411 torch.nn.Parameter, Tuple[Tuple[int, ...], Tuple[dist.ProcessGroup, ...]]
412 ] = {}
414 # Cache: (parent_ranks_tuple, sub_size) -> {sub_idx: sub_pg}
415 self._split_sub_pg_cache: Dict[Tuple[Tuple[int, ...], int], Dict[int, dist.ProcessGroup]] = {}
417 def _group_dtensor_by_mesh(self):
418 """Group DTensor parameters by mesh topology and shard layout."""
419 self._hsdp_grouping: Dict[int, Tuple[List, List]] = {}
420 for group_key, group in enumerate(self.param_groups):
421 no_comm_params, hsdp_groups = group_parameters_for_hsdp(group["params"])
422 self._hsdp_grouping[group_key] = (no_comm_params, hsdp_groups)
424 def reset_optimizer_parameters(self) -> None:
425 """Rebuild subclass metadata after optimizer parameters are replaced."""
426 raise NotImplementedError
428 def _auto_deduce_replica_count(self) -> Optional[int]:
429 """Deduce hsdp_replica_count based on cluster topology.
431 - Intra-node PGs: Full dedup (no split), high bandwidth makes broadcast cheap.
432 - Inter-node PGs: Split at node boundaries to restrict communication domains
433 within a single node, bypassing cross-node bottlenecks.
434 """
435 devices_per_node = get_device_count()
437 dedup_per_dim: Dict[int, int] = {}
438 needs_split = False
440 # group_key, (no_comm_params, hsdp_groups)
441 for _, (_, hsdp_groups) in self._hsdp_grouping.items():
442 for hsdp_group in hsdp_groups:
443 for dim_idx, pg in enumerate(hsdp_group.replicate_pgs):
444 if pg is None:
445 continue
446 pg_size = dist.get_world_size(pg)
447 if pg_size <= 1:
448 continue
450 if pg_size > devices_per_node:
451 # Inter-node: Find largest divisor safe for node boundary
452 dedup = min(pg_size, devices_per_node)
453 while pg_size % dedup != 0:
454 dedup -= 1
455 needs_split = True
456 else:
457 # origin Inter-node
458 dedup = pg_size
460 # Enforce conservative (smallest) dedup across shared mesh axes
461 if dim_idx not in dedup_per_dim:
462 dedup_per_dim[dim_idx] = dedup
463 else:
464 dedup_per_dim[dim_idx] = min(dedup_per_dim[dim_idx], dedup)
466 if not needs_split:
467 return None
469 sorted_dedups = [dedup_per_dim[k] for k in sorted(dedup_per_dim.keys())]
470 return min(sorted_dedups)
472 def _split_replicate_groups(self) -> None:
473 """Split replicate ProcessGroups into smaller sub-groups based on hsdp_replica_count."""
474 if self.hsdp_replica_count is None:
475 return
477 # Argument validation
478 if not isinstance(self.hsdp_replica_count, int):
479 raise TypeError(f"Unsupported hsdp_replica_count type: {type(self.hsdp_replica_count).__name__}")
480 if self.hsdp_replica_count <= 0:
481 raise ValueError(f"hsdp_replica_count must be positive, got {self.hsdp_replica_count}")
483 for group_key, (_, hsdp_groups) in self._hsdp_grouping.items():
484 for hsdp_group in hsdp_groups:
485 new_replicate_pgs: List[dist.ProcessGroup] = []
486 for dim_idx, pg in enumerate(hsdp_group.replicate_pgs):
487 if pg is None:
488 new_replicate_pgs.append(pg)
489 continue
491 pg_size = dist.get_world_size(pg)
492 dedup_size = self.hsdp_replica_count
494 if pg_size <= dedup_size:
495 new_replicate_pgs.append(pg)
496 continue
498 if pg_size % dedup_size != 0:
499 raise ValueError(
500 f"hsdp_replica_count {dedup_size} must evenly divide replicate group size {pg_size}"
501 )
503 sub_pg = self._get_or_create_sub_pg(pg, dedup_size)
504 new_replicate_pgs.append(sub_pg)
506 logger.info_rank0(
507 "[HSDP Split] group_key=%s, dim_idx=%s, original_size=%s, sub_size=%s",
508 group_key, dim_idx, pg_size, dedup_size
509 )
511 # replace new sub groups of hsdp groups
512 hsdp_group.replicate_pgs = tuple(new_replicate_pgs)
514 def _get_or_create_sub_pg(
515 self,
516 parent_pg: dist.ProcessGroup,
517 sub_size: int,
518 ) -> dist.ProcessGroup:
519 """Retrieve or collectively create a synchronized sub-ProcessGroup."""
520 recovery_group = recovery_optimizer_subgroup(parent_pg, sub_size)
521 if recovery_group is not None:
522 parent_ranks = tuple(sorted(dist.get_process_group_ranks(parent_pg)))
523 self._split_sub_pg_cache[(parent_ranks, sub_size)] = {0: recovery_group}
524 return recovery_group
525 local_parent_ranks = tuple(sorted(list(dist.get_process_group_ranks(parent_pg))))
526 cache_key = (local_parent_ranks, sub_size)
528 # Cache Hit Check
529 if cache_key in self._split_sub_pg_cache:
530 sub_pg_map = self._split_sub_pg_cache[cache_key]
531 for sub_pg in sub_pg_map.values():
532 if sub_pg is not None:
533 try:
534 dist.get_rank(group=sub_pg)
535 return sub_pg
536 except RuntimeError:
537 continue
538 raise RuntimeError(f"Current rank not found in cached sub-groups for parent_pg={local_parent_ranks}")
540 global_rank = dist.get_rank()
541 world_size = dist.get_world_size()
543 # Global Rendezvous via GPU all_gather_into_tensor (NCCL/HCCL fast-path).
544 # Far more scalable than all_gather_object for large world_size.
545 device = get_current_device()
546 num_parent_ranks = len(local_parent_ranks)
547 local_tensor = torch.tensor(local_parent_ranks, dtype=torch.long, device=device)
548 gathered_tensor = torch.empty((world_size, num_parent_ranks), dtype=torch.long, device=device)
549 dist.all_gather_into_tensor(gathered_tensor.view(-1), local_tensor)
551 # Deduplicate: each row is one rank's parent_ranks; convert to
552 # sorted set of tuples for deterministic iteration order.
553 gathered_cpu_list = gathered_tensor.cpu().tolist()
554 unique_all_parent_ranks = sorted(set(
555 tuple(row) for row in gathered_cpu_list
556 ))
558 sub_pg_map: Dict[int, dist.ProcessGroup] = {}
559 my_sub_pg: Optional[dist.ProcessGroup] = None
561 # Synchronized collective creation loop
562 for parent_ranks in unique_all_parent_ranks:
563 num_sub_groups = len(parent_ranks) // sub_size
565 for sub_idx in range(num_sub_groups):
566 sub_ranks = parent_ranks[sub_idx * sub_size: (sub_idx + 1) * sub_size]
567 sub_pg = dist.new_group(sub_ranks)
569 # Map results only if this parent ranks list matches the current rank's context
570 if parent_ranks == local_parent_ranks:
571 if global_rank in sub_ranks:
572 my_sub_pg = sub_pg
573 sub_pg_map[sub_idx] = sub_pg
574 else:
575 sub_pg_map[sub_idx] = None
577 self._split_sub_pg_cache[cache_key] = sub_pg_map
579 if my_sub_pg is None:
580 raise RuntimeError(
581 f"Rank {global_rank} not found in any sub-group of parent_pg "
582 f"with ranks {local_parent_ranks} and sub_size={sub_size}"
583 )
585 return my_sub_pg
587 def _build_hsdp_batch(
588 self,
589 max_batch_numel: Optional[int] = None,
590 ) -> None:
591 """Split HSDP groups into memory-capped batches for compute-broadcast overlap."""
592 if max_batch_numel is None:
593 broadcast_max_bytes = getattr(
594 self, "replicate_broadcast_max_bytes", 512 * 1024 * 1024,
595 )
596 hsdp_size = self.hsdp_replica_count if self.hsdp_replica_count is not None else 1
597 max_batch_numel = broadcast_max_bytes * hsdp_size # if hsdp_size > 1 else float('inf')
599 self._hsdp_batches: Dict[int, List[Dict]] = {}
601 for group_key, (_, hsdp_groups) in self._hsdp_grouping.items():
602 # Sort groups by total numel descending — large groups first.
603 sorted_groups = sorted(
604 hsdp_groups,
605 key=lambda g: -sum(r.param.numel() for r in g.records),
606 )
608 batch_groups: List[Dict] = []
610 for hsdp_group in sorted_groups:
611 # Sort records within group by numel descending.
612 sorted_records = sorted(
613 hsdp_group.records,
614 key=lambda r: -r.param.numel(),
615 )
617 sub_batches: List[List[Dict]] = []
618 current_batch: List[Dict] = []
619 current_numel = 0
621 for record in sorted_records:
622 p_numel = record.param.numel()
624 current_batch.append({
625 "record": record,
626 "hsdp_group": hsdp_group,
627 })
628 current_numel += p_numel
630 # Soft limit: allow the bucket to slightly exceed the cap
631 # so that symmetric structures stay together and fragmentation is reduced.
632 if current_numel >= max_batch_numel:
633 sub_batches.append(current_batch)
634 current_batch = []
635 current_numel = 0
637 if current_batch:
638 sub_batches.append(current_batch)
640 # Sort sub-batches by numel descending within this group.
641 sub_batches.sort(key=lambda b: -sum(e["record"].param.numel() for e in b))
643 batch_groups.append({
644 "hsdp_group": hsdp_group,
645 "sub_batches": sub_batches,
646 })
648 # log batch split info.
649 total_sub_batches = sum(len(bg["sub_batches"]) for bg in batch_groups)
650 logger.info_rank0(
651 "[HSDP Batch] group_key=%s, num_hsdp_groups=%s, num_batch_groups=%s, "
652 "total_sub_batches=%s, group_numels=%s, max_batch_numel=%s",
653 group_key,
654 len(hsdp_groups),
655 len(batch_groups),
656 total_sub_batches,
657 [sum(bg['hsdp_group'].records_numel) if hasattr(bg['hsdp_group'], 'records_numel') else sum(
658 r.param.numel() for r in bg['hsdp_group'].records) for bg in batch_groups],
659 max_batch_numel
660 )
661 self._hsdp_batches[group_key] = batch_groups
663 def _build_sub_batch_assignment(
664 self,
665 sub_batch_entries: List[Dict],
666 hsdp_group: Any,
667 ) -> Optional[HSDPGroupAssignment]:
668 """Build an HSDPGroupAssignment for one sub-batch and update broadcast info."""
669 records = [e["record"] for e in sub_batch_entries]
670 if not records:
671 return None
673 device_mesh = records[0].param.device_mesh
675 replicate_group_ranks, replicate_sizes = get_multi_dim_logical_info(
676 device_mesh,
677 hsdp_group.comm_key.replicate_mesh_dims,
678 )
680 # When hsdp_replica_count is set, remap coordinates into
681 # sub-groups: each original coord maps to (coord % sub_size)
682 # within its sub-group, and the effective group size shrinks.
683 if self.hsdp_replica_count is not None:
684 replicate_group_ranks = tuple(
685 r % self.hsdp_replica_count for r in replicate_group_ranks
686 )
687 replicate_sizes = tuple(
688 min(s, self.hsdp_replica_count) for s in replicate_sizes
689 )
691 # Greedy owner assignment on this sub-batch's records.
692 owner_by_index = build_owner_by_size(
693 records=records,
694 replicate_sizes=replicate_sizes,
695 )
697 owned_records = select_owned_records(
698 records=records,
699 owner_by_index=owner_by_index,
700 replicate_group_ranks=replicate_group_ranks,
701 )
703 is_shard_for_ns = (
704 hsdp_group.comm_key.has_shard_group
705 and hsdp_group.layout_spec.is_last2d_sharded
706 )
708 hsdp_assign = HSDPGroupAssignment(
709 owned_records=owned_records,
710 all_records=records,
711 owner_by_index=owner_by_index,
712 replicate_group_ranks=replicate_group_ranks,
713 replicate_sizes=replicate_sizes,
714 replicate_pgs=hsdp_group.replicate_pgs,
715 shard_pgs=hsdp_group.shard_pgs,
716 is_shard=is_shard_for_ns,
717 layout_spec=hsdp_group.layout_spec,
718 )
719 logger.debug_rank0(f'[Hyper-optimizer] hsdp_assign: {hsdp_assign}')
721 # Build broadcast reverse mapping for replicated groups
722 if hsdp_assign.is_replicated and hsdp_assign.replicate_pgs:
723 for record in hsdp_assign.all_records:
724 src_coord = hsdp_assign.owner_rank_coord(record)
725 if not src_coord or any(c < 0 for c in src_coord):
726 continue
727 self._param_to_broadcast_info[record.param] = (
728 src_coord, hsdp_assign.replicate_pgs,
729 )
731 return hsdp_assign
733 def _build_param_broadcast_info(self) -> None:
734 """Build per-batch HSDP assignments and param broadcast reverse mapping.
736 When ``hsdp_replica_count`` is set, replicate coordinates and sizes
737 are remapped so that owner assignment and broadcast happen within
738 sub-groups of size ``hsdp_replica_count`` instead of the full
739 replicate group.
741 Sub-group broadcast already covers all ranks (each rank belongs to
742 exactly one sub-group), so param and state broadcast use the same
743 sub-group mapping — no separate full-group path is needed.
744 """
745 self._hsdp_assignment_batches: Dict[int, Dict] = {}
746 self._param_to_broadcast_info: Dict[
747 torch.nn.Parameter, Tuple[Tuple[int, ...], Tuple[dist.ProcessGroup, ...]]
748 ] = {}
750 for group_key, batch_groups in self._hsdp_batches.items():
751 no_comm_params = self._hsdp_grouping[group_key][0]
752 assignment_batch_groups = []
754 for bg in batch_groups:
755 hsdp_group = bg["hsdp_group"]
756 sub_batch_assigns: List[HSDPGroupAssignment] = []
758 for sub_batch_entries in bg["sub_batches"]:
759 hsdp_assign = self._build_sub_batch_assignment(sub_batch_entries, hsdp_group)
760 if hsdp_assign is not None:
761 sub_batch_assigns.append(hsdp_assign)
763 assignment_batch_groups.append({
764 "hsdp_group": hsdp_group,
765 "sub_batches": sub_batch_assigns,
766 })
768 self._hsdp_assignment_batches[group_key] = {
769 "no_comm": no_comm_params,
770 "batch_groups": assignment_batch_groups,
771 }
773 def _broadcast_replicate_params_after_step(self) -> None:
774 """Broadcast updated params from assigned rank to replicate-group peers."""
775 self._broadcast_op_fused(target="param")
777 def _broadcast_state_fused_for_ckpt(self) -> None:
778 """Broadcast optimizer state before checkpoint save."""
779 self._broadcast_op_fused(
780 target="state",
781 state_keys=list(self._state_keys_for_checkpoint_broadcast()),
782 )
784 def _state_keys_for_checkpoint_broadcast(self) -> Tuple[str, ...]:
785 """Return optimizer state fields synchronized for an HSDP checkpoint."""
786 return ("momentum_buffer",) if self.is_muon else ("exp_avg", "exp_avg_sq")
788 def _collect_broadcast_tensors(
789 self,
790 target: str,
791 state_keys: Optional[List[str]] = None,
792 ) -> Dict[Tuple, List[torch.Tensor]]:
793 """Collect tensors to broadcast, grouped by (src_coord, dtype, replicate_pgs).
795 Args:
796 target: "param" or "state".
797 state_keys: State dict keys to broadcast when target="state".
799 Returns:
800 Dict mapping (src_coord, dtype, replicate_pgs) to list of local tensors.
801 """
802 rank_dtype_tensors = defaultdict(list)
804 for p, (src_coord, replicate_pgs) in self._param_to_broadcast_info.items():
805 if target == "param":
806 local_tensor = to_local_if_dtensor(p.data)
807 rank_dtype_tensors[(src_coord, local_tensor.dtype, replicate_pgs)].append(local_tensor)
809 elif target == "state" and state_keys:
810 param_state = self.state.setdefault(p, {})
811 for key in state_keys:
812 if key not in param_state:
813 # Muon initializes owner state from its gradient, which has the parameter dtype.
814 param_state[key] = torch.empty_like(p)
815 state_tensor = param_state[key]
816 local_tensor = to_local_if_dtensor(state_tensor)
817 if local_tensor is state_tensor:
818 # State initialized with dispatch disabled can be a plain local shard.
819 param_state[key] = _restore_dtensor_metadata(p, local_tensor)
820 rank_dtype_tensors[(src_coord, local_tensor.dtype, replicate_pgs)].append(local_tensor)
822 return rank_dtype_tensors
824 @staticmethod
825 def _compute_broadcast_batches(
826 tensors: List[torch.Tensor],
827 alignment_elements: int,
828 max_broadcast_elements: int
829 ) -> List[Tuple[List[Tuple[torch.Tensor, int, int, int]], int]]:
830 """Split tensors into memory-capped batches with alignment padding.
832 Args:
833 tensors: List of tensors to batch.
834 alignment_elements: Alignment granularity in elements.
835 max_broadcast_elements: Maximum elements per batch.
837 Returns:
838 List of (batch_offsets, batch_total_size) tuples.
839 Each batch_offsets entry is (tensor, offset, actual_numel, padded_numel).
840 """
841 batches = []
842 current_batch = []
843 current_total_size = 0
845 for t in tensors:
846 actual_numel = t.numel()
847 padded_numel = ((actual_numel + alignment_elements - 1) // alignment_elements) * alignment_elements
849 if current_batch and current_total_size + padded_numel > max_broadcast_elements:
850 batches.append((current_batch, current_total_size))
851 current_batch = []
852 current_total_size = 0
854 current_batch.append((t, current_total_size, actual_numel, padded_numel))
855 current_total_size += padded_numel
857 if current_batch:
858 batches.append((current_batch, current_total_size))
860 return batches
862 @staticmethod
863 def _hierarchical_broadcast_buffer(
864 batch_buffer: torch.Tensor,
865 src_coord: Tuple[int, ...],
866 replicate_pgs: Tuple[dist.ProcessGroup, ...],
867 local_coord: Tuple[int, ...]
868 ) -> None:
869 """Broadcast a buffer dimension-by-dimension across replicate groups.
871 Args:
872 batch_buffer: Contiguous buffer to broadcast.
873 src_coord: Source coordinate tuple.
874 replicate_pgs: Tuple of ProcessGroups (one per dimension).
875 local_coord: Local rank coordinate tuple.
876 """
878 for dim_idx, pg in enumerate(replicate_pgs):
879 if pg is None:
880 continue
882 participate = True
883 for subsequent_dim in range(dim_idx + 1, len(replicate_pgs)):
884 if local_coord[subsequent_dim] != src_coord[subsequent_dim]:
885 participate = False
886 break
888 if not participate:
889 continue
891 src_rank_in_pg = src_coord[dim_idx]
892 global_src_rank = dist.get_global_rank(pg, src_rank_in_pg)
893 dist.broadcast(batch_buffer, src=global_src_rank, group=pg)
895 @staticmethod
896 def _hierarchical_broadcast_buffer_async(
897 batch_buffer: torch.Tensor,
898 src_coord: Tuple[int, ...],
899 replicate_pgs: Tuple[dist.ProcessGroup, ...],
900 local_coord: Tuple[int, ...],
901 ) -> List[dist.Work]:
902 """Async version of _hierarchical_broadcast_buffer.
904 Same dimension-by-dimension relay logic, but each dist.broadcast uses
905 async_op=True. Returns a list of Work handles to wait on later.
907 Note: dimensions within a single buffer are still sequential (dim N+1
908 depends on dim N completing), but different buffers can overlap.
909 """
910 broadcast_ops: List[Tuple[dist.ProcessGroup, int]] = []
912 for dim_idx, pg in enumerate(replicate_pgs):
913 if pg is None:
914 continue
916 participate = True
917 for subsequent_dim in range(dim_idx + 1, len(replicate_pgs)):
918 if local_coord[subsequent_dim] != src_coord[subsequent_dim]:
919 participate = False
920 break
922 if not participate:
923 continue
925 src_rank_in_pg = src_coord[dim_idx]
926 global_src_rank = dist.get_global_rank(pg, src_rank_in_pg)
927 broadcast_ops.append((pg, global_src_rank))
929 handles: List[dist.Work] = []
930 for op_idx, (pg, global_src_rank) in enumerate(broadcast_ops):
931 handle = dist.broadcast(
932 batch_buffer, src=global_src_rank, group=pg, async_op=True,
933 )
934 if op_idx + 1 < len(broadcast_ops):
935 # The next mesh dimension relays the data received here.
936 # It must not read the shared buffer until this hop finishes.
937 handle.wait()
938 else:
939 # Only the final hop may overlap with subsequent computation.
940 handles.append(handle)
942 return handles
944 def _broadcast_op_fused(
945 self,
946 target: str,
947 state_keys: Optional[List[str]] = None,
948 ) -> None:
949 """Fused hierarchical broadcast for param or state across replicate groups.
951 Groups tensors by (src_coord, dtype, replicate_pgs), packs into contiguous device buffers
952 with 512-byte alignment, and broadcasts dimension-by-dimension in memory-capped batches.
953 State tensors may be CPU swap mirrors; only the current fused buffer is then resident on
954 the accelerator while packing and unpacking each batch.
956 Args:
957 target: "param" or "state".
958 state_keys: State dict keys to broadcast when target="state".
959 """
960 device = get_current_device()
962 alignment = 512 # bytes
963 rank_dtype_tensors = self._collect_broadcast_tensors(target, state_keys)
965 for (src_coord, dtype, replicate_pgs), tensors in rank_dtype_tensors.items():
966 if not tensors:
967 continue
969 local_coord = tuple(
970 dist.get_rank(group=pg) if pg is not None else -1
971 for pg in replicate_pgs
972 )
974 element_size = torch.empty(0, dtype=dtype, device=device).element_size()
975 alignment_elements = alignment // element_size
976 max_broadcast_bytes = getattr(self, "replicate_broadcast_max_bytes", 512 * 1024 * 1024)
977 max_broadcast_elements = max_broadcast_bytes // element_size
978 max_broadcast_elements = max(
979 alignment_elements,
980 (max_broadcast_elements // alignment_elements) * alignment_elements,
981 )
983 batches = self._compute_broadcast_batches(tensors, alignment_elements, max_broadcast_elements)
984 if not batches:
985 continue
987 max_batch_size = max(batch_size for _, batch_size in batches)
988 buffer = torch.empty(max_batch_size, dtype=dtype, device=device)
990 for batch_tensor_offsets, batch_total_size in batches:
991 batch_buffer = buffer[:batch_total_size]
993 # Pack: owner rank
994 if local_coord == src_coord:
995 for t, offset, actual_numel, padded_numel in batch_tensor_offsets:
996 batch_buffer[offset:offset + actual_numel].copy_(t.view(-1))
997 if padded_numel > actual_numel:
998 batch_buffer[offset + actual_numel:offset + padded_numel].zero_()
1000 # Hierarchical Broadcast
1001 self._hierarchical_broadcast_buffer(batch_buffer, src_coord, replicate_pgs, local_coord)
1003 # Unpack: copy buffer data back to individual tensors
1004 for t, offset, actual_numel, _ in batch_tensor_offsets:
1005 t.view(-1).copy_(batch_buffer[offset:offset + actual_numel])
1007 buffer.untyped_storage().resize_(0)
1008 del buffer
1010 def cleanup_synced_state(self) -> None:
1011 """Release optimizer state for non-owned params after checkpoint saving.
1013 In HSDP mode, _broadcast_state_fused_for_ckpt broadcasts state to all
1014 ranks so every rank can save a complete checkpoint. This method removes
1015 the non-owned state to restore per-rank memory savings. Call once all
1016 checkpoint consumers have finished reading the live state, either after
1017 persistence or after creating an independent snapshot for async I/O.
1018 """
1019 params_to_remove = []
1020 for assignment_info in self._hsdp_assignment_batches.values():
1021 for bg in assignment_info["batch_groups"]:
1022 for hsdp_info in bg["sub_batches"]:
1023 if not hsdp_info.is_replicated:
1024 continue
1025 for record in hsdp_info.all_records:
1026 # Records without an owner are never broadcast, so their state is not a replica copy.
1027 if record.index not in hsdp_info.owner_by_index:
1028 continue
1029 if not hsdp_info.is_owned(record) and record.param in self.state:
1030 params_to_remove.append(record.param)
1032 for p in params_to_remove:
1033 self.state[p].clear()
1034 del self.state[p]
1036 empty_accelerator_cache()
1039class AsyncReplicateBroadcaster:
1040 """Incremental async replicate broadcast with HSDP-group-level flushing.
1042 Designed to overlap HSDP replicate-group broadcasts with Muon NS
1043 computation. After all sub_batches for an HSDP group are done, the
1044 caller invokes flush_group(hsdp_assign) to issue an async hierarchical
1045 broadcast — overlapping with the next HSDP group's NS computation.
1047 Flush is driven by the caller at HSDP-group boundaries (not by a
1048 threshold) so that all ranks issue the same collective operations in
1049 the same order, which is required by NCCL/HCCL.
1051 Usage::
1053 broadcaster = AsyncReplicateBroadcaster(optimizer)
1054 for hsdp_assign in hsdp_assignments:
1055 # ... NS compute + apply for this group ...
1056 broadcaster.flush_group(hsdp_assign)
1057 broadcaster.wait_all()
1058 """
1060 def __init__(
1061 self,
1062 optimizer: BaseDistributedOptimizer,
1063 ) -> None:
1064 """Bind the distributed optimizer whose broadcasts are batched.
1066 Args:
1067 optimizer: Distributed optimizer owning the replica assignments.
1068 """
1069 self._optimizer = optimizer
1071 # Inflight async broadcasts: list of (buffer, batch_offsets, handles)
1072 # Buffer must stay alive until handles are waited on.
1073 self._inflight: List[
1074 Tuple[
1075 torch.Tensor,
1076 List[Tuple[torch.Tensor, int, int, int]],
1077 List[dist.Work],
1078 ]
1079 ] = []
1080 # Allow one batch of replicate communication to overlap with the
1081 # next batch's compute, but avoid unbounded inflight buffer growth.
1082 self._max_inflight_batches = 1
1084 def flush_group(
1085 self,
1086 hsdp_assign: Any,
1087 records: Optional[List] = None,
1088 ) -> None:
1089 """Flush params belonging to the given HSDP group.
1091 Can be called per sub_batch (passing only the records in that
1092 sub_batch) so that the async replicate broadcast overlaps with
1093 the next sub_batch's NS computation. When *records* is None,
1094 all records in the group are flushed (backward compatible).
1096 All ranks must call this at the same point in the execution flow
1097 to ensure collective communication consistency.
1099 Args:
1100 hsdp_assign: Assignment defining the replica groups and owners.
1101 records: Optional subset of parameter records to broadcast.
1102 """
1103 if not hsdp_assign.is_replicated or not hsdp_assign.replicate_pgs:
1104 return
1106 flush_records = records if records is not None else hsdp_assign.all_records
1108 # Collect local tensors for the given records, grouped by
1109 # (src_coord, dtype, replicate_pgs) — same logic as
1110 # _collect_broadcast_tensors but scoped to the provided records.
1111 rank_dtype_tensors: Dict[
1112 Tuple[Tuple[int, ...], torch.dtype, Tuple[dist.ProcessGroup, ...]],
1113 List[torch.Tensor],
1114 ] = defaultdict(list)
1116 for record in flush_records:
1117 src_coord = hsdp_assign.owner_rank_coord(record)
1118 if not src_coord or any(c < 0 for c in src_coord):
1119 continue
1120 local_tensor = to_local_if_dtensor(record.param.data)
1121 key = (src_coord, local_tensor.dtype, hsdp_assign.replicate_pgs)
1122 rank_dtype_tensors[key].append(local_tensor)
1124 for key, tensors in rank_dtype_tensors.items():
1125 if tensors:
1126 self._flush_key(key, tensors, async_op=True)
1128 while len(self._inflight) > self._max_inflight_batches:
1129 self._wait_and_release_oldest()
1131 @staticmethod
1132 def _unpack_batch(buffer: torch.Tensor, offsets: List[Tuple[torch.Tensor, int, int, int]]) -> None:
1133 """Copy completed replica broadcasts back to the corresponding parameter shards."""
1134 for tensor, offset, numel, _ in offsets:
1135 tensor.view(-1).copy_(buffer[offset:offset + numel])
1137 def _flush_key(
1138 self,
1139 key: Tuple[Tuple[int, ...], torch.dtype, Tuple[dist.ProcessGroup, ...]],
1140 tensors: List[torch.Tensor],
1141 async_op: bool = True,
1142 ) -> None:
1143 """Pack and broadcast tensors for one broadcast key."""
1144 device = get_current_device()
1145 src_coord, dtype, replicate_pgs = key
1146 alignment = 512 # bytes
1148 local_coord = tuple(
1149 dist.get_rank(group=pg) if pg is not None else -1
1150 for pg in replicate_pgs
1151 )
1153 element_size = torch.empty(0, dtype=dtype, device=device).element_size()
1154 alignment_elements = alignment // element_size
1155 max_broadcast_bytes = getattr(
1156 self._optimizer, "replicate_broadcast_max_bytes", 512 * 1024 * 1024,
1157 )
1158 max_broadcast_elements = max_broadcast_bytes // element_size
1159 max_broadcast_elements = max(
1160 alignment_elements,
1161 (max_broadcast_elements // alignment_elements) * alignment_elements,
1162 )
1164 # pylint: disable=protected-access
1165 batches = BaseDistributedOptimizer._compute_broadcast_batches(
1166 tensors, alignment_elements, max_broadcast_elements,
1167 )
1168 if not batches:
1169 return
1171 buffer: torch.Tensor
1172 if not async_op:
1173 max_batch_size = max(batch_size for _, batch_size in batches)
1174 buffer = torch.empty(max_batch_size, dtype=dtype, device=device)
1176 for batch_tensor_offsets, batch_total_size in batches:
1177 if async_op:
1178 batch_buffer = torch.empty(batch_total_size, dtype=dtype, device=device)
1179 else:
1180 batch_buffer = buffer[:batch_total_size]
1182 # Pack: owner rank
1183 if local_coord == src_coord:
1184 for t, offset, actual_numel, padded_numel in batch_tensor_offsets:
1185 batch_buffer[offset:offset + actual_numel].copy_(t.view(-1))
1186 if padded_numel > actual_numel:
1187 batch_buffer[offset + actual_numel:offset + padded_numel].zero_()
1189 if async_op:
1190 handles = BaseDistributedOptimizer._hierarchical_broadcast_buffer_async(
1191 batch_buffer, src_coord, replicate_pgs, local_coord,
1192 )
1193 if handles:
1194 # Pin buffer + offsets until wait_all unpacks them.
1195 self._inflight.append((batch_buffer, batch_tensor_offsets, handles))
1196 else:
1197 # No async work was enqueued on this rank, so unpack and free now.
1198 self._unpack_batch(batch_buffer, batch_tensor_offsets)
1199 batch_buffer.untyped_storage().resize_(0)
1200 del batch_buffer
1201 else:
1202 BaseDistributedOptimizer._hierarchical_broadcast_buffer(
1203 batch_buffer, src_coord, replicate_pgs, local_coord,
1204 )
1205 # Unpack immediately for sync path
1206 self._unpack_batch(batch_buffer, batch_tensor_offsets)
1208 if not async_op:
1209 # Sync path: buffer can be freed immediately
1210 buffer.untyped_storage().resize_(0)
1211 del buffer
1213 def _wait_and_release_oldest(self) -> None:
1214 """Wait, unpack, and release the oldest inflight async batch."""
1215 batch_buffer, batch_tensor_offsets, handles = self._inflight.pop(0)
1216 for handle in handles:
1217 handle.wait()
1219 # Unpack after the async broadcast completes.
1220 self._unpack_batch(batch_buffer, batch_tensor_offsets)
1222 batch_buffer.untyped_storage().resize_(0)
1223 del batch_buffer
1225 def wait_all(self) -> None:
1226 """Wait for all inflight async broadcasts and unpack results."""
1227 while self._inflight:
1228 self._wait_and_release_oldest()