Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / core / optimizer / muon.py: 74%

817 statements  

« 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# ============================================================================ 

15 

16"""Muon optimizer with HSDP shard-group-aware communication.""" 

17 

18import math 

19from collections import defaultdict, deque 

20from collections.abc import Callable, Iterable, Iterator 

21from dataclasses import dataclass, field 

22from functools import partial 

23from itertools import chain, groupby 

24import logging 

25from typing import Any, Deque, Dict, List, Optional, Sequence, Tuple, Union 

26 

27import torch 

28import torch.distributed as dist 

29 

30from hyper_parallel.high_availability.group_registry import is_recovery_bootstrapping 

31from hyper_parallel.core.optimizer.optimizer import AsyncReplicateBroadcaster, BaseDistributedOptimizer 

32from hyper_parallel.core.optimizer.dtensor_compat import to_local_if_dtensor 

33from hyper_parallel.core.optimizer.sharding_category import ( 

34 HSDPGroupAssignment, 

35 ParamShardMeta, 

36 build_owner_by_size, 

37) 

38from hyper_parallel.core.optimizer.muon_shard import ( 

39 _comm_device_for_group, 

40 _debug_param_shard_metadata, 

41 build_pad_ns_inputs, 

42 build_param_shard_metadata_for_group, 

43 chunk_update_by_layout, 

44 fused_allgather_dtensor_params, 

45 get_or_alloc_buffer, 

46) 

47 

48logger = logging.getLogger(__name__) 

49 

50 

51# Legacy: single-coefficient quintic NS (Keller Jordan / Moonlight). 

52# Same (a, b, c) applied every step; typically 5 steps. 

53_NS_LEGACY_COEFFS: Tuple[float, float, float] = (3.4445, -4.7750, 2.0315) 

54 

55# Asym5: 5-step asymmetric NS (dion). Each step uses different coefficients. 

56_NS_ASYM5_COEFFS: Tuple[Tuple[float, float, float], ...] = ( 

57 (4.0848, -6.8946, 2.9270), 

58 (3.9505, -6.3029, 2.6377), 

59 (3.7418, -5.5913, 2.3037), 

60 (2.8769, -3.1427, 1.2046), 

61 (2.8366, -3.0525, 1.2012), 

62) 

63 

64 

65@dataclass 

66class NSInputTransform: 

67 """Prepared NS tensors and the callback that restores their updates.""" 

68 

69 tensors: List[torch.Tensor] 

70 restore: Callable[[List[torch.Tensor], torch.Tensor], None] 

71 

72 

73@dataclass(frozen=True) 

74class MuonPostUpdateContext: 

75 """Context supplied to an optional parameter post-update callback.""" 

76 

77 param_fqn: Optional[str] 

78 logical_shape: Tuple[int, ...] 

79 lr: float 

80 weight_decay: float 

81 step: int 

82 

83 

84@dataclass(frozen=True) 

85class _ShardBatch: 

86 """One batch and its original assignment boundary.""" 

87 

88 group_idx: int 

89 assignment: HSDPGroupAssignment 

90 params: List[torch.nn.Parameter] 

91 last_in_assignment: bool 

92 

93 

94_PackedShardUpdates = Dict[ 

95 Tuple[int, ...], Tuple[torch.Tensor, List[Tuple[torch.nn.Parameter, int, int]]] 

96] 

97_AssignmentEntry = Tuple[int, HSDPGroupAssignment] 

98_ShardPipelineKey = Tuple[torch.device, Tuple[dist.ProcessGroup, ...], Tuple[dist.ProcessGroup, ...]] 

99_LocalQueueKey = Tuple[int, torch.device] 

100_LocalBatches = Deque[List[torch.nn.Parameter]] 

101_LocalWindowQuotas = Dict[_LocalQueueKey, Deque[int]] 

102 

103 

104@dataclass 

105class _ShardPipelineBuffers: 

106 """Reusable scratch allocated and consumed on the caller's compute stream.""" 

107 

108 gather: Dict = field(default_factory=dict) 

109 owner: Dict = field(default_factory=dict) 

110 broadcast: Dict = field(default_factory=dict) 

111 

112 

113@dataclass 

114class _BroadcastShardBatch: 

115 """Packed updates kept alive until the compute stream joins the broadcasts.""" 

116 

117 batch: _ShardBatch 

118 packed: _PackedShardUpdates 

119 works: List[dist.Work] 

120 

121 

122_MUON_ADVANCED_DEFAULTS: Dict[str, Any] = { 

123 "ns_coefficients": None, 

124 "ns_epsilon": 1e-10, 

125 "zeropower_fn": None, 

126 "momentum_update_fn": None, 

127 "reshape_fn": None, 

128 "ns_transform_fn": None, 

129 "post_update_fn": None, 

130 "zero_rms_scale_mode": "zero", 

131 "apply_lr_in_update": False, 

132 "overlap_shard_comm": False, 

133} 

134 

135 

136@dataclass(frozen=True) 

137class _MuonAdvancedOptions: 

138 """Validated low-frequency Muon options.""" 

139 

140 ns_coefficients: Optional[Sequence[Tuple[float, float, float]]] 

141 ns_epsilon: float 

142 zeropower_fn: Optional[Callable[..., torch.Tensor]] 

143 momentum_update_fn: Optional[Callable[..., torch.Tensor]] 

144 reshape_fn: Optional[Callable[..., Any]] 

145 ns_transform_fn: Optional[Callable[..., Optional[NSInputTransform]]] 

146 post_update_fn: Optional[Callable[..., None]] 

147 zero_rms_scale_mode: str 

148 apply_lr_in_update: bool 

149 overlap_shard_comm: bool 

150 

151 

152def _resolve_muon_advanced_options(options: Dict[str, Any]) -> _MuonAdvancedOptions: 

153 """Validate and fill low-frequency Muon keyword options.""" 

154 unknown = options.keys() - _MUON_ADVANCED_DEFAULTS.keys() 

155 if unknown: 

156 raise TypeError(f"Muon got unexpected keyword arguments: {', '.join(sorted(unknown))}") 

157 resolved = dict(_MUON_ADVANCED_DEFAULTS) 

158 resolved.update(options) 

159 return _MuonAdvancedOptions(**resolved) 

160 

161 

162_TransformNSState = Dict[str, Any] 

163 

164 

165def _resolve_ns_coefficients( 

166 steps: int, 

167 ns_variant: str = "asym5", 

168 ns_coefficients: Optional[Sequence[Tuple[float, float, float]]] = None, 

169) -> Tuple[Tuple[float, float, float], ...]: 

170 """Resolve the coefficient prefix shared by native NS and backend construction.""" 

171 if ns_variant == "legacy": 

172 return (_NS_LEGACY_COEFFS,) * steps 

173 if ns_variant == "asym5": 

174 return _NS_ASYM5_COEFFS[:steps] 

175 if ns_variant == "custom": 

176 if ns_coefficients is None: 

177 raise ValueError("ns_coefficients must be provided when ns_variant='custom'") 

178 if steps > len(ns_coefficients): 

179 raise ValueError( 

180 f"ns_steps={steps} exceeds the {len(ns_coefficients)} provided coefficient groups" 

181 ) 

182 return tuple(tuple(row) for row in ns_coefficients[:steps]) 

183 raise ValueError(f"ns_variant must be 'legacy', 'asym5', or 'custom', got {ns_variant!r}") 

184 

185 

186def zeropower_via_newtonschulz5( 

187 ns_inputs: torch.Tensor, 

188 steps: int, 

189 ns_variant: str = "asym5", 

190 epsilon: float = 1e-10, 

191 ns_coefficients: Optional[Sequence[Tuple[float, float, float]]] = None, 

192) -> torch.Tensor: 

193 """Newton-Schulz orthogonalization with preallocated matmul buffers. 

194 

195 Args: 

196 ns_inputs: Matrix or matrix batch to orthogonalize. 

197 steps: Requested iteration count; asym5 uses at most five iterations. 

198 ns_variant: Built-in legacy/asym5 schedule or an explicit custom schedule. 

199 epsilon: Normalization epsilon added to the input norm. 

200 ns_coefficients: Coefficient triples required by the custom variant. 

201 

202 Returns: 

203 Orthogonalized updates with the input shape, dtype and device. 

204 """ 

205 mat_x = ns_inputs 

206 transposed = ns_inputs.size(-2) > ns_inputs.size(-1) 

207 if transposed: 

208 mat_x = mat_x.mT 

209 

210 # Normalize input before Newton-Schulz iteration. 

211 mat_x = mat_x / (mat_x.norm(dim=(-2, -1), keepdim=True) + epsilon) 

212 

213 n_size = mat_x.size(-2) 

214 buf_a = torch.empty(mat_x.shape[:-2] + (n_size, n_size), dtype=mat_x.dtype, device=mat_x.device) 

215 buf_b = torch.empty_like(buf_a) 

216 buf_c = torch.empty(mat_x.shape, dtype=mat_x.dtype, device=mat_x.device) 

217 

218 step_coeffs = _resolve_ns_coefficients(steps, ns_variant, ns_coefficients) 

219 

220 for coeff_a, coeff_b, coeff_c in step_coeffs: 

221 torch.matmul(mat_x, mat_x.mT, out=buf_a) 

222 torch.matmul(buf_a, buf_a, out=buf_b) 

223 buf_a.mul_(coeff_b) 

224 buf_b.mul_(coeff_c) 

225 buf_a.add_(buf_b) 

226 torch.matmul(buf_a, mat_x, out=buf_c) 

227 mat_x.mul_(coeff_a).add_(buf_c) 

