Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / core / optimizer / swap_muon.py: 89%
538 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# ============================================================================
15"""Muon momentum-only optimizer-state swap adapter."""
17# pylint: disable=protected-access
19from __future__ import annotations
21from collections import defaultdict, deque
22from dataclasses import dataclass
23from itertools import groupby
24import math
25from typing import Any, Callable, Dict, Iterable, Iterator, List, Optional, Sequence, Tuple
27import torch
28import torch.distributed as dist
30from hyper_parallel.core.optimizer.muon import (
31 Muon,
32 _BroadcastShardBatch,
33 _ShardBatch,
34 _ShardPipelineBuffers,
35)
36from hyper_parallel.core.optimizer.optimizer import AsyncReplicateBroadcaster
37from hyper_parallel.core.optimizer.sharding_category import HSDPGroupAssignment
38from hyper_parallel.core.optimizer.swap_optimizer_base import (
39 StateSwapAdapter,
40 SwapOptimizer as CoreSwapOptimizer,
41 SwapSlot,
42)
44#: Muon's only persistent optimizer state that participates in swap.
45MUON_STATE_KEYS = ("momentum_buffer",)
47_NO_COMM = "no_comm"
48_HSDP = "hsdp"
51@dataclass
52class MuonSwapUnit:
53 """One atomic Muon update unit and the momentum slots it needs.
55 A unit is never split by the pipeline: its parameters run through momentum,
56 Newton-Schulz and the parameter update as one indivisible piece of work, so
57 a single matrix is never partially swapped. ``kind`` only selects which
58 Muon execution path consumes the unit, and ``hsdp_assign`` keeps the
59 original HSDP communication boundary intact.
61 Attributes:
62 group_index: Index of the owning parameter group, derived from
63 ``schedule_key``.
64 kind: ``"no_comm"`` for locally orthonormalized params, ``"hsdp"`` for
65 an HSDP shard/replicate assignment. Derived from ``schedule_key``.
66 params: Parameters this unit updates, in schedule order.
67 slots: Swappable momentum-buffer slots for ``params``.
68 schedule_key: Rank-independent group, kind, assignment and sub-batch indices.
69 logical_nbytes: Full logical momentum bytes, independent of local ownership.
70 hsdp_assign: The original assignment for ``"hsdp"`` units, else ``None``.
71 post_update_params: Parameters whose post-update callbacks run after this
72 unit. Only the final unit of the original Muon update boundary owns
73 this tuple, in the original parameter order.
74 flushes_broadcast: Whether this unit commits its assignment's parameter
75 broadcast. Only the last unit of an assignment sets it, so an
76 assignment split into several NS batches still issues the single
77 flush the bare schedule issues.
78 logical_device: Device shared by the logical parameters before
79 rank-local ownership and gradient filtering.
80 """
82 params: List[torch.nn.Parameter]
83 slots: List[SwapSlot]
84 schedule_key: Tuple[int, str, int, int]
85 logical_nbytes: int
86 hsdp_assign: Optional[HSDPGroupAssignment] = None
87 post_update_params: Tuple[torch.nn.Parameter, ...] = ()
88 flushes_broadcast: bool = False
89 logical_device: Optional[torch.device] = None
91 @property
92 def group_index(self) -> int:
93 """Return the owning parameter-group index from the schedule identity."""
94 return self.schedule_key[0]
96 @property
97 def kind(self) -> str:
98 """Return the execution-path kind from the schedule identity."""
99 return self.schedule_key[1]
102@dataclass
103class _MuonSwapPartitionUnit:
104 """Update units that must stay resident for one native Muon pipeline."""
106 units: List[MuonSwapUnit]
108 @property
109 def logical_nbytes(self) -> int:
110 """Return the rank-independent swap cost of the grouped units."""
111 return sum(unit.logical_nbytes for unit in self.units)
114class MuonSwapAdapter(StateSwapAdapter):
115 """Swap adapter that offloads and prefetches Muon's momentum buffers.
117 The adapter is the swap *coordinator* for Muon, never a second Muon
118 implementation. It replays the schedule of the unmodified ``Muon`` and
119 calls that optimizer's existing execution methods -- momentum,
120 Newton-Schulz, all-gather, broadcast and the parameter write-back all stay
121 in ``muon.py`` as the single source of truth. What the adapter owns is
122 (a) building the atomic update-unit schedule in the original order, and
123 (b) making sure the momentum buffer each unit reads is materialized on the
124 device only for the duration of that unit.
125 """
127 @staticmethod
128 def default_state_keys() -> Tuple[str, ...]:
129 """Return the swap state keys a Muon optimizer owns."""
130 return MUON_STATE_KEYS
132 def validate(self) -> None:
133 """Reject configurations the momentum-only swap path cannot preserve.
135 Raises:
136 ValueError: If a configured state key is not one Muon owns, or a
137 parameter holds momentum state the runtime cannot rebind, or a
138 custom momentum update would lose its original call boundary.
139 """
140 self._validate_configured_state_keys()
141 if self.optimizer.momentum_update_fn is not None:
142 raise ValueError(
143 "Muon swap optimizer does not support momentum_update_fn because "
144 "state partitioning changes its call boundary."
145 )
146 for group in self.optimizer.param_groups:
147 for param in group["params"]:
148 self._validate_param(param)
150 def _validate_configured_state_keys(self) -> None:
151 """Reject a configured swap key that is not Muon state.
153 ``_configured_state_keys`` shares a vocabulary with the other families
154 and silently drops keys none of them implement, so Muon has to check its
155 own selection explicitly: asking to swap ``exp_avg`` on a Muon optimizer
156 must fail rather than quietly swap nothing.
158 Raises:
159 ValueError: If the configured selection names a foreign state key.
160 """
161 if self.config.state_keys is None:
162 return
163 unavailable = sorted(set(self.config.state_keys) - set(self.default_state_keys()))
164 if unavailable:
165 raise ValueError(
166 f"Requested state keys {unavailable} are not available for {type(self.optimizer)!r}; "
167 f"Muon only swaps {self.default_state_keys()}."
168 )
170 def _validate_param(self, param: torch.nn.Parameter) -> None:
171 """Validate one parameter's momentum state is swap-compatible."""
172 state = self.optimizer.state.get(param)
173 if not state:
174 return
175 buffer = state.get("momentum_buffer")
176 if buffer is None:
177 return
178 if getattr(param, "grad", None) is not None and getattr(param.grad, "is_sparse", False):
179 raise ValueError("Muon swap optimizer only supports dense gradients.")
180 local = self._runtime_local_tensor(buffer)
181 if not isinstance(local, torch.Tensor):
182 raise ValueError(
183 f"Muon swap optimizer requires tensor momentum state, got {type(buffer)!r}."
184 )
185 if local.layout != torch.strided:
186 raise ValueError("Muon swap optimizer requires dense momentum state.")
187 if not local.is_contiguous():
188 raise ValueError("Muon swap optimizer requires contiguous momentum state.")
190 @staticmethod
191 def _runtime_local_tensor(tensor: Any) -> Any:
192 """Return the local shard of a possibly distributed tensor."""
193 to_local = getattr(tensor, "to_local", None)
194 return to_local() if callable(to_local) else tensor
196 def _scheduled_param_ids(self) -> Optional[set[int]]:
197 """Return parameters whose Muon state remains authoritative on this rank.
199 ``None`` means the optimizer has no HSDP schedule and therefore all
200 parameters are local. With HSDP metadata present, no-comm parameters,
201 assignment owners and records without an owner retain local state.
202 """
203 schedule = getattr(self.optimizer, "_hsdp_assignment_batches", None)
204 # ``Muon`` initialises this as an empty dict in non-HSDP runs, so an
205 # empty schedule carries no ownership metadata at all: every parameter
206 # is local and pre-existing momentum state must be kept.
207 if not schedule:
208 return None
209 scheduled: set[int] = set()
210 for group_index, group in enumerate(self.optimizer.param_groups):
211 info = schedule.get(group_index)
212 if info is None:
213 scheduled.update(id(param) for param in group["params"])
214 continue
215 scheduled.update(id(param) for param in info.get("no_comm", []))
216 for batch_group in info.get("batch_groups", []):
217 for assignment in batch_group.get("sub_batches", []):
218 scheduled.update(id(param) for param in assignment.owned_params)
219 # Frozen records have no owner and are never broadcast, so
220 # their pre-existing state is not a checkpoint replica.
221 scheduled.update(
222 id(record.param) for record in assignment.all_records
223 if record.index not in assignment.owner_by_index
224 )
225 return scheduled
227 def _params_with_local_state(self, params: Iterable[Any]) -> Iterable[Any]:
228 """Keep checkpoint-restored momentum only when authoritative locally."""
229 scheduled_ids = self._scheduled_param_ids()
230 if scheduled_ids is None:
231 return params
232 return tuple(param for param in params if id(param) in scheduled_ids)
234 def initial_slots(self) -> Iterable[SwapSlot]:
235 """Discover authoritative local momentum state before the first step."""
236 scheduled_ids = self._scheduled_param_ids()
237 slots = []
238 for group in self.optimizer.param_groups:
239 for param in group["params"]:
240 if scheduled_ids is not None and id(param) not in scheduled_ids:
241 # State may have been primed on every rank before this
242 # wrapper was created. Drop replicated non-owner entries
243 # before the swap runtime publishes any slots.
244 self.optimizer.state.pop(param, None)
245 continue
246 state = self.optimizer.state.get(param)
247 if not state:
248 continue
249 for key in self._configured_state_keys():
250 if key in state and (id(param), key) not in self._slots:
251 self._slots[(id(param), key)] = self._make_slot(key, state[key])
252 slots.extend(self._slots_for_params([param]))
253 return tuple(slots)
255 # ------------------------------------------------------------------ schedule
256 def prepare_step(self, *args: Any, **kwargs: Any) -> Dict[str, Any]:
257 """Advance steps, register momentum slots and build the unit schedule.
259 The unit schedule mirrors ``Muon.step()`` exactly: the no-comm params of
260 every group first, then the flattened HSDP assignment schedule, keeping
261 the per-group-then-per-batch nesting so collective order across ranks is
262 unchanged.
264 Returns:
265 Step context holding the ordered units and the step's broadcaster.
267 Raises:
268 ValueError: If extra step arguments are passed.
269 """
270 if args or kwargs:
271 raise ValueError("Muon swap optimizer step does not support closure or extra arguments.")
272 for group in self.optimizer.param_groups:
273 group['step'] = (group.get('step') or 0) + 1
275 units: List[MuonSwapUnit] = []
276 num_groups = len(self.optimizer.param_groups)
277 for group_index in range(num_groups):
278 no_comm_params = self._no_comm_params(group_index)
279 no_comm_batches = list(self._iter_unshard_batches(no_comm_params))
280 for batch_index, params in enumerate(no_comm_batches):
281 post_update_params = no_comm_params if batch_index == len(no_comm_batches) - 1 else ()
282 units.append(self._make_unit(
283 (group_index, _NO_COMM, -1, batch_index), params, params,
284 post_update_params=post_update_params,
285 ))
287 linear_batches = [
288 self._hsdp_linear_batches(group_index) for group_index in range(num_groups)
289 ]
290 max_num_batches = max((len(batches) for batches in linear_batches), default=0)
291 for batch_index in range(max_num_batches):
292 for group_index in range(num_groups):
293 group_batches = linear_batches[group_index]
294 if batch_index >= len(group_batches):
295 continue
296 units.extend(self._make_hsdp_units(group_index, group_batches[batch_index], batch_index))
298 return {
299 "units": units,
300 "broadcaster": AsyncReplicateBroadcaster(self.optimizer),
301 }
303 def _no_comm_params(self, group_index: int) -> List[torch.nn.Parameter]:
304 """Return the params of ``group_index`` that need no HSDP collective.
306 This reads the same private schedule metadata ``Muon.step()`` reads, and
307 falls back to every parameter in the group when no HSDP assignment
308 metadata was built for it -- the same "no HSDP info means all params are
309 no_comm" rule the bare step applies.
310 """
311 info = getattr(self.optimizer, "_hsdp_assignment_batches", {}).get(group_index)
312 if not info:
313 return list(self.optimizer.unshard_params_by_group.get(group_index, []))
314 return list(info.get("no_comm", []))
316 def _hsdp_linear_batches(self, group_index: int) -> List[HSDPGroupAssignment]:
317 """Flatten one group's nested HSDP schedule into a linear batch list."""
318 info = getattr(self.optimizer, "_hsdp_assignment_batches", {}).get(group_index)
319 linear_batches: List[HSDPGroupAssignment] = []
320 if info:
321 for batch_group in info.get("batch_groups", []):
322 linear_batches.extend(batch_group.get("sub_batches", []))
323 return linear_batches
325 def _iter_unshard_batches(
326 self,
327 params: List[torch.nn.Parameter],
328 ) -> Iterator[List[torch.nn.Parameter]]:
329 """Plan logical batches using Muon's existing shape and memory rules."""
330 for shape_group in self.optimizer._group_by_shape(params).values():
331 yield from self.optimizer._split_into_memory_safe_batches(shape_group, shard_size=1)
333 def _make_unit(
334 self,
335 schedule_key: Tuple[int, str, int, int],
336 logical_params: Iterable[torch.nn.Parameter],
337 params: Iterable[torch.nn.Parameter],
338 hsdp_assign: Optional[HSDPGroupAssignment] = None,
339 post_update_params: Iterable[torch.nn.Parameter] = (),
340 flushes_broadcast: bool = False,
341 ) -> MuonSwapUnit:
342 """Project a logical unit onto local gradient-bearing owners and slots."""
343 logical_params = list(logical_params)
344 logical_nbytes = sum(
345 math.prod(param.shape) * self._runtime_local_tensor(param).element_size()
346 for param in logical_params
347 )
348 logical_devices = {self._runtime_local_tensor(param).device for param in logical_params}
349 logical_device = next(iter(logical_devices)) if len(logical_devices) == 1 else None
350 params = [param for param in params if param.grad is not None]
351 post_update_params = tuple(
352 param for param in post_update_params if param.grad is not None
353 )
354 # HSDP assignments contain every logical parameter, but only the local
355 # owner participates in this rank's momentum update. Register state
356 # only for parameters that are actually present in this atomic unit;
357 # otherwise a non-owner would retain a device/host slot indefinitely.
358 for param in params:
359 self._ensure_momentum_state(param)
360 return MuonSwapUnit(
361 params=params,
362 slots=self._slots_for_params(params),
363 schedule_key=schedule_key,
364 logical_nbytes=logical_nbytes,
365 hsdp_assign=hsdp_assign,
366 post_update_params=post_update_params,
367 flushes_broadcast=flushes_broadcast,
368 logical_device=logical_device,
369 )
371 def _make_hsdp_units(
372 self,
373 group_index: int,
374 hsdp_assign: HSDPGroupAssignment,
375 assignment_index: int,
376 ) -> List[MuonSwapUnit]:
377 """Build the units for one HSDP assignment, in assignment order.
379 Sharded assignments stay atomic because the shard executor consumes the
380 entire assignment. For unsharded assignments, every rank derives all
381 owners' NS batches before selecting its own local batch.
382 """
383 if hsdp_assign.is_shard:
384 return [
385 self._make_unit(
386 (group_index, _HSDP, assignment_index, 0),
387 hsdp_assign.all_params, hsdp_assign.owned_params,
388 hsdp_assign, post_update_params=hsdp_assign.owned_params,
389 flushes_broadcast=True,
390 )
391 ]
392 params_by_owner: Dict[Tuple[int, ...], List[torch.nn.Parameter]] = {}
393 for record in hsdp_assign.all_records:
394 owner = hsdp_assign.owner_by_index.get(record.index)
395 # Frozen records remain in all_records but have no assigned owner.
396 # () is a valid owner when there are no replicate dimensions.
397 if owner is None:
398 continue
399 params_by_owner.setdefault(owner, []).append(record.param)
400 batches_by_owner = {
401 owner: list(self._iter_unshard_batches(params_by_owner[owner]))
402 for owner in sorted(params_by_owner)
403 }
404 batch_count = max((len(batches) for batches in batches_by_owner.values()), default=1)
405 local_batches = batches_by_owner.get(hsdp_assign.replicate_group_ranks, [])
406 units = []
407 for index in range(batch_count):
408 logical_params = [
409 param for batches in batches_by_owner.values() if index < len(batches)
410 for param in batches[index]
411 ]
412 local_params = local_batches[index] if index < len(local_batches) else []
413 post_update_params = hsdp_assign.owned_params if index == batch_count - 1 else ()
414 units.append(self._make_unit(
415 (group_index, _HSDP, assignment_index, index),
416 logical_params, local_params, hsdp_assign,
417 post_update_params=post_update_params,
418 flushes_broadcast=index == batch_count - 1,
419 ))
420 return units
422 def _ensure_momentum_state(self, param: torch.nn.Parameter) -> None:
423 """Create the host-resident momentum slot for one parameter.
425 First-step state is created host-side on purpose: the design requires
426 that a freshly created momentum buffer never becomes device-resident
427 outside its own update unit. Parameters without a gradient keep Muon's
428 original skip semantics and get no slot at all.
430 The device shell published into ``state[param]`` is what
431 ``Muon._update_muon_momentum`` reads during this step. That method only
432 allocates momentum when the key is missing, so a registered slot is
433 written in place and never replaced.
434 """
435 if self._runtime_local_tensor(param.grad).layout != torch.strided:
436 raise ValueError("Muon swap optimizer only supports dense gradients.")
437 state = self.optimizer.state[param]
438 for key in self._configured_state_keys():
439 if (id(param), key) in self._slots:
440 continue
441 device_tensor = self.runtime.make_empty_state_like(param)
442 if not self._runtime_local_tensor(device_tensor).is_contiguous():
443 raise ValueError("Muon swap optimizer requires contiguous momentum state.")
444 state[key] = device_tensor
445 slot = self._make_slot(key, device_tensor)
446 if not slot.swappable:
447 # Too small or otherwise ineligible: keep ordinary device state.
448 device_tensor.zero_()
449 self._slots[(id(param), key)] = slot
450 continue
451 slot.cpu_tensor = self.runtime.make_zero_cpu_tensor_like(param)
452 slot.state = "host"
453 self._slots[(id(param), key)] = slot
454 self.runtime.release_device_storage(slot)
456 def _slots_for_params(self, params: Iterable[torch.nn.Parameter]) -> List[SwapSlot]:
457 """Return the registered momentum slots for ``params``, in order.
459 Only slots the adapter already owns are returned: they carry the swap
460 state (host mirror, released device storage, pending event) that the
461 runtime manipulates, so rebuilding a slot here would drop that state.
462 Momentum state materialized before the wrapper was created is registered
463 separately by :meth:`initial_slots`.
464 """
465 keys = self._configured_state_keys()
466 slots = []
467 seen = set()
468 for param in params:
469 for key in keys:
470 slot = self._slots.get((id(param), key))
471 if slot is None or id(slot) in seen:
472 continue
473 slots.append(slot)
474 seen.add(id(slot))
475 return slots
477 # ------------------------------------------------------------------ execution
478 def iter_update_units(self, step_context: Dict[str, Any]) -> List[MuonSwapUnit]:
479 """Return the units built by :meth:`prepare_step`.
481 Args:
482 step_context: Context returned by :meth:`prepare_step`.
484 Returns:
485 Ordered Muon update units for this step.
486 """
487 return step_context["units"]
489 def partition_costs(self, units: Sequence[MuonSwapUnit], step_context: Any) -> Sequence[int]:
490 """Return logical momentum bytes without consulting local slots or gradients.
492 Args:
493 units: Ordered Muon update units.
494 step_context: Unused step context supplied by the shared runtime.
496 Returns:
497 Rank-independent logical byte cost for every unit.
498 """
499 del step_context
500 return [unit.logical_nbytes for unit in units]
502 def partition_update_units(
503 self,
504 units: Sequence[MuonSwapUnit],
505 step_context: Any,
506 ) -> List[List[MuonSwapUnit]]:
507 """Keep the minimum native overlap window resident in each swap batch.
509 Args:
510 units: Ordered Muon update units.
511 step_context: Context returned by :meth:`prepare_step`.
513 Returns:
514 Swap batches with native overlap windows kept intact.
515 """
516 if not self.optimizer.overlap_shard_comm:
517 return super().partition_update_units(units, step_context)
519 partitions = self._build_overlap_partitions(list(units))
520 if partitions is None:
521 return super().partition_update_units(units, step_context)
522 planned = self.runtime.partition(
523 partitions,
524 unit_costs=[partition.logical_nbytes for partition in partitions],
525 )
526 return [
527 [unit for partition in batch for unit in partition.units]
528 for batch in planned
529 ]
531 def run_pipeline(
532 self,
533 batches: Sequence[Sequence[MuonSwapUnit]],
534 step_context: Any,
535 ) -> None:
536 """Keep one native shard pipeline alive across logical swap batches."""
537 batch_lists = [list(batch) for batch in batches]
538 if not self._supports_cross_partition_pipeline(batch_lists):
539 super().run_pipeline(batch_lists, step_context)
540 return
542 pipeline = _MuonCrossPartitionPipeline(
543 self,
544 step_context["broadcaster"],
545 )
546 try:
547 self.runtime.run_delayed_pipeline(
548 batch_lists,
549 step_context,
550 pipeline.consume_batch,
551 pipeline.finish,
552 )
553 except Exception:
554 pipeline.abort()
555 raise
557 def _supports_cross_partition_pipeline(
558 self,
559 batches: Sequence[Sequence[MuonSwapUnit]],
560 ) -> bool:
561 """Return whether logical batches contain a shard run crossing a boundary."""
562 if not self.optimizer.overlap_shard_comm or len(batches) < 2:
563 return False
564 if any(unit.kind != _HSDP for batch in batches for unit in batch):
565 return False
566 if not self.runtime.supports_delayed_pipeline(batches):
567 return False
568 for current, following in zip(batches, batches[1:]):
569 if not current or not following:
570 continue
571 current_key = self._shard_pipeline_key(current[-1])
572 following_key = self._shard_pipeline_key(following[0])
573 if current_key is not None and current_key == following_key:
574 return True
575 return False
577 def _build_overlap_partitions(
578 self,
579 units: List[MuonSwapUnit],
580 ) -> Optional[List[_MuonSwapPartitionUnit]]:
581 """Pair shard units and attach local work to otherwise single-unit runs."""
582 pipeline_local_keys = {
583 (unit.group_index, key[0])
584 for unit in units
585 for key in (self._shard_pipeline_key(unit),)
586 if key is not None
587 }
588 if not pipeline_local_keys:
589 return None
591 partitions, local_partitions, target_partitions = self._group_overlap_partitions(
592 units,
593 pipeline_local_keys,
594 )
595 moved_partition_ids = self._attach_local_overlap_partitions(local_partitions, target_partitions)
596 return [partition for partition in partitions if id(partition) not in moved_partition_ids]
598 def _group_overlap_partitions(
599 self,
600 units: List[MuonSwapUnit],
601 pipeline_local_keys: set[Tuple[int, torch.device]],
602 ) -> Tuple[
603 List[_MuonSwapPartitionUnit],
604 Dict[Tuple[int, torch.device], deque],
605 Dict[Tuple[int, torch.device], deque],
606 ]:
607 """Build shard pairs and index movable local and singleton shard units."""
608 local_partitions: Dict[Tuple[int, torch.device], deque] = defaultdict(deque)
609 target_partitions: Dict[Tuple[int, torch.device], deque] = defaultdict(deque)
610 partitions: List[_MuonSwapPartitionUnit] = []
612 for key, run in groupby(units, key=self._shard_pipeline_key):
613 run_units = list(run)
614 if key is None:
615 for unit in run_units:
616 partition = _MuonSwapPartitionUnit([unit])
617 partitions.append(partition)
618 local_key = self._local_overlap_key(unit, pipeline_local_keys)
619 if local_key is not None:
620 local_partitions[local_key].append(partition)
621 continue
623 for start in range(0, len(run_units), 2):
624 partition = _MuonSwapPartitionUnit(run_units[start:start + 2])
625 partitions.append(partition)
626 if len(partition.units) == 1:
627 unit = partition.units[0]
628 target_partitions[(unit.group_index, key[0])].append(partition)
629 return partitions, local_partitions, target_partitions
631 @staticmethod
632 def _attach_local_overlap_partitions(
633 local_partitions: Dict[Tuple[int, torch.device], deque],
634 target_partitions: Dict[Tuple[int, torch.device], deque],
635 ) -> set[int]:
636 """Move at most one matching local unit into every singleton shard window."""
637 moved_partition_ids = set()
638 for local_key, targets in target_partitions.items():
639 candidates = local_partitions.get(local_key)
640 while candidates and targets:
641 local_partition = candidates.popleft()
642 targets.popleft().units.extend(local_partition.units)
643 moved_partition_ids.add(id(local_partition))
644 return moved_partition_ids
646 def step_batch(self, batch: List[MuonSwapUnit], step_context: Dict[str, Any]) -> None:
647 """Run one prefetched batch of Muon update units.
649 The runtime has already waited for this batch's H2D before calling in,
650 so every slot the batch reads is device-resident here.
652 Args:
653 batch: Resident update units assigned to this swap partition.
654 step_context: Context holding the step broadcaster.
655 """
656 broadcaster = step_context["broadcaster"]
657 if self.optimizer.overlap_shard_comm:
658 self._run_overlap_batch(batch, broadcaster)
659 return
660 for unit in batch:
661 self._run_unit(unit, broadcaster)
663 def _run_overlap_batch(
664 self,
665 batch: List[MuonSwapUnit],
666 broadcaster: AsyncReplicateBroadcaster,
667 ) -> None:
668 """Run overlap-eligible units through Muon's native shard pipeline.
670 Swap batches remain the residency boundary: only momentum slots already
671 prefetched for ``batch`` may participate in a run. Muon reconnects its
672 final apply event to the current compute stream before returning, so the
673 swap runtime can safely use its existing current-stream event for D2H.
674 """
675 pipeline_local_keys = {
676 (unit.group_index, key[0])
677 for unit in batch
678 for key in (self._shard_pipeline_key(unit),)
679 if key is not None
680 }
681 if not pipeline_local_keys:
682 self._run_units(batch, broadcaster)
683 return
685 remaining, local_batches = self._extract_local_overlap_batches(
686 batch, pipeline_local_keys,
687 )
688 runs = self._build_overlap_runs(remaining)
689 shard_runs, quotas = self._plan_local_overlap(runs, local_batches)
690 self._execute_overlap_runs(runs, shard_runs, local_batches, quotas, broadcaster)
691 self._drain_local_batches(local_batches)
693 def _extract_local_overlap_batches(
694 self,
695 batch: List[MuonSwapUnit],
696 pipeline_local_keys: set[Tuple[int, torch.device]],
697 ) -> Tuple[List[MuonSwapUnit], Dict[Any, Any]]:
698 """Move independent resident units into Muon's local work queues."""
699 local_batches = {}
700 local_unit_ids = set()
701 for unit in batch:
702 local_key = self._local_overlap_key(unit, pipeline_local_keys)
703 if local_key is None:
704 continue
705 if unit.params:
706 local_batches.setdefault(local_key, deque()).append(unit.params)
707 local_unit_ids.add(id(unit))
708 return [unit for unit in batch if id(unit) not in local_unit_ids], local_batches
710 def _build_overlap_runs(self, units: List[MuonSwapUnit]) -> List[Tuple[Any, List[MuonSwapUnit]]]:
711 """Group consecutive units by Muon's native shard pipeline key."""
712 return [
713 (key, list(units))
714 for key, units in groupby(units, key=self._shard_pipeline_key)
715 ]
717 def _plan_local_overlap(
718 self,
719 runs: List[Tuple[Any, List[MuonSwapUnit]]],
720 local_batches: Dict[Any, Any],
721 ) -> Tuple[Dict[int, Any], Dict[Any, Any]]:
722 """Plan local windows from the resident shard parameters only."""
723 if not local_batches:
724 return {}, {}
725 shard_runs = {}
726 counts = defaultdict(int)
727 for run_index, (key, units) in enumerate(runs):
728 if key is None:
729 continue
730 batches = list(self._iter_shard_batches(units))
731 shard_runs[run_index] = batches
732 if batches:
733 counts[batches[0].group_idx, key[0]] += 1
734 for shard_batch in batches:
735 counts[shard_batch.group_idx, key[0]] += 1
737 quotas = {}
738 for local_key, windows in counts.items():
739 num_local = len(local_batches.get(local_key, ()))
740 if num_local:
741 quotas[local_key] = deque(
742 (index + 1) * num_local // windows - index * num_local // windows
743 for index in range(windows)
744 )
745 return shard_runs, quotas
747 def _execute_overlap_runs(
748 self,
749 runs: List[Tuple[Any, List[MuonSwapUnit]]],
750 shard_runs: Dict[int, Any],
751 local_batches: Dict[Any, Any],
752 quotas: Dict[Any, Any],
753 broadcaster: AsyncReplicateBroadcaster,
754 ) -> None:
755 """Execute serial runs and native Muon shard pipeline runs in order."""
756 for run_index, (key, units) in enumerate(runs):
757 if key is None:
758 self._run_units(units, broadcaster)
759 continue
760 planned_batches = shard_runs.get(run_index)
761 if planned_batches is None:
762 planned_batches = self._iter_shard_batches(units)
763 shard_batches = iter(planned_batches)
764 self.optimizer._process_shard_pipeline(
765 shard_batches, key[0], broadcaster, local_batches, quotas,
766 )
768 def _iter_shard_batches(self, units: Iterable[MuonSwapUnit]) -> Iterator[_ShardBatch]:
769 """Build native shard batches without changing assignment membership.
771 ``unit.params`` is the local projection whose active momentum state is
772 resident in this swap batch. Muon's shard collectives, however, are
773 defined over the complete owner assignment, including parameters whose
774 gradient is absent on this step. Keep those two concerns separate so
775 batch boundaries and collective payloads stay identical to native Muon.
776 """
777 for unit in units:
778 assignment = unit.hsdp_assign
779 if assignment is None:
780 raise RuntimeError("Muon swap shard pipeline unit is missing its group assignment.")
781 shard_size = dist.get_world_size(assignment.shard_pgs[0])
782 batches = self.optimizer._split_into_memory_safe_batches(
783 assignment.owned_params,
784 shard_size,
785 shard_size,
786 )
787 for batch_index, params in enumerate(batches):
788 yield _ShardBatch(
789 unit.group_index,
790 assignment,
791 params,
792 batch_index == len(batches) - 1,
793 )
795 def _drain_local_batches(self, local_batches: Dict[Any, Any]) -> None:
796 """Run local work left after the shard communication windows."""
797 for (group_index, _), queue in local_batches.items():
798 while queue:
799 self.optimizer._run_local_batch(group_index, queue)
801 def _run_units(
802 self,
803 units: Iterable[MuonSwapUnit],
804 broadcaster: AsyncReplicateBroadcaster,
805 ) -> None:
806 """Run units through the serial swap path in schedule order."""
807 for unit in units:
808 self._run_unit(unit, broadcaster)
810 def _shard_pipeline_key(self, unit: MuonSwapUnit) -> Any:
811 """Return Muon's overlap key for one sharded swap unit."""
812 if unit.kind != _HSDP or unit.hsdp_assign is None:
813 return None
814 return self.optimizer._shard_pipeline_key((unit.group_index, unit.hsdp_assign))
816 def _local_overlap_key(
817 self,
818 unit: MuonSwapUnit,
819 pipeline_local_keys: set[Tuple[int, torch.device]],
820 ) -> Optional[Tuple[int, torch.device]]:
821 """Return the matching shard run for independent local work."""
822 if unit.kind == _HSDP:
823 assignment = unit.hsdp_assign
824 if assignment is None or assignment.is_shard or assignment.is_replicated:
825 return None
826 elif unit.kind != _NO_COMM:
827 return None
829 if unit.logical_device is None:
830 return None
831 local_key = unit.group_index, unit.logical_device
832 return local_key if local_key in pipeline_local_keys else None
834 def _run_unit(self, unit: MuonSwapUnit, broadcaster: AsyncReplicateBroadcaster) -> None:
835 """Run one atomic update unit with the matching Muon method."""
836 kind = unit.kind
837 if kind not in (_NO_COMM, _HSDP):
838 raise ValueError(f"Unknown Muon swap unit kind {kind!r}.")
839 group = self.optimizer.param_groups[unit.group_index]
840 ns_inputs = self.optimizer._update_muon_momentum(group, unit.params)
841 if kind == _NO_COMM:
842 self._apply_unshard_update(group, ns_inputs)
843 else:
844 hsdp_assign = unit.hsdp_assign
845 if hsdp_assign is None:
846 raise RuntimeError("Muon swap HSDP unit is missing its group assignment.")
847 if hsdp_assign.is_shard:
848 self.optimizer._process_shard_params(
849 group, ns_inputs, [hsdp_assign], unit.group_index,
850 buffer_cache={},
851 )
852 else:
853 self._apply_unshard_update(group, ns_inputs)
854 if self.optimizer.post_update_fn is not None and unit.post_update_params:
855 self.optimizer._run_post_update_fn(group, unit.post_update_params)
856 # Flush at the global assignment boundary, after owner callbacks, even
857 # when this rank has no local updates in the last logical unit.
858 if unit.flushes_broadcast:
859 broadcaster.flush_group(unit.hsdp_assign)
861 def _apply_unshard_update(
862 self,
863 group: Dict[str, Any],
864 ns_inputs: Dict[torch.nn.Parameter, torch.Tensor],
865 ) -> None:
866 """Run the unsharded NS and parameter update for one unit."""
867 if not ns_inputs:
868 return
869 # Muon's own helper re-groups by shape and re-splits into memory-safe
870 # batches; a unit's params are already one such batch, so the split is a
871 # single group and the boundary cannot drift.
872 self.optimizer._process_unshard_params(group, ns_inputs)
874 def finish_step(self, step_context: Any) -> None:
875 """Wait for every parameter broadcast issued during this step.
877 Args:
878 step_context: Context holding the step broadcaster.
879 """
880 step_context["broadcaster"].wait_all()
883class _MuonCrossPartitionPipeline:
884 """Incrementally replay Muon's shard pipeline over swap residency windows.
886 The class only schedules Muon's existing gather, Newton-Schulz, broadcast
887 and apply helpers. It does not implement optimizer math. A swap batch is
888 reported complete after every momentum buffer in it has been consumed, so
889 the packed runtime may reuse that batch's staging arena without breaking the
890 communication pipeline.
891 """
893 def __init__(
894 self,
895 adapter: MuonSwapAdapter,
896 broadcaster: AsyncReplicateBroadcaster,
897 ) -> None:
898 """Bind the adapter and initialize an empty native pipeline."""
899 self.adapter = adapter
900 self.optimizer = adapter.optimizer
901 self.broadcaster = broadcaster
902 self._remaining: Dict[int, int] = {}
903 self._fed = set()
904 self._reported = set()
905 self._report_completion: Optional[Callable[[int], None]] = None
906 self._candidate = None
907 self._active_key = None
908 self._active_batch = None
909 self._active_inputs = None
910 self._active_coords = None
911 self._pending = None
912 self._buffers = None
913 self._devices = set()
915 def consume_batch(
916 self,
917 batch_index: int,
918 units: List[MuonSwapUnit],
919 step_context: Any,
920 report_completion: Callable[[int], None],
921 ) -> None:
922 """Feed one resident swap batch and immediately report releasable state."""
923 del step_context
924 self._report_completion = report_completion
925 try:
926 operations = self._plan_operations(batch_index, units)
927 self._remaining[batch_index] = len(operations)
928 for operation, key, unit, shard_batch in operations:
929 if operation == "serial":
930 self._flush_segment()
931 self.adapter._run_unit(unit, self.broadcaster)
932 self._complete_operation(batch_index)
933 continue
934 if self._active_key is not None and key != self._active_key:
935 self._flush_segment()
936 self._push_shard(batch_index, key, unit, shard_batch)
938 self._fed.add(batch_index)
939 self._mark_ready(batch_index)
940 finally:
941 self._report_completion = None
943 def _plan_operations(
944 self,
945 batch_index: int,
946 units: List[MuonSwapUnit],
947 ) -> List[Tuple[str, Any, MuonSwapUnit, Optional[_ShardBatch]]]:
948 """Materialize operation counts before callbacks can complete a batch."""
949 del batch_index
950 operations = []
951 for unit in units:
952 key = self.adapter._shard_pipeline_key(unit)
953 if key is None:
954 operations.append(("serial", None, unit, None))
955 continue
956 shard_batches = list(self.adapter._iter_shard_batches((unit,)))
957 if not shard_batches:
958 operations.append(("serial", None, unit, None))
959 continue
960 self._devices.add(key[0])
961 operations.extend(("shard", key, unit, shard_batch) for shard_batch in shard_batches)
962 return operations
964 def _push_shard(
965 self,
966 owner: int,
967 key: Any,
968 unit: MuonSwapUnit,
969 batch: _ShardBatch,
970 ) -> None:
971 """Append one shard batch, starting overlap when its successor arrives."""
972 if self._candidate is not None:
973 candidate_owner, candidate_key, _, candidate_batch = self._candidate
974 if candidate_key != key:
975 self._flush_segment()
976 else:
977 self._start_pipeline(candidate_owner, candidate_key, candidate_batch)
978 self._candidate = None
979 self._advance_pipeline(owner, batch)
980 return
982 if self._active_batch is None:
983 self._candidate = (owner, key, unit, batch)
984 self._active_key = key
985 return
986 self._advance_pipeline(owner, batch)
988 def _start_pipeline(self, owner: int, key: Any, batch: _ShardBatch) -> None:
989 """Prepare the first shard batch once a second batch proves overlap useful."""
990 self._active_key = key
991 self._buffers = _ShardPipelineBuffers()
992 self._active_batch = batch
993 self._active_inputs, self._active_coords = self.optimizer._prepare_shard_batch(
994 batch,
995 self._buffers,
996 lambda: None,
997 )
998 # Prepare has updated momentum and moved all following work onto
999 # independent pipeline buffers, so the packed state may leave now.
1000 self._complete_operation(owner)
1002 def _advance_pipeline(self, owner: int, batch: _ShardBatch) -> None:
1003 """Gather the following shard while computing and broadcasting the active one."""
1004 inputs, coords = self.optimizer._prepare_shard_batch(
1005 batch,
1006 self._buffers,
1007 self._compute_active,
1008 )
1009 self._active_batch = batch
1010 self._active_inputs = inputs
1011 self._active_coords = coords
1012 self._complete_operation(owner)
1014 def _compute_active(self) -> None:
1015 """Run Muon's unchanged compute/broadcast body for the active shard."""
1016 batch = self._active_batch
1017 pg = batch.assignment.shard_pgs[0]
1018 with torch.profiler.record_function("muon.pipeline.ns"):
1019 updates = self.optimizer._compute_shard_updates(
1020 self._active_inputs,
1021 self.optimizer.param_groups[batch.group_idx],
1022 dist.get_world_size(pg),
1023 )
1025 if self._pending is not None:
1026 self.optimizer._apply_pipeline_batch(self._pending, self.broadcaster)
1028 with torch.profiler.record_function("muon.pipeline.broadcast"):
1029 packed = self.optimizer._pack_shard_updates(
1030 batch.params,
1031 updates,
1032 self._active_coords,
1033 (dist.get_rank(pg),),
1034 device=self._active_key[0],
1035 buffer_cache=self._buffers.broadcast,
1036 )
1037 works = self.optimizer._launch_shard_axis_broadcasts(packed, pg, 0, ())
1038 self._pending = _BroadcastShardBatch(batch, packed, works)
1040 def _flush_segment(self) -> None:
1041 """Finish the current key, retaining Muon's serial single-batch behavior."""
1042 if self._candidate is not None:
1043 owner, _, unit, _ = self._candidate
1044 self.adapter._run_unit(unit, self.broadcaster)
1045 self._complete_operation(owner)
1046 self._candidate = None
1047 self._active_key = None
1048 return
1049 if self._active_batch is None:
1050 self._active_key = None
1051 return
1053 self._compute_active()
1054 self.optimizer._apply_pipeline_batch(self._pending, self.broadcaster)
1055 self._active_key = None
1056 self._active_batch = None
1057 self._active_inputs = None
1058 self._active_coords = None
1059 self._pending = None
1060 self._buffers = None
1062 def _complete_operation(self, owner: int) -> None:
1063 """Account for one operation after its momentum state is no longer read."""
1064 remaining = self._remaining[owner] - 1
1065 if remaining < 0:
1066 raise RuntimeError(f"Muon swap batch {owner} completed more work than planned.")
1067 self._remaining[owner] = remaining
1068 self._mark_ready(owner)
1070 def _mark_ready(self, owner: int) -> None:
1071 """Immediately report a fully fed batch whose momentum is no longer read."""
1072 if owner not in self._fed or self._remaining.get(owner) != 0 or owner in self._reported:
1073 return
1074 if self._report_completion is None:
1075 raise RuntimeError("Muon swap completion was produced outside the packed runtime callback.")
1076 self._reported.add(owner)
1077 self._report_completion(owner)
1079 def finish(self, step_context: Any, report_completion: Callable[[int], None]) -> None:
1080 """Flush the final native pipeline and immediately release remaining state."""
1081 del step_context
1082 self._report_completion = report_completion
1083 try:
1084 self._flush_segment()
1085 incomplete = {owner: count for owner, count in self._remaining.items() if count}
1086 if incomplete:
1087 raise RuntimeError(f"Muon cross-partition pipeline left incomplete work: {incomplete}.")
1088 finally:
1089 self._report_completion = None
1091 def abort(self) -> None:
1092 """Drain submitted device collectives before pipeline scratch is released."""
1093 for device in self._devices:
1094 getattr(torch, device.type).synchronize(device)
1097def build_muon_swap_adapter(optimizer: Any, config: Any, runtime: Any) -> MuonSwapAdapter:
1098 """Build the Muon swap adapter for ``optimizer``.
1100 Args:
1101 optimizer: Muon optimizer instance.
1102 config: Resolved ``SwapOptimizerConfig``.
1103 runtime: Shared ``PipelineSwapRuntime``.
1105 Returns:
1106 The Muon swap adapter.
1108 Raises:
1109 ValueError: If ``optimizer`` is not a Muon optimizer.
1110 """
1111 if not isinstance(optimizer, Muon):
1112 raise ValueError(
1113 "Swap muon only supports hyper_parallel.core.optimizer.muon.Muon. "
1114 f"Got {type(optimizer)!r}."
1115 )
1116 return MuonSwapAdapter(optimizer, config, runtime)
1119def swap_muon(optimizer: Any, config: Any) -> Any:
1120 """Wrap a Muon optimizer with momentum-only state swap.
1122 Args:
1123 optimizer: Muon optimizer instance.
1124 config: Resolved ``SwapOptimizerConfig``. Packed swap preserves Muon's
1125 logical units and only coalesces their momentum transfers.
1127 Returns:
1128 The shared core swap-optimizer wrapper.
1129 """
1130 return CoreSwapOptimizer(
1131 optimizer,
1132 config,
1133 adapter_factory=build_muon_swap_adapter,
1134 )