228 

229 del buf_a, buf_b, buf_c 

230 

231 if transposed: 

232 mat_x = mat_x.mT 

233 

234 return mat_x 

235 

236 

237def compute_muon_slice_scale( 

238 slice_tensor: torch.Tensor, 

239 matched_adamw_rms: float, 

240 zero_rms_scale_mode: str = "zero", 

241) -> float: 

242 """Compute Muon scale from the logical matrix dims of a reshaped slice.""" 

243 if not matched_adamw_rms: 

244 return 1.0 if zero_rms_scale_mode == "use_lr" else 0.0 

245 shape = tuple(slice_tensor.shape) 

246 if len(shape) == 3 and shape[1] == 1: 

247 logical_dims = (shape[0], shape[2]) 

248 else: 

249 logical_dims = shape[-2:] 

250 return math.sqrt(max(logical_dims)) * matched_adamw_rms 

251 

252 

253class Muon(BaseDistributedOptimizer): 

254 """Muon optimizer with HSDP shard-group-aware Newton-Schulz orthogonalization. 

255 

256 Implements the Muon optimizer which uses Newton-Schulz iteration for matrix 

257 orthogonalization of gradient updates, with HSDP-aware communication for 

258 sharded parameters. 

259 """ 

260 

261 ADDITIONAL_CONFIG_KEYS = set(_MUON_ADVANCED_DEFAULTS) 

262 

263 def __init__( 

264 self, 

265 params: Any, 

266 lr: float = 2e-2, 

267 weight_decay: float = 0.1, 

268 matched_adamw_rms: float = 0.2, 

269 momentum: Union[float, List[float], Tuple[float, ...]] = 0.95, 

270 nesterov: bool = True, 

271 ns_steps: int = 5, 

272 ns_variant: str = "asym5", 

273 hsdp_replica_count: Optional[Union[int, Tuple[int, ...]]] = None, 

274 momentum_mode: str = "legacy", 

275 **advanced_options: Any, 

276 ) -> None: 

277 """Initialize Muon and build parameter-identity runtime caches. 

278 

279 Args: 

280 params: Parameters or parameter groups optimized by Muon. 

281 lr: Learning rate. 

282 weight_decay: Decoupled weight-decay coefficient. 

283 matched_adamw_rms: RMS scale matched to an AdamW update. 

284 momentum: Momentum coefficient or coefficient pair. 

285 nesterov: Whether to use Nesterov momentum. 

286 ns_steps: Newton-Schulz iteration count. 

287 ns_variant: Newton-Schulz coefficient variant. 

288 ns_coefficients: Optional custom Newton-Schulz coefficients. 

289 ns_epsilon: Numerical stability term used during normalization. 

290 zeropower_fn: Optional ``fn(local_tensor, steps=ns_steps)`` override. 

291 Return a writable tensor with the same shape, dtype and device. 

292 The callback owns its coefficient schedule and epsilon; these 

293 group options are not forwarded. Recreate matching callback 

294 configuration when restoring an optimizer checkpoint. 

295 momentum_update_fn: Optional momentum update implementation override. 

296 reshape_fn: Optional logical-matrix reshape function. 

297 ns_transform_fn: Optional Newton-Schulz input transformation. 

298 post_update_fn: Optional callback applied after a parameter update. 

299 overlap_shard_comm: Overlap Muon computation with shard all-gather 

300 and update broadcast on a single CUDA or NPU shard axis. 

301 Distribute independent local batches evenly across communication 

302 windows for their group and device. Set consistently on all ranks. 

303 Reshape and NS transform callbacks may run in a different order 

304 across parameters. Custom momentum and post-update callbacks 

305 use the serial schedule. 

306 zero_rms_scale_mode: Scaling behavior when matched AdamW RMS is zero. 

307 apply_lr_in_update: Whether the update callback applies the learning rate. 

308 hsdp_replica_count: Optional optimizer-state replica group size. 

309 momentum_mode: Momentum formula, either "legacy" or "vanilla". 

310 Both modes support distinct update and buffer coefficients. 

311 """ 

312 advanced = _resolve_muon_advanced_options(advanced_options) 

313 if not isinstance(advanced.overlap_shard_comm, bool): 

314 raise TypeError("overlap_shard_comm must be a bool") 

315 if momentum_mode not in ("legacy", "vanilla"): 

316 raise ValueError( 

317 f"momentum_mode must be 'legacy' or 'vanilla', got {momentum_mode!r}" 

318 ) 

319 if ns_variant not in ("legacy", "asym5", "custom"): 

320 raise ValueError( 

321 f"ns_variant must be 'legacy', 'asym5', or 'custom', got {ns_variant!r}" 

322 ) 

323 if advanced.ns_epsilon < 0.0 or not math.isfinite(advanced.ns_epsilon): 

324 raise ValueError(f"ns_epsilon must be a finite non-negative value, got {advanced.ns_epsilon}") 

325 if advanced.zero_rms_scale_mode not in ("zero", "use_lr"): 

326 raise ValueError( 

327 "zero_rms_scale_mode must be 'zero' or 'use_lr', " 

328 f"got {advanced.zero_rms_scale_mode!r}" 

329 ) 

330 normalized_coefficients = self._validate_ns_coefficients( 

331 ns_variant, ns_steps, advanced.ns_coefficients 

332 ) 

333 if not isinstance(momentum, (list, tuple)): 

334 momentum = [momentum] 

335 if len(momentum) == 1: 

336 momentum = (momentum[0], momentum[0]) 

337 defaults = { 

338 "lr": lr, 

339 "weight_decay": weight_decay, 

340 "matched_adamw_rms": matched_adamw_rms, 

341 "momentum": momentum, 

342 "nesterov": nesterov, 

343 "ns_steps": ns_steps, 

344 "ns_variant": ns_variant, 

345 "ns_coefficients": normalized_coefficients, 

346 "ns_epsilon": advanced.ns_epsilon, 

347 "zero_rms_scale_mode": advanced.zero_rms_scale_mode, 

348 "apply_lr_in_update": advanced.apply_lr_in_update, 

349 } 

350 super().__init__(params, defaults, is_muon=True, hsdp_replica_count=hsdp_replica_count) 

351 self.reshape_fn = advanced.reshape_fn 

352 self.zeropower_fn = advanced.zeropower_fn 

353 self.momentum_update_fn = advanced.momentum_update_fn 

354 self._update_muon_momentum_mode = momentum_mode 

355 self.ns_transform_fn = advanced.ns_transform_fn 

356 self.post_update_fn = advanced.post_update_fn 

357 self.overlap_shard_comm = advanced.overlap_shard_comm 

358 self.reset_optimizer_parameters() 

359 

360 def reset_optimizer_parameters(self) -> None: 

361 """Rebuild all parameter-identity caches from current param groups.""" 

362 self._group_dtensor_by_mesh() 

363 if is_recovery_bootstrapping(): 

364 # Peers are parked until communication rebuild. Shape collectives 

365 # must run on all workers from rebuild_recovery_state instead. 

366 self._param_shard_metadata = {} 

367 else: 

368 self._build_param_shard_metadata() 

369 if self.hsdp_replica_count is None: 

370 self.hsdp_replica_count = self._auto_deduce_replica_count() 

371 # Retain the original cache if graph binding has to roll back. 

372 self._split_sub_pg_cache = self._split_sub_pg_cache.copy() 

373 self._split_replicate_groups() 

374 self._build_hsdp_batch() 

375 self._build_param_broadcast_info() 

376 self._classify_parameters_for_step() 

377 

378 def rebuild_recovery_state(self) -> None: 

379 """Refresh shard shapes on every rank after existing groups are reinitialized.""" 

380 self._build_param_shard_metadata() 

381 

382 @staticmethod 

383 def _validate_ns_coefficients( 

384 ns_variant: str, 

385 ns_steps: int, 

386 ns_coefficients: Optional[Sequence[Tuple[float, float, float]]], 

387 ) -> Optional[Tuple[Tuple[float, float, float], ...]]: 

388 """Validate and normalize externally supplied Newton-Schulz coefficients.""" 

389 if ns_variant != "custom": 

390 if ns_coefficients is not None: 

391 raise ValueError("ns_coefficients can only be provided when ns_variant='custom'") 

392 return None 

393 if not ns_coefficients: 

394 raise ValueError("ns_coefficients must be provided when ns_variant='custom'") 

395 if ns_steps > len(ns_coefficients): 

396 raise ValueError( 

397 f"ns_steps={ns_steps} exceeds the {len(ns_coefficients)} provided coefficient groups" 

398 ) 

399 

400 normalized = [] 

401 for index, coefficients in enumerate(ns_coefficients): 

402 if len(coefficients) != 3: 

403 raise ValueError( 

404 f"ns_coefficients[{index}] must contain exactly three values, got {coefficients!r}" 

405 ) 

406 normalized_coefficients = tuple(float(value) for value in coefficients) 

407 if not all(math.isfinite(value) for value in normalized_coefficients): 

408 raise ValueError(f"ns_coefficients[{index}] must contain only finite values") 

409 normalized.append(normalized_coefficients) 

410 return tuple(normalized) 

411 

412 def __str__(self) -> str: 

413 """Return the optimizer representation.""" 

414 return super().__repr__() 

415 

416 __repr__ = __str__ 

417 

418 @torch.no_grad() 

419 def step( 

420 self, 

421 closure: Optional[Callable[[], Any]] = None, 

422 ) -> Optional[float]: 

423 """Perform a single optimization step. 

424 

425 De-duplication is controlled by the caller: ``param_to_ns_input`` should already contain only the owned 

426 params (via ``hsdp_assign.owned_params``). The caller is responsible for broadcasting the updated params to 

427 replica peers via ``AsyncReplicateBroadcaster.flush_group``. 

428 

429 Args: 

430 closure: Optional callable that reevaluates the model and returns loss. 

431 

432 Returns: 

433 The closure loss when provided, otherwise ``None``. 

434 """ 

435 loss = None 

436 if closure is not None: 

437 with torch.enable_grad(): 

438 loss = closure() 

439 broadcaster = AsyncReplicateBroadcaster(self) 

440 

441 for group in self.param_groups: 

442 group['step'] = (group.get('step') or 0) + 1 

443 

444 self._run_step_assignments(broadcaster) 

445 broadcaster.wait_all() 

446 return loss 

447 

448 def _run_step_assignments(self, broadcaster: AsyncReplicateBroadcaster) -> None: 

449 """Submit shard and independent local batches in one schedule.""" 

450 assignments: Iterable[_AssignmentEntry] = self._step_assignments() 

451 local_batches: Dict[_LocalQueueKey, _LocalBatches] = {} 

452 if self.overlap_shard_comm and self.momentum_update_fn is None and self.post_update_fn is None: 

453 assignments, local_batches = self._plan_overlap_batches(assignments) 

454 self._process_no_comm_params(local_batches) 

455 

456 runs = groupby(assignments, self._shard_pipeline_key) 

457 shard_runs = {} 

458 quotas: _LocalWindowQuotas = {} 

459 if any(local_batches.values()): 

460 runs = [(key, list(run)) for key, run in runs] 

461 shard_runs, quotas = self._plan_local_overlap_windows(runs, local_batches) 

462 

463 for run_idx, (key, run) in enumerate(runs): 

464 if key is None: 

465 for group_idx, assignment in run: 

466 self._process_serial_assignment(group_idx, assignment, broadcaster) 

467 else: 

468 device, _, _ = key 

469 batches = iter(shard_runs[run_idx]) if run_idx in shard_runs else self._iter_shard_batches(run) 

470 self._process_shard_pipeline(batches, device, broadcaster, local_batches, quotas) 

471 for (group_idx, _), queue in local_batches.items(): 

472 while queue: 

473 self._run_local_batch(group_idx, queue) 

474 

475 def _plan_overlap_batches( 

476 self, assignments: Iterable[_AssignmentEntry], 

477 ) -> Tuple[List[_AssignmentEntry], Dict[_LocalQueueKey, _LocalBatches]]: 

478 """Extract updates that need neither shard collectives nor replica synchronization.""" 

479 entries = list(assignments) 

480 queues: Dict[_LocalQueueKey, _LocalBatches] = {} 

481 for entry in entries: 

482 pipeline_key = self._shard_pipeline_key(entry) 

483 if pipeline_key is not None: 

484 queues.setdefault((entry[0], pipeline_key[0]), deque()) 

485 

486 remaining = [] 

487 for group_idx, assignment in entries: 

488 if not assignment.is_shard and not assignment.is_replicated and assignment.owned_records: 

489 params = assignment.owned_params 

490 device = to_local_if_dtensor(params[0]).device 

491 queue = queues.get((group_idx, device)) 

492 if queue is not None: 

493 self._queue_local_batches(params, queue) 

494 continue 

495 remaining.append((group_idx, assignment)) 

496 return remaining, queues 

497 

498 def _queue_local_batches(self, params: List[torch.nn.Parameter], queue: _LocalBatches) -> None: 

499 """Plan local work while keeping pending entries free of temporary tensors.""" 

500 for shape_group in self._group_by_shape([param for param in params if param.grad is not None]).values(): 

501 queue.extend(self._split_into_memory_safe_batches(shape_group, shard_size=1)) 

502 

503 def _plan_local_overlap_windows( 

504 self, 

505 runs: List[Tuple[Optional[_ShardPipelineKey], List[_AssignmentEntry]]], 

506 local_batches: Dict[_LocalQueueKey, _LocalBatches], 

507 ) -> Tuple[Dict[int, List[_ShardBatch]], _LocalWindowQuotas]: 

508 """Count each run's initial gather and each shard batch's broadcast.""" 

509 shard_runs = {} 

510 counts = defaultdict(int) 

511 for run_idx, (key, run) in enumerate(runs): 

512 if key is None: 

513 continue 

514 device = key[0] 

515 batches = list(self._iter_shard_batches(run)) 

516 shard_runs[run_idx] = batches 

517 if batches: 

518 counts[batches[0].group_idx, device] += 1 

519 for batch in batches: 

520 counts[batch.group_idx, device] += 1 

521 

522 quotas = {} 

523 for key, windows in counts.items(): 

524 num_local = len(local_batches.get(key, ())) 

525 if num_local: 

526 quotas[key] = deque( 

527 (index + 1) * num_local // windows - index * num_local // windows 

528 for index in range(windows) 

529 ) 

530 return shard_runs, quotas 

531 

532 def _process_no_comm_params(self, local_batches: Dict[_LocalQueueKey, _LocalBatches]) -> None: 

533 """Use the same local queue for parameters outside HSDP assignments.""" 

534 no_comm_inputs = [] 

535 for group_idx, group in enumerate(self.param_groups): 

536 info = self._hsdp_assignment_batches.get(group_idx) 

537 params = info.get("no_comm", []) if info else self.unshard_params_by_group.get(group_idx, []) 

538 if local_batches and params: 

539 eligible = defaultdict(list) 

540 eager = [] 

541 for param in params: 

542 device = to_local_if_dtensor(param).device 

543 if (group_idx, device) in local_batches: 

544 eligible[device].append(param) 

545 else: 

546 eager.append(param) 

547 for device, device_params in eligible.items(): 

548 self._queue_local_batches(device_params, local_batches[(group_idx, device)]) 

549 params = eager 

550 no_comm_inputs.append(self._update_muon_momentum(group, params) if params else {}) 

551 

552 for group, ns_inputs in zip(self.param_groups, no_comm_inputs): 

553 if ns_inputs: 

554 self._process_unshard_params(group, ns_inputs) 

555 if self.post_update_fn is not None: 

556 self._run_post_update_fn(group, ns_inputs.keys()) 

557 

558 def _run_local_batch(self, group_idx: int, queue: Optional[_LocalBatches]) -> None: 

559 """Submit one local batch on the caller's compute stream.""" 

560 if queue: 

561 with torch.profiler.record_function("muon.pipeline.local_ns"): 

562 group = self.param_groups[group_idx] 

563 self._process_unshard_params(group, self._update_muon_momentum(group, queue.popleft())) 

564 

565 def _run_local_window( 

566 self, group_idx: int, queue: Optional[_LocalBatches], quotas: Optional[Deque[int]], 

567 ) -> None: 

568 """Submit the local work allotted to this independent communication window.""" 

569 if quotas: 

570 for _ in range(quotas.popleft()): 

571 self._run_local_batch(group_idx, queue) 

572 

573 def _step_assignments(self) -> Iterator[_AssignmentEntry]: 

574 """Yield assignments in the original round-robin optimizer group order.""" 

575 by_group = [] 

576 for group_idx in range(len(self.param_groups)): 

577 batch_groups = self._hsdp_assignment_batches.get(group_idx, {}).get("batch_groups", []) 

578 by_group.append(list(chain.from_iterable(batch_group["sub_batches"] for batch_group in batch_groups))) 

579 for batch_idx in range(max(map(len, by_group), default=0)): 

580 for group_idx, assignments in enumerate(by_group): 

581 if batch_idx < len(assignments): 

582 yield group_idx, assignments[batch_idx] 

583 

584 def _process_serial_assignment( 

585 self, group_idx: int, assignment: HSDPGroupAssignment, broadcaster: AsyncReplicateBroadcaster, 

586 overlap_work: Optional[Callable[[], None]] = None, 

587 ) -> None: 

588 """Keep whole-assignment callback inputs and the serial shard path.""" 

589 group = self.param_groups[group_idx] 

590 ns_inputs = self._update_muon_momentum(group, assignment.owned_params) 

591 if assignment.is_shard: 

592 self._process_shard_params( 

593 group, ns_inputs, [assignment], group_idx, buffer_cache={}, overlap_work=overlap_work, 

594 ) 

595 elif ns_inputs: 

596 self._process_unshard_params(group, ns_inputs) 

597 if self.post_update_fn is not None: 

598 self._run_post_update_fn(group, ns_inputs.keys()) 

599 broadcaster.flush_group(assignment) 

600 

601 def _shard_pipeline_key( 

602 self, entry: Tuple[int, HSDPGroupAssignment], 

603 ) -> Optional[_ShardPipelineKey]: 

604 """Only look ahead across consecutive assignments with the same communication groups.""" 

605 _, assignment = entry 

606 if not self.overlap_shard_comm or self.momentum_update_fn is not None or self.post_update_fn is not None: 

607 return None 

608 if not assignment.is_shard or len(assignment.shard_pgs) != 1 or not assignment.owned_records: 

609 return None 

610 pg = assignment.shard_pgs[0] 

611 if pg is None or dist.get_world_size(pg) <= 1: 

612 return None 

613 device = to_local_if_dtensor(assignment.owned_records[0].param).device 

614 if device.type not in ("cuda", "npu"): 

615 return None 

616 return device, assignment.shard_pgs, assignment.replicate_pgs 

617 

618 def _iter_shard_batches(self, assignments: Iterable[Tuple[int, HSDPGroupAssignment]]) -> Iterator[_ShardBatch]: 

619 """Keep the serial shard batch membership and replica flush boundaries.""" 

620 for group_idx, assignment in assignments: 

621 shard_size = dist.get_world_size(assignment.shard_pgs[0]) 

622 batches = self._split_into_memory_safe_batches(assignment.owned_params, shard_size, shard_size) 

623 for batch_idx, params in enumerate(batches): 

624 yield _ShardBatch(group_idx, assignment, params, batch_idx == len(batches) - 1) 

625 

626 def _prepare_shard_batch( 

627 self, batch: _ShardBatch, buffers: _ShardPipelineBuffers, while_gathering: Callable[[], None], 

628 ) -> Tuple[Dict[torch.nn.Parameter, torch.Tensor], Dict[torch.nn.Parameter, Tuple[int, ...]]]: 

629 """Pack on the caller stream and submit independent work before waiting for gather.""" 

630 with torch.profiler.record_function("muon.pipeline.gather"): 

631 ns_inputs = self._update_muon_momentum(self.param_groups[batch.group_idx], batch.params) 

632 return self._gather_shard_inputs( 

633 batch.params, ns_inputs, batch.assignment, self._shard_compute_coord[batch.group_idx], 

634 buffer_cache=buffers.gather, fallback_dtype=torch.bfloat16, 

635 owner_buffer_cache=buffers.owner, overlap_work=while_gathering, 

636 ) 

637 

638 def _process_shard_pipeline( 

639 self, batches: Iterator[_ShardBatch], device: torch.device, broadcaster: AsyncReplicateBroadcaster, 

640 local_batches: Dict[_LocalQueueKey, _LocalBatches], 

641 quotas: _LocalWindowQuotas, 

642 ) -> None: 

643 """Overlap each batch's NS with its neighbors' collectives using two in-flight batches.""" 

644 first = next(batches) 

645 second = next(batches, None) 

646 if second is None: 

647 key = first.group_idx, device 

648 queue = local_batches.get(key) 

649 windows = quotas.get(key) 

650 overlap_work = partial(self._run_local_window, first.group_idx, queue, windows) if windows else None 

651 self._process_serial_assignment(first.group_idx, first.assignment, broadcaster, overlap_work) 

652 return 

653 

654 buffers = _ShardPipelineBuffers() 

655 try: 

656 self._run_shard_pipeline( 

657 first, chain((second,), batches), broadcaster, local_batches, device, buffers, quotas, 

658 ) 

659 except Exception: 

660 # Drain any partially submitted collective before releasing its scratch. 

661 getattr(torch, device.type).synchronize(device) 

662 raise 

663 

664 def _run_shard_pipeline( 

665 self, batch: _ShardBatch, following_batches: Iterator[_ShardBatch], broadcaster: AsyncReplicateBroadcaster, 

666 local_batches: Dict[_LocalQueueKey, _LocalBatches], device: torch.device, 

667 buffers: _ShardPipelineBuffers, quotas: _LocalWindowQuotas, 

668 ) -> None: 

669 """Overlap process-group collectives with work on the caller's compute stream.""" 

670 def run_local(group_idx: int) -> None: 

671 key = group_idx, device 

672 self._run_local_window(group_idx, local_batches.get(key), quotas.get(key)) 

673 

674 inputs, coords = self._prepare_shard_batch(batch, buffers, partial(run_local, batch.group_idx)) 

675 pending = None 

676 

677 def compute_and_broadcast() -> None: 

678 nonlocal pending 

679 pg = batch.assignment.shard_pgs[0] 

680 with torch.profiler.record_function("muon.pipeline.ns"): 

681 updates = self._compute_shard_updates( 

682 inputs, self.param_groups[batch.group_idx], dist.get_world_size(pg), 

683 ) 

684 

685 if pending is not None: 

686 run_local(pending.batch.group_idx) 

687 self._apply_pipeline_batch(pending, broadcaster) 

688 

689 # Apply has consumed the previous broadcast slot. Pack before the 

690 # next gather unpacks into the owner slot, which updates may alias. 

691 with torch.profiler.record_function("muon.pipeline.broadcast"): 

692 packed = self._pack_shard_updates( 

693 batch.params, updates, coords, (dist.get_rank(pg),), device, buffers.broadcast, 

694 ) 

695 works = self._launch_shard_axis_broadcasts(packed, pg, 0, ()) 

696 pending = _BroadcastShardBatch(batch, packed, works) 

697 

698 for following in following_batches: 

699 # Queue gather(i+1) before broadcast(i) on the same process group. 

700 # The callback consumes owner(i) while gather(i+1) is in flight. 

701 inputs, coords = self._prepare_shard_batch(following, buffers, compute_and_broadcast) 

702 batch = following 

703 compute_and_broadcast() 

704 run_local(batch.group_idx) 

705 self._apply_pipeline_batch(pending, broadcaster) 

706 

707 def _apply_pipeline_batch( 

708 self, pending: _BroadcastShardBatch, broadcaster: AsyncReplicateBroadcaster, 

709 ) -> None: 

710 """Join the shard broadcasts on the caller stream before applying or reusing the slot.""" 

711 batch = pending.batch 

712 with torch.profiler.record_function("muon.pipeline.apply"): 

713 for work in pending.works: 

714 work.wait() 

715 self._apply_shard_updates(pending.packed, self.param_groups[batch.group_idx], batch.assignment) 

716 if batch.last_in_assignment and batch.assignment.is_replicated: 

717 broadcaster.flush_group(batch.assignment) 

718 

719 def _run_post_update_fn( 

720 self, 

721 group: Dict[str, Any], 

722 params: Iterable[torch.nn.Parameter], 

723 ) -> None: 

724 """Run the optional model callback on updated owner parameters before broadcast.""" 

725 if self.post_update_fn is None: 

726 return 

727 context_values = { 

728 "lr": group["lr"], 

729 "weight_decay": group["weight_decay"], 

730 "step": group["step"], 

731 } 

732 for param in params: 

733 local_tensor = to_local_if_dtensor(param.data) 

734 context = MuonPostUpdateContext( 

735 param_fqn=getattr(param, "model_name", None), 

736 logical_shape=tuple(param.shape), 

737 **context_values, 

738 ) 

739 self.post_update_fn(param, local_tensor, context) 

740 

741 def _classify_parameters_for_step(self) -> None: 

742 """Classify params by whether the last two dims are sharded. 

743 

744 unshard: run Newton-Schulz locally. 

745 shard: all-gather before Newton-Schulz. 

746 

747 Reads from self._hsdp_assignment_batches which is organized by batch. 

748 """ 

749 self.unshard_params_by_group: Dict[int, List] = {} 

750 self.shard_params_by_group: Dict[int, List] = {} 

751 self.shard_assignments_by_group: Dict[int, List[HSDPGroupAssignment]] = {} 

752 # Per group: record.index -> shard coord that computes NS. 

753 self._shard_compute_coord: Dict[int, Dict[int, Tuple[int, ...]]] = {} 

754 

755 for group_idx, group in enumerate(self.param_groups): 

756 assignment_info = self._hsdp_assignment_batches.get(group_idx) 

757 

758 unshard_params = [] 

759 shard_hsdp_assignments: List[HSDPGroupAssignment] = [] 

760 

761 if assignment_info: 

762 unshard_params.extend(assignment_info["no_comm"]) 

763 for bg in assignment_info["batch_groups"]: 

764 for hsdp_assign in bg["sub_batches"]: 

765 if hsdp_assign.is_shard: 

766 shard_hsdp_assignments.append(hsdp_assign) 

767 else: 

768 unshard_params.extend(hsdp_assign.owned_params) 

769 else: 

770 unshard_params.extend(group["params"]) 

771 

772 # Shard params only include locally owned params; replica ownership is enforced at apply time. 

773 shard_params = [p for a in shard_hsdp_assignments for p in a.owned_params] 

774 

775 # Greedily assign NS compute across shard ranks. 

776 self._shard_compute_coord[group_idx] = {} 

777 for hsdp_assign in shard_hsdp_assignments: 

778 shard_sizes, _, _, _ = self._get_shard_info(hsdp_assign) 

779 compute_by_index = build_owner_by_size( 

780 records=hsdp_assign.owned_records, 

781 replicate_sizes=shard_sizes, 

782 ) 

783 self._shard_compute_coord[group_idx].update(compute_by_index) 

784 

785 self.unshard_params_by_group[group_idx] = unshard_params 

786 self.shard_assignments_by_group[group_idx] = shard_hsdp_assignments 

787 self.shard_params_by_group[group_idx] = shard_params 

788 

789 @staticmethod 

790 def _update_muon_momentum_foreach( 

791 grads: List[torch.Tensor], 

792 bufs: List[torch.Tensor], 

793 momentum1: float, 

794 momentum2: float, 

795 nesterov: bool, 

796 mode: str, 

797 ) -> List[torch.Tensor]: 

798 """Apply the built-in momentum formula in homogeneous foreach regions.""" 

799 if mode not in ("vanilla", "legacy"): 

800 raise ValueError( 

801 "Muon._update_muon_momentum_mode must be 'vanilla' or 'legacy', " 

802 f"got {mode!r}" 

803 ) 

804 

805 # NPU mixed-dtype foreach may round BF16 differently from homogeneous 

806 # calls. Swap and HSDP can change list boundaries, so keep each foreach 

807 # region homogeneous while preserving the original parameter order. 

808 foreach_groups = defaultdict(list) 

809 for index, (grad, buffer) in enumerate(zip(grads, bufs)): 

810 key = (grad.device, grad.dtype, buffer.device, buffer.dtype) 

811 foreach_groups[key].append(index) 

812 

813 local_us = list(grads) 

814 # PyTorch exposes foreach operators only through underscore-prefixed APIs. 

815 # pylint: disable=protected-access 

816 for indices in foreach_groups.values(): 

817 grouped_grads = [grads[index] for index in indices] 

818 grouped_bufs = [bufs[index] for index in indices] 

819 if mode == "vanilla": 

820 # Match vanilla Muon while folding Nesterov into one lerp. 

821 update_momentum = momentum1 ** 2 if nesterov else momentum1 

822 grouped_us = torch._foreach_lerp(grouped_grads, grouped_bufs, weight=update_momentum) 

823 torch._foreach_lerp_(grouped_bufs, grouped_grads, weight=1 - momentum2) 

824 else: 

825 grouped_us = torch._foreach_add(grouped_grads, grouped_bufs, alpha=momentum1) 

826 torch._foreach_mul_(grouped_bufs, momentum2) 

827 torch._foreach_add_(grouped_bufs, grouped_grads) 

828 if nesterov: 

829 torch._foreach_mul_(grouped_us, momentum1) 

830 torch._foreach_add_(grouped_us, grouped_grads) 

831 for index, update in zip(indices, grouped_us): 

832 local_us[index] = update 

833 # pylint: enable=protected-access 

834 return local_us 

835 

836 def _update_muon_momentum( 

837 self, 

838 group: Dict[str, Any], 

839 params: List[torch.Tensor], 

840 ) -> Dict[torch.nn.Parameter, torch.Tensor]: 

841 """Compute first-order momentum and return bfloat16 NS inputs.""" 

842 momentum = group["momentum"] 

843 if not isinstance(momentum, (list, tuple)): 

844 momentum = [momentum] 

845 if len(momentum) == 1: 

846 momentum = (momentum[0], momentum[0]) 

847 momentum1, momentum2 = momentum 

848 # Pre-filter params with valid grads and ensure momentum buffers exist 

849 valid_params = [] 

850 grads = [] 

851 bufs = [] 

852 for p in params: 

853 g = p.grad 

854 if g is None: 

855 continue 

856 if "momentum_buffer" not in self.state[p]: 

857 self.state[p]["momentum_buffer"] = torch.zeros_like(g) 

858 valid_params.append(p) 

859 grads.append(g) 

860 bufs.append(self.state[p]["momentum_buffer"]) 

861 

862 if not valid_params: 

863 return {} 

864 

865 grads = [to_local_if_dtensor(grad) for grad in grads] 

866 bufs = [to_local_if_dtensor(buffer) for buffer in bufs] 

867 if self.momentum_update_fn is not None: 

868 custom_updates = list(self.momentum_update_fn(grads, bufs, momentum1, momentum2, group["nesterov"])) 

869 if len(custom_updates) != len(valid_params): 

870 raise ValueError( 

871 "momentum_update_fn must return one update tensor per input gradient, " 

872 f"got {len(custom_updates)} updates for {len(valid_params)} gradients" 

873 ) 

874 custom_updates = [update.to(torch.bfloat16) for update in custom_updates] 

875 param_updates = dict(zip(valid_params, custom_updates)) 

876 return param_updates 

877 

878 local_us = self._update_muon_momentum_foreach( 

879 grads, 

880 bufs, 

881 momentum1, 

882 momentum2, 

883 group["nesterov"], 

884 self._update_muon_momentum_mode, 

885 ) 

886 

887 local_us = [ 

888 update if update.dtype == torch.bfloat16 else update.to(torch.bfloat16) 

889 for update in local_us 

890 ] 

891 

892 param_updates = dict(zip(valid_params, local_us)) 

893 return param_updates 

894 

895 def _process_unshard_params( 

896 self, 

897 group: Dict[str, Any], 

898 param_to_ns_input: Dict[torch.nn.Parameter, torch.Tensor], 

899 ) -> None: 

900 """Process un-sharded params: shape-group -> memory-batch -> NS -> local update.""" 

901 lr = group["lr"] 

902 weight_decay = group["weight_decay"] 

903 

904 # empty params are not processed in muon, for uneven shard 

905 param_to_ns_input = { 

906 p: ns_input for p, ns_input in param_to_ns_input.items() if ns_input.numel() > 0 

907 } 

908 if not param_to_ns_input: 

909 return 

910 

911 shape_groups = self._group_by_shape(list(param_to_ns_input.keys())) 

912 for _, p_list in shape_groups.items(): 

913 safe_batches = self._split_into_memory_safe_batches(p_list, shard_size=1) 

914 

915 for sub_batch in safe_batches: 

916 updates_dict = self._compute_batched_ns_updates( 

917 sub_batch, param_to_ns_input, group, no_shard=True 

918 ) 

919 

920 local_params = [to_local_if_dtensor(p.data) for p in sub_batch] 

921 local_updates = [updates_dict[p].view(lp.shape) for p, lp in zip(sub_batch, local_params)] 

922 

923 if weight_decay != 0.0: 

924 # pylint: disable=protected-access 

925 torch._foreach_mul_(local_params, 1 - lr * weight_decay) 

926 # pylint: disable=protected-access 

927 apply_alpha = 1.0 if group["apply_lr_in_update"] else -lr 

928 torch._foreach_add_(local_params, local_updates, alpha=apply_alpha) 

929 

930 def _gather_and_compute_shard_updates( 

931 self, 

932 valid_params: List[torch.nn.Parameter], 

933 param_to_ns_input: Dict[torch.nn.Parameter, torch.Tensor], 

934 hsdp_assign: HSDPGroupAssignment, 

935 shard_compute_coord: Dict[int, Tuple[int, ...]], 

936 group: Dict[str, Any], 

937 buffer_cache: Optional[Dict], 

938 overlap_work: Optional[Callable[[], None]] = None, 

939 ) -> Tuple[ 

940 Dict[torch.nn.Parameter, torch.Tensor], 

941 Dict[torch.nn.Parameter, Tuple[int, ...]], 

942 ]: 

943 """Gather NS inputs and compute updates for locally-assigned shard params. 

944 

945 Returns: 

946 (my_updates, param_compute_coord) for this HSDP assignment. 

947 """ 

948 # Gradient-free ranks must match their peers' BF16 NS payload and padding, 

949 # including when a single pipeline batch falls back to this serial path. 

950 gathered_inputs, compute_coords = self._gather_shard_inputs( 

951 valid_params, param_to_ns_input, hsdp_assign, shard_compute_coord, buffer_cache, 

952 fallback_dtype=torch.bfloat16, overlap_work=overlap_work, 

953 ) 

954 shard_size = self._get_shard_info(hsdp_assign)[-1] 

955 return self._compute_shard_updates(gathered_inputs, group, shard_size), compute_coords 

956 

957 def _gather_shard_inputs( 

958 self, 

959 params: List[torch.nn.Parameter], 

960 param_to_ns_input: Dict[torch.nn.Parameter, torch.Tensor], 

961 hsdp_assign: HSDPGroupAssignment, 

962 shard_compute_coord: Dict[int, Tuple[int, ...]], 

963 buffer_cache: Optional[Dict], 

964 fallback_dtype: Optional[torch.dtype] = None, 

965 overlap_work: Optional[Callable[[], None]] = None, 

966 owner_buffer_cache: Optional[Dict] = None, 

967 ) -> Tuple[Dict[torch.nn.Parameter, torch.Tensor], Dict[torch.nn.Parameter, Tuple[int, ...]]]: 

968 """Gather a fused buffer and retain only locally assigned NS inputs.""" 

969 shard_sizes, local_coords, shard_pgs, _ = self._get_shard_info(hsdp_assign) 

970 param_to_index = {record.param: record.index for record in hsdp_assign.owned_records} 

971 param_compute_coord: Dict[torch.nn.Parameter, Tuple[int, ...]] = {} 

972 my_indices: set = set() 

973 

974 for idx, p in enumerate(params): 

975 p_index = param_to_index[p] 

976 compute_coord = shard_compute_coord.get(p_index, (0,) * len(shard_sizes)) 

977 param_compute_coord[p] = compute_coord 

978 if compute_coord == local_coords: 

979 my_indices.add(idx) 

980 

981 local_inputs = build_pad_ns_inputs( 

982 params, 

983 param_to_ns_input, 

984 self._param_shard_metadata, 

985 fallback_dtype=fallback_dtype, 

986 ) 

987 param_shard_metadata = [self._param_shard_metadata.get(p) for p in params] 

988 gathered_list = fused_allgather_dtensor_params( 

989 local_inputs, shard_pgs, hsdp_assign.layout_spec, 

990 param_shard_metadata=param_shard_metadata, 

991 buffer_cache=buffer_cache, 

992 keep_indices=my_indices, 

993 while_gathering=overlap_work, 

994 owner_buffer_cache=owner_buffer_cache, 

995 ) 

996 return {p: full_input for p, full_input in zip(params, gathered_list) 

997 if full_input is not None}, param_compute_coord 

998 

999 def _compute_shard_updates( 

1000 self, 

1001 gathered_inputs: Dict[torch.nn.Parameter, torch.Tensor], 

1002 group: Dict[str, Any], 

1003 shard_size: int, 

1004 ) -> Dict[torch.nn.Parameter, torch.Tensor]: 

1005 """Use the same NS shape groups for serial and overlapping shard batches.""" 

1006 my_updates: Dict[torch.nn.Parameter, torch.Tensor] = {} 

1007 for params in self._group_by_shape(list(gathered_inputs)).values(): 

1008 for batch in self._split_into_memory_safe_batches(params, shard_size=shard_size): 

1009 updates = self._compute_batched_ns_updates(batch, gathered_inputs, group) 

1010 my_updates.update(updates) 

1011 return my_updates 

1012 

1013 def _process_shard_params( 

1014 self, 

1015 group: Dict[str, Any], 

1016 param_to_ns_input: Dict[torch.nn.Parameter, torch.Tensor], 

1017 hsdp_assignments: List[HSDPGroupAssignment], 

1018 group_idx: int, 

1019 buffer_cache: Optional[Dict] = None, 

1020 overlap_work: Optional[Callable[[], None]] = None, 

1021 ) -> None: 

1022 """Process sharded params with greedy shard-group compute assignment.""" 

1023 shard_compute_coord = self._shard_compute_coord.get(group_idx, {}) 

1024 

1025 for hsdp_assign in hsdp_assignments: 

1026 owned_params = hsdp_assign.owned_params 

1027 # Communication membership is static per assignment. Ranks with empty 

1028 # local shards still participate via build_pad_ns_inputs(). 

1029 valid_params = owned_params 

1030 

1031 shard_sizes, _, shard_pgs, total_shard_size = self._get_shard_info(hsdp_assign) 

1032 

1033 # uneven shard check 

1034 shard_pgs_rank = [] 

1035 for pg in shard_pgs: 

1036 pg_rank = torch.distributed.get_process_group_ranks(pg) 

1037 shard_pgs_rank.append(pg_rank) 

1038 

1039 for p in valid_params: 

1040 if tuple(p.shape)[0] % shard_sizes[0] != 0: 

1041 logger.debug_rank0( 

1042 "[hyper-optimizer uneven-shard] p %s placement %s device_mesh %s " 

1043 "local_shape %s global_shape %s pg_rank %s shard_sizes %s", 

1044 getattr(p, "model_name", None), 

1045 p.placements, 

1046 p.device_mesh, 

1047 p.to_local().shape, 

1048 p.shape, 

1049 shard_pgs_rank, 

1050 shard_sizes, 

1051 ) 

1052 

1053 if valid_params: 

1054 safe_batches = self._split_into_memory_safe_batches( 

1055 valid_params, shard_size=total_shard_size, min_batch_size=total_shard_size 

1056 ) 

1057 for sub_batch in safe_batches: 

1058 my_updates, param_compute_coord = self._gather_and_compute_shard_updates( 

1059 sub_batch, param_to_ns_input, hsdp_assign, 

1060 shard_compute_coord, group, buffer_cache, overlap_work, 

1061 ) 

1062 

1063 self._fused_broadcast_and_apply( 

1064 sub_batch, my_updates, param_compute_coord, 

1065 group, hsdp_assign, overlap_work, 

1066 ) 

1067 

1068 def _group_by_shape( 

1069 self, 

1070 params: List[torch.nn.Parameter], 

1071 ) -> Dict[tuple, List[torch.nn.Parameter]]: 

1072 """Group parameters by their last-2-dim shape (A, B) for batched NS. 

1073 

1074 [1024, 1024], [1024, 1, 1024], and [3, 1024, 1024] all map to 

1075 key (1024, 1024) for maximum batch merging. 

1076 """ 

1077 groups = defaultdict(list) 

1078 

1079 for p in params: 

1080 core_shape = self._shape_to_core_shape(tuple(p.shape)) 

1081 groups[core_shape].append(p) 

1082 

1083 return groups 

1084 

1085 @staticmethod 

1086 def _shape_to_core_shape(shape: Tuple[int, ...]) -> Tuple[int, int]: 

1087 if len(shape) == 2: 

1088 return (shape[0], shape[1]) 

1089 if len(shape) == 3 and shape[1] == 1: 

1090 return (shape[0], shape[2]) 

1091 if len(shape) >= 3: 

1092 return (shape[-2], shape[-1]) 

1093 raise ValueError('1D parameters are not supported in Muon') 

1094 

1095 def _reshape_ns_input( 

1096 self, 

1097 param: torch.nn.Parameter, 

1098 ns_input: torch.Tensor, 

1099 ) -> Tuple[torch.Tensor, List[torch.Tensor]]: 

1100 """Return the contiguous NS input and any reshape views used for NS.""" 

1101 working_input = ns_input if ns_input.is_contiguous() else ns_input.contiguous() 

1102 if self.reshape_fn is None: 

1103 return working_input, [working_input] 

1104 

1105 param_fqn = param.model_name 

1106 if param_fqn is None: 

1107 return working_input, [working_input] 

1108 

1109 reshaped_inputs = list(self.reshape_fn(param_fqn, working_input)) 

1110 if not reshaped_inputs: 

1111 return working_input, [working_input] 

1112 

1113 if reshaped_inputs[0].shape != working_input.shape: 

1114 logger.info_rank0( 

1115 "Reshape %s from %s to %s", 

1116 param_fqn, 

1117 working_input.shape, 

1118 reshaped_inputs[0].shape, 

1119 ) 

1120 

1121 for reshaped_input in reshaped_inputs: 

1122 if reshaped_input.untyped_storage() is not working_input.untyped_storage(): 

1123 raise ValueError("reshape_fn must return views that share storage with the working NS input tensor") 

1124 

1125 return working_input, reshaped_inputs 

1126 

1127 def _prepare_ns_transform( 

1128 self, 

1129 param: torch.nn.Parameter, 

1130 ns_input: torch.Tensor, 

1131 ) -> Tuple[torch.Tensor, NSInputTransform]: 

1132 """Route one parameter through custom, zero-copy, or identity NS preparation.""" 

1133 working_input = ns_input if ns_input.is_contiguous() else ns_input.contiguous() 

1134 param_fqn = getattr(param, "model_name", None) 

1135 if self.ns_transform_fn is not None and param_fqn is not None: 

1136 transform = self.ns_transform_fn(param_fqn, working_input) 

1137 if transform is not None: 

1138 self._validate_ns_transform(transform, working_input) 

1139 return working_input, transform 

1140 

1141 _, reshaped_inputs = self._reshape_ns_input(param, working_input) 

1142 

1143 def restore_view_updates(updates: List[torch.Tensor], output: torch.Tensor) -> None: 

1144 """Write reshaped NS updates back into the views and the working input. 

1145 

1146 Args: 

1147 updates: Reshaped Newton-Schulz updates. 

1148 output: Working buffer receiving the final update. 

1149 """ 

1150 for reshaped_input, update in zip(reshaped_inputs, updates): 

1151 reshaped_input.copy_(update.contiguous().view_as(reshaped_input)) 

1152 if output.untyped_storage() is not working_input.untyped_storage(): 

1153 output.copy_(working_input) 

1154 

1155 return working_input, NSInputTransform(tensors=reshaped_inputs, restore=restore_view_updates) 

1156 

1157 @staticmethod 

1158 def _validate_ns_transform(transform: NSInputTransform, working_input: torch.Tensor) -> None: 

1159 """Validate a model-provided reversible NS transform.""" 

1160 if not isinstance(transform, NSInputTransform): 

1161 raise ValueError( 

1162 "ns_transform_fn must return NSInputTransform or None, " 

1163 f"got {type(transform).__name__}" 

1164 ) 

1165 if not transform.tensors: 

1166 raise ValueError("NSInputTransform.tensors must not be empty") 

1167 for index, tensor in enumerate(transform.tensors): 

1168 if not isinstance(tensor, torch.Tensor): 

1169 raise ValueError(f"NSInputTransform.tensors[{index}] must be a torch.Tensor") 

1170 if tensor.device != working_input.device: 

1171 raise ValueError("NSInputTransform tensors must be on the same device as the NS input") 

1172 if tensor.dtype != working_input.dtype: 

1173 raise ValueError("NSInputTransform tensors must have the same dtype as the NS input") 

1174 if tensor.dim() < 2: 

1175 raise ValueError("NSInputTransform tensors must have at least two dimensions") 

1176 if not callable(transform.restore): 

1177 raise ValueError("NSInputTransform.restore must be callable") 

1178 

1179 def _compute_batched_ns_outputs_for_tensors( 

1180 self, 

1181 tensor_list: List[torch.Tensor], 

1182 ns_steps: int, 

1183 ns_variant: str = "asym5", 

1184 ns_coefficients: Optional[Sequence[Tuple[float, float, float]]] = None, 

1185 ns_epsilon: float = 1e-10, 

1186 ) -> List[torch.Tensor]: 

1187 """Run batched NS on mixed-shape tensors and restore their original shapes.""" 

1188 

1189 if not tensor_list: 

1190 return [] 

1191 

1192 state = {"inputs_3d": [], "slice_sizes": [], "shapes_info": [], "restored_updates": [], "current_idx": 0} 

1193 

1194 for tensor in tensor_list: 

1195 origin_shape = tuple(tensor.shape) 

1196 is_conv = False 

1197 

1198 if len(origin_shape) == 2: 

1199 inp_3d = tensor.unsqueeze(0) 

1200 n_dim = 1 

1201 elif len(origin_shape) == 3 and origin_shape[1] == 1: 

1202 inp_3d = tensor.squeeze(1).unsqueeze(0) 

1203 is_conv = True 

1204 n_dim = 1 

1205 elif len(origin_shape) == 3: 

1206 inp_3d = tensor 

1207 n_dim = origin_shape[0] 

1208 else: 

1209 inp_3d = tensor.reshape(-1, origin_shape[-2], origin_shape[-1]) 

1210 n_dim = inp_3d.shape[0] 

1211 

1212 state["inputs_3d"].append(inp_3d) 

1213 state["slice_sizes"].append(n_dim) 

1214 state["shapes_info"].append((origin_shape, is_conv)) 

1215 

1216 merged_input = torch.cat(state["inputs_3d"], dim=0) 

1217 

1218 if merged_input.shape[0] == 1: 

1219 merged_input = merged_input.squeeze(0) 

1220 

1221 if self.zeropower_fn is None: 

1222 merged_update = zeropower_via_newtonschulz5( 

1223 merged_input, 

1224 steps=ns_steps, 

1225 ns_variant=ns_variant, 

1226 epsilon=ns_epsilon, 

1227 ns_coefficients=ns_coefficients, 

1228 ) 

1229 else: 

1230 merged_update = self.zeropower_fn(merged_input, steps=ns_steps) 

1231 

1232 if merged_input.dim() == 2: 

1233 merged_update = merged_update.unsqueeze(0) 

1234 del merged_input 

1235 

1236 for n_dim, (origin_shape, is_conv) in zip(state["slice_sizes"], state["shapes_info"]): 

1237 update = merged_update[state["current_idx"]:state["current_idx"] + n_dim] 

1238 state["current_idx"] += n_dim 

1239 

1240 if is_conv: 

1241 update = update.squeeze(0).unsqueeze(1) 

1242 elif len(origin_shape) == 2: 

1243 update = update.squeeze(0) 

1244 elif len(origin_shape) >= 4: 

1245 update = update.reshape(origin_shape) 

1246 

1247 state["restored_updates"].append(update) 

1248 

1249 del merged_update 

1250 return state["restored_updates"] 

1251 

1252 def _split_into_memory_safe_batches( 

1253 self, 

1254 p_list: List[torch.nn.Parameter], 

1255 shard_size: int = 1, 

1256 min_batch_size: int = 1, 

1257 ) -> List[List[torch.nn.Parameter]]: 

1258 """Split parameters into memory-safe batches to prevent OOM during NS. 

1259 

1260 The per-batch element limit is scaled down by shard_size to account 

1261 for the memory amplification from allgather. Sharded paths prioritize 

1262 filling the compute-owner ranks before applying this soft limit. 

1263 """ 

1264 max_numel_per_batch = 512 * 1024 * 1024 // shard_size 

1265 min_batch_size = max(1, min_batch_size) 

1266 

1267 batches = [] 

1268 current_batch = [] 

1269 current_count = 0 

1270 

1271 for p in p_list: 

1272 p_count = p.numel() 

1273 if ( 

1274 len(current_batch) >= min_batch_size 

1275 and current_count + p_count > max_numel_per_batch 

1276 ): 

1277 batches.append(current_batch) 

1278 current_batch = [p] 

1279 current_count = p_count 

1280 else: 

1281 current_batch.append(p) 

1282 current_count += p_count 

1283 

1284 if current_batch: 

1285 batches.append(current_batch) 

1286 

1287 return batches 

1288 

1289 def _compute_batched_ns_updates( 

1290 self, 

1291 p_list: List[torch.nn.Parameter], 

1292 ns_inputs: Dict[torch.nn.Parameter, torch.Tensor], 

1293 group: Dict[str, Any], 

1294 no_shard: bool = False 

1295 ) -> Dict[torch.nn.Parameter, torch.Tensor]: 

1296 """Route batched NS through the native or reversible-transform path.""" 

1297 if self.ns_transform_fn is None: 

1298 return self._compute_batched_ns_updates_fast(p_list, ns_inputs, group, no_shard) 

1299 return self._compute_batched_ns_updates_with_transform(p_list, ns_inputs, group, no_shard) 

1300 

1301 def _compute_batched_ns_updates_fast( 

1302 self, 

1303 p_list: List[torch.nn.Parameter], 

1304 ns_inputs: Dict[torch.nn.Parameter, torch.Tensor], 

1305 group: Dict[str, Any], 

1306 no_shard: bool = False, 

1307 ) -> Dict[torch.nn.Parameter, torch.Tensor]: 

1308 """Compute native reshape/view NS updates without transform bookkeeping.""" 

1309 if not p_list: 

1310 return {} 

1311 state = {"reshape_groups": defaultdict(list), "origin_shapes": {}, "working_inputs": {}, "restored": {}} 

1312 for param in p_list: 

1313 local_shape = getattr(param, "local_shape", None) 

1314 if local_shape is None: 

1315 local_shape = to_local_if_dtensor(param.data).shape 

1316 state["origin_shapes"][param] = tuple(local_shape) if no_shard else tuple(param.shape) 

1317 working_input, reshaped_inputs = self._reshape_ns_input( 

1318 param, ns_inputs[param].view(state["origin_shapes"][param]) 

1319 ) 

1320 state["working_inputs"][param] = working_input 

1321 for reshaped_input in reshaped_inputs: 

1322 state["reshape_groups"][self._shape_to_core_shape(tuple(reshaped_input.shape))].append( 

1323 reshaped_input 

1324 ) 

1325 for tensor_list in state["reshape_groups"].values(): 

1326 updates = self._compute_batched_ns_outputs_for_tensors( 

1327 tensor_list, group["ns_steps"], group["ns_variant"], group["ns_coefficients"], group["ns_epsilon"] 

1328 ) 

1329 for reshaped_input, update in zip(tensor_list, updates): 

1330 scale = compute_muon_slice_scale( 

1331 update, group["matched_adamw_rms"], zero_rms_scale_mode=group["zero_rms_scale_mode"] 

1332 ) 

1333 if group["apply_lr_in_update"]: 

1334 scale *= -group["lr"] 

1335 update.mul_(scale) 

1336 reshaped_input.copy_(update.contiguous().view_as(reshaped_input)) 

1337 

1338 for param in p_list: 

1339 update = ns_inputs[param].view(state["origin_shapes"][param]) 

1340 working_input = state["working_inputs"][param] 

1341 if working_input.untyped_storage() is not update.untyped_storage(): 

1342 update.copy_(working_input) 

1343 state["restored"][param] = update 

1344 return state["restored"] 

1345 

1346 def _compute_batched_ns_updates_with_transform( 

1347 self, 

1348 p_list: List[torch.nn.Parameter], 

1349 ns_inputs: Dict[torch.nn.Parameter, torch.Tensor], 

1350 group: Dict[str, Any], 

1351 no_shard: bool = False, 

1352 ) -> Dict[torch.nn.Parameter, torch.Tensor]: 

1353 """Batched Newton-Schulz update for mixed 2D / Conv3D / 3D parameters. 

1354 

1355 Normalizes all inputs to 3D, concatenates along dim 0, runs a single 

1356 NS iteration, then slices results back to original shapes. 

1357 

1358 """ 

1359 

1360 if not p_list: 

1361 return {} 

1362 

1363 state: _TransformNSState = { 

1364 "reshape_groups": defaultdict(list), 

1365 "origin_shapes": {}, 

1366 "working_inputs": {}, 

1367 "transforms": {}, 

1368 "transform_updates": [], 

1369 "restored": {}, 

1370 } 

1371 

1372 for p in p_list: 

1373 state["origin_shapes"][p] = ( 

1374 tuple(to_local_if_dtensor(p.data).shape) if no_shard else tuple(p.shape) 

1375 ) 

1376 prepared = self._prepare_ns_transform(p, ns_inputs[p].view(state["origin_shapes"][p])) 

1377 state["working_inputs"][p] = prepared[0] 

1378 state["transforms"][p] = prepared[1] 

1379 state["transform_updates"].append([None] * len(prepared[1].tensors)) 

1380 

1381 for tensor_index, transformed_input in enumerate(prepared[1].tensors): 

1382 state["reshape_groups"][self._shape_to_core_shape(tuple(transformed_input.shape))].append( 

1383 (transformed_input, len(state["transform_updates"]) - 1, tensor_index) 

1384 ) 

1385 

1386 for tensor_records in state["reshape_groups"].values(): 

1387 reshaped_updates = self._compute_batched_ns_outputs_for_tensors( 

1388 [record[0] for record in tensor_records], 

1389 group["ns_steps"], 

1390 ns_variant=group["ns_variant"], 

1391 ns_coefficients=group["ns_coefficients"], 

1392 ns_epsilon=group["ns_epsilon"], 

1393 ) 

1394 

1395 # Scale updates. 

1396 for record, reshaped_update in zip(tensor_records, reshaped_updates): 

1397 slice_scale = compute_muon_slice_scale( 

1398 reshaped_update, 

1399 group["matched_adamw_rms"], 

1400 zero_rms_scale_mode=group["zero_rms_scale_mode"], 

1401 ) 

1402 

1403 if group["apply_lr_in_update"]: 

1404 slice_scale *= -group["lr"] 

1405 reshaped_update.mul_(slice_scale) 

1406 state["transform_updates"][record[1]][record[2]] = reshaped_update 

1407 

1408 for p, reshaped_updates in zip(p_list, state["transform_updates"]): 

1409 

1410 if any(update is None for update in reshaped_updates): 

1411 raise RuntimeError("Missing Newton-Schulz update for a transformed input") 

1412 state["transforms"][p].restore(reshaped_updates, state["working_inputs"][p]) 

1413 

1414 for p in p_list: 

1415 reshaped_update = ns_inputs[p].view(state["origin_shapes"][p]) 

1416 if state["working_inputs"][p].untyped_storage() is not reshaped_update.untyped_storage(): 

1417 reshaped_update.copy_(state["working_inputs"][p]) 

1418 state["restored"][p] = reshaped_update 

1419 

1420 return state["restored"] 

1421 

1422 def _fused_broadcast_and_apply( 

1423 self, 

1424 valid_params: List[torch.nn.Parameter], 

1425 my_updates: Dict[torch.nn.Parameter, torch.Tensor], 

1426 param_compute_coord: Dict[torch.nn.Parameter, Tuple[int, ...]], 

1427 group: Dict[str, Any], 

1428 hsdp_assign: HSDPGroupAssignment, 

1429 overlap_work: Optional[Callable[[], None]] = None, 

1430 ) -> None: 

1431 """Fused broadcast and apply for shard-group updates.""" 

1432 shard_sizes, local_coords, shard_pgs, total_shard_size = self._get_shard_info(hsdp_assign) 

1433 local_device = to_local_if_dtensor(valid_params[0].data).device 

1434 first_pg = next((pg for pg in shard_pgs if pg is not None), None) 

1435 comm_device = _comm_device_for_group(first_pg, local_device) 

1436 packed = self._pack_shard_updates(valid_params, my_updates, param_compute_coord, local_coords, comm_device) 

1437 if total_shard_size > 1: 

1438 self._batched_relay_broadcast(packed, shard_pgs, shard_sizes, local_coords, overlap_work) 

1439 self._apply_shard_updates(packed, group, hsdp_assign) 

1440 

1441 @staticmethod 

1442 def _pack_shard_updates( 

1443 params: List[torch.nn.Parameter], 

1444 my_updates: Dict[torch.nn.Parameter, torch.Tensor], 

1445 param_compute_coord: Dict[torch.nn.Parameter, Tuple[int, ...]], 

1446 local_coords: Tuple[int, ...], 

1447 device: torch.device, 

1448 buffer_cache: Optional[Dict] = None, 

1449 ) -> _PackedShardUpdates: 

1450 """Pack BF16 updates into one aligned buffer per compute owner.""" 

1451 coord_groups: Dict[Tuple[int, ...], List[torch.nn.Parameter]] = defaultdict(list) 

1452 for p in params: 

1453 coord_groups[param_compute_coord[p]].append(p) 

1454 

1455 alignment_elements = 256 # 512 bytes in BF16 

1456 offsets_by_coord = {} 

1457 sizes = [] 

1458 for coord, coord_params in coord_groups.items(): 

1459 param_offsets = [] 

1460 total_padded_numel = 0 

1461 for p in coord_params: 

1462 actual_numel = p.numel() 

1463 padded_numel = ((actual_numel + alignment_elements - 1) // alignment_elements) * alignment_elements 

1464 param_offsets.append((p, total_padded_numel, actual_numel, padded_numel)) 

1465 total_padded_numel += padded_numel 

1466 

1467 offsets_by_coord[coord] = param_offsets 

1468 sizes.append(total_padded_numel) 

1469 

1470 if buffer_cache is None: 

1471 buffers = (torch.empty(size, dtype=torch.bfloat16, device=device) for size in sizes) 

1472 else: 

1473 total_size = sum(sizes) 

1474 buffer = get_or_alloc_buffer(buffer_cache, device, total_size, torch.bfloat16, device) 

1475 buffers = buffer[:total_size].split(sizes) 

1476 

1477 packed: _PackedShardUpdates = {} 

1478 for (coord, param_offsets), pack_buffer in zip(offsets_by_coord.items(), buffers): 

1479 if coord == local_coords: 

1480 for p, offset, actual_numel, padded_numel in param_offsets: 

1481 update = my_updates[p] 

1482 pack_buffer[offset:offset + actual_numel].view(update.shape).copy_(update) 

1483 if padded_numel > actual_numel: 

1484 pack_buffer[offset + actual_numel:offset + padded_numel].zero_() 

1485 packed[coord] = pack_buffer, [(p, offset, count) for p, offset, count, _ in param_offsets] 

1486 return packed 

1487 

1488 def _apply_shard_updates( 

1489 self, packed: _PackedShardUpdates, group: Dict[str, Any], hsdp_assign: HSDPGroupAssignment, 

1490 ) -> None: 

1491 """Apply the local shard of each update after its broadcast completes.""" 

1492 lr = group["lr"] 

1493 weight_decay = group["weight_decay"] 

1494 all_local_params: List[torch.Tensor] = [] 

1495 all_update_shards: List[torch.Tensor] = [] 

1496 for pack_buffer, param_offsets in packed.values(): 

1497 for p, offset, actual_numel in param_offsets: 

1498 full_update = pack_buffer[offset:offset + actual_numel].view(tuple(p.shape)) 

1499 update_to_apply = chunk_update_by_layout( 

1500 full_update, 

1501 p, 

1502 hsdp_assign.layout_spec, 

1503 self._param_shard_metadata.get(p), 

1504 ) 

1505 

1506 local_param = to_local_if_dtensor(p.data) 

1507 all_local_params.append(local_param) 

1508 if update_to_apply.device != local_param.device: 

1509 # CPU offload: updates were broadcast on the accelerator 

1510 # while the parameter local lives on host. 

1511 update_to_apply = update_to_apply.to(local_param.device) 

1512 all_update_shards.append(update_to_apply.view(local_param.shape)) 

1513 

1514 if not all_local_params: 

1515 return 

1516 

1517 if weight_decay != 0.0: 

1518 coeff = 1.0 - lr * weight_decay 

1519 # pylint: disable=protected-access 

1520 torch._foreach_mul_(all_local_params, coeff) 

1521 

1522 # Slice-wise Muon scaling has already been applied during NS postprocess. 

1523 # pylint: disable=protected-access 

1524 apply_alpha = 1.0 if group["apply_lr_in_update"] else -lr 

1525 torch._foreach_add_(all_local_params, all_update_shards, alpha=apply_alpha) 

1526 

1527 def _build_param_shard_metadata(self) -> None: 

1528 """Build shard metadata once during optimizer init.""" 

1529 self._param_shard_metadata: Dict[torch.nn.Parameter, ParamShardMeta] = {} 

1530 

1531 for _, hsdp_groups in self._hsdp_grouping.values(): 

1532 for hsdp_group in hsdp_groups: 

1533 if hsdp_group.layout_spec is None or not hsdp_group.layout_spec.shard_axes: 

1534 continue 

1535 group_param_to_meta = build_param_shard_metadata_for_group(hsdp_group) 

1536 for param, shard_meta in group_param_to_meta.items(): 

1537 self._param_shard_metadata[param] = shard_meta 

1538 _debug_param_shard_metadata(hsdp_group, group_param_to_meta) 

1539 

1540 @staticmethod 

1541 def _get_shard_info( 

1542 hsdp_assign: HSDPGroupAssignment, 

1543 ) -> Tuple[Tuple[int, ...], Tuple[int, ...], Tuple[dist.ProcessGroup, ...], int]: 

1544 """Extract shard topology from HSDPGroupAssignment. 

1545 

1546 Returns: 

1547 shard_sizes: Size of each shard mesh dimension. 

1548 local_coords: Current rank's coordinate in each shard mesh dim. 

1549 shard_pgs: ProcessGroup for each shard mesh dim. 

1550 total_shard_size: Product of all shard_sizes. 

1551 """ 

1552 shard_pgs = hsdp_assign.shard_pgs 

1553 shard_sizes = tuple( 

1554 dist.get_world_size(pg) if pg is not None else 1 

1555 for pg in shard_pgs 

1556 ) 

1557 local_coords = tuple( 

1558 dist.get_rank(pg) if pg is not None else 0 

1559 for pg in shard_pgs 

1560 ) 

1561 total_shard_size = 1 

1562 for s in shard_sizes: 

1563 total_shard_size *= s 

1564 

1565 return shard_sizes, local_coords, shard_pgs, total_shard_size 

1566 

1567 @classmethod 

1568 def _batched_relay_broadcast( 

1569 cls, 

1570 packed: _PackedShardUpdates, 

1571 shard_pgs: Tuple[dist.ProcessGroup, ...], 

1572 shard_sizes: Tuple[int, ...], 

1573 local_coords: Tuple[int, ...], 

1574 overlap_work: Optional[Callable[[], None]] = None, 

1575 ) -> None: 

1576 """ 

1577 Batched asynchronous multi-dimensional relay broadcast. 

1578 By operating asynchronously within each dimension, we eliminate CPU overhead bubbles 

1579 while strictly preserving the multidimensional relay dependency. 

1580 """ 

1581 for dim_idx, pg in enumerate(shard_pgs): 

1582 if pg is None or shard_sizes[dim_idx] <= 1: 

1583 continue 

1584 

1585 works = cls._launch_shard_axis_broadcasts(packed, pg, dim_idx, local_coords[dim_idx + 1:]) 

1586 try: 

1587 if works and overlap_work is not None: 

1588 overlap_work() 

1589 finally: 

1590 for work in works: 

1591 work.wait() 

1592 

1593 @staticmethod 

1594 def _launch_shard_axis_broadcasts( 

1595 packed: _PackedShardUpdates, 

1596 pg: dist.ProcessGroup, 

1597 dim_idx: int, 

1598 downstream_coords: Tuple[int, ...], 

1599 ) -> List[dist.Work]: 

1600 """Submit the buffers whose source is present on this relay axis.""" 

1601 works = [] 

1602 for coord, (tensor, _) in packed.items(): 

1603 if coord[dim_idx + 1:] != downstream_coords: 

1604 continue 

1605 src = dist.get_global_rank(pg, coord[dim_idx]) 

1606 work = dist.broadcast(tensor, src=src, group=pg, async_op=True) 

1607 if work is not None: 

1608 works.append(work) 

1609 return works