Diff Coverage

Diff: origin/master...HEAD, staged and unstaged changes

Source File Diff Coverage (%) Missing Lines
hyper_parallel/core/optimizer/swap_muon.py 85.6% 515,536,540-541,547-549,564,569,583,676-677,723,752-753,774,793,801,821,824,924-927,929,948-949,952-953,969,980,1037-1042,1044-1045,1060,1069,1081,1087-1088
hyper_parallel/core/optimizer/swap_optimizer_base.py 88.4% 362,365,376,381,400,430,472,474,476,484,489,1067,1071,1079,1583-1584
hyper_parallel/core/optimizer/swap_muon.py
511
512
513
514
515
516
517
518
519
            return super().partition_update_units(units, step_context)

        partitions = self._build_overlap_partitions(list(units))
        if partitions is None:
            return super().partition_update_units(units, step_context)
        planned = self.runtime.partition(
            partitions,
            unit_costs=[partition.logical_nbytes for partition in partitions],
        )
532
533
534
535
536
537
538
539
540
541
542
543
544
545
        if not self._supports_cross_partition_pipeline(batch_lists):
            super().run_pipeline(batch_lists, step_context)
            return

        pipeline = _MuonCrossPartitionPipeline(
            self,
            step_context["broadcaster"],
        )
        try:
            self.runtime.run_delayed_pipeline(
                batch_lists,
                step_context,
                pipeline.consume_batch,
                pipeline.finish,
543
544
545
546
547
548
549
550
551
552
553
                step_context,
                pipeline.consume_batch,
                pipeline.finish,
            )
        except Exception:
            pipeline.abort()
            raise

    def _supports_cross_partition_pipeline(
            self,
            batches: Sequence[Sequence[MuonSwapUnit]],
560
561
562
563
564
565
566
567
568
569
570
571
572
573
        if not self.runtime.supports_delayed_pipeline(batches):
            return False
        for current, following in zip(batches, batches[1:]):
            if not current or not following:
                continue
            current_key = self._shard_pipeline_key(current[-1])
            following_key = self._shard_pipeline_key(following[0])
            if current_key is not None and current_key == following_key:
                return True
        return False

    def _build_overlap_partitions(
            self,
            units: List[MuonSwapUnit],
579
580
581
582
583
584
585
586
587
            for key in (self._shard_pipeline_key(unit),)
            if key is not None
        }
        if not pipeline_local_keys:
            return None

        partitions, local_partitions, target_partitions = self._group_overlap_partitions(
            units,
            pipeline_local_keys,
672
673
674
675
676
677
678
679
680
681
            for key in (self._shard_pipeline_key(unit),)
            if key is not None
        }
        if not pipeline_local_keys:
            self._run_units(batch, broadcaster)
            return

        remaining, local_batches = self._extract_local_overlap_batches(
            batch, pipeline_local_keys,
        )
719
720
721
722
723
724
725
726
727
        shard_runs = {}
        counts = defaultdict(int)
        for run_index, (key, units) in enumerate(runs):
            if key is None:
                continue
            batches = list(self._iter_shard_batches(units))
            shard_runs[run_index] = batches
            if batches:
                counts[batches[0].group_idx, key[0]] += 1
748
749
750
751
752
753
754
755
756
757
    ) -> None:
        """Execute serial runs and native Muon shard pipeline runs in order."""
        for run_index, (key, units) in enumerate(runs):
            if key is None:
                self._run_units(units, broadcaster)
                continue
            planned_batches = shard_runs.get(run_index)
            if planned_batches is None:
                planned_batches = self._iter_shard_batches(units)
            shard_batches = iter(planned_batches)
770
771
772
773
774
775
776
777
778
        """
        for unit in units:
            assignment = unit.hsdp_assign
            if assignment is None:
                raise RuntimeError("Muon swap shard pipeline unit is missing its group assignment.")
            shard_size = dist.get_world_size(assignment.shard_pgs[0])
            batches = self.optimizer._split_into_memory_safe_batches(
                assignment.owned_params,
                shard_size,
789
790
791
792
793
794
795
796
797
    def _drain_local_batches(self, local_batches: Dict[Any, Any]) -> None:
        """Run local work left after the shard communication windows."""
        for (group_index, _), queue in local_batches.items():
            while queue:
                self.optimizer._run_local_batch(group_index, queue)

    def _run_units(
            self,
            units: Iterable[MuonSwapUnit],
797
798
799
800
801
802
803
804
805
            units: Iterable[MuonSwapUnit],
            broadcaster: AsyncReplicateBroadcaster,
    ) -> None:
        """Run units through the serial swap path in schedule order."""
        for unit in units:
            self._run_unit(unit, broadcaster)

    def _shard_pipeline_key(self, unit: MuonSwapUnit) -> Any:
        """Return Muon's overlap key for one sharded swap unit."""
817
818
819
820
821
822
823
824
825
826
827
828
            assignment = unit.hsdp_assign
            if assignment is None or assignment.is_shard or assignment.is_replicated:
                return None
        elif unit.kind != _NO_COMM:
            return None

        if unit.logical_device is None:
            return None
        local_key = unit.group_index, unit.logical_device
        return local_key if local_key in pipeline_local_keys else None

    def _run_unit(self, unit: MuonSwapUnit, broadcaster: AsyncReplicateBroadcaster) -> None:
920
921
922
923
924
925
926
927
928
929
930
931
932
933
            operations = self._plan_operations(batch_index, units)
            self._remaining[batch_index] = len(operations)
            for operation, key, unit, shard_batch in operations:
                if operation == "serial":
                    self._flush_segment()
                    self.adapter._run_unit(unit, self.broadcaster)
                    self._complete_operation(batch_index)
                    continue
                if self._active_key is not None and key != self._active_key:
                    self._flush_segment()
                self._push_shard(batch_index, key, unit, shard_batch)

            self._fed.add(batch_index)
            self._mark_ready(batch_index)
944
945
946
947
948
949
950
951
952
953
954
955
956
        operations = []
        for unit in units:
            key = self.adapter._shard_pipeline_key(unit)
            if key is None:
                operations.append(("serial", None, unit, None))
                continue
            shard_batches = list(self.adapter._iter_shard_batches((unit,)))
            if not shard_batches:
                operations.append(("serial", None, unit, None))
                continue
            self._devices.add(key[0])
            operations.extend(("shard", key, unit, shard_batch) for shard_batch in shard_batches)
        return operations
965
966
967
968
969
970
971
972
973
        """Append one shard batch, starting overlap when its successor arrives."""
        if self._candidate is not None:
            candidate_owner, candidate_key, _, candidate_batch = self._candidate
            if candidate_key != key:
                self._flush_segment()
            else:
                self._start_pipeline(candidate_owner, candidate_key, candidate_batch)
                self._candidate = None
                self._advance_pipeline(owner, batch)
976
977
978
979
980
981
982
983
984
        if self._active_batch is None:
            self._candidate = (owner, key, unit, batch)
            self._active_key = key
            return
        self._advance_pipeline(owner, batch)

    def _start_pipeline(self, owner: int, key: Any, batch: _ShardBatch) -> None:
        """Prepare the first shard batch once a second batch proves overlap useful."""
        self._active_key = key
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049

    def _flush_segment(self) -> None:
        """Finish the current key, retaining Muon's serial single-batch behavior."""
        if self._candidate is not None:
            owner, _, unit, _ = self._candidate
            self.adapter._run_unit(unit, self.broadcaster)
            self._complete_operation(owner)
            self._candidate = None
            self._active_key = None
            return
        if self._active_batch is None:
            self._active_key = None
            return

        self._compute_active()
        self.optimizer._apply_pipeline_batch(self._pending, self.broadcaster)
        self._active_key = None
1056
1057
1058
1059
1060
1061
1062
1063
1064
    def _complete_operation(self, owner: int) -> None:
        """Account for one operation after its momentum state is no longer read."""
        remaining = self._remaining[owner] - 1
        if remaining < 0:
            raise RuntimeError(f"Muon swap batch {owner} completed more work than planned.")
        self._remaining[owner] = remaining
        self._mark_ready(owner)

    def _mark_ready(self, owner: int) -> None:
1065
1066
1067
1068
1069
1070
1071
1072
1073
        """Immediately report a fully fed batch whose momentum is no longer read."""
        if owner not in self._fed or self._remaining.get(owner) != 0 or owner in self._reported:
            return
        if self._report_completion is None:
            raise RuntimeError("Muon swap completion was produced outside the packed runtime callback.")
        self._reported.add(owner)
        self._report_completion(owner)

    def finish(self, step_context: Any, report_completion: Callable[[int], None]) -> None:
1077
1078
1079
1080
1081
1082
1083
1084
1085
        try:
            self._flush_segment()
            incomplete = {owner: count for owner, count in self._remaining.items() if count}
            if incomplete:
                raise RuntimeError(f"Muon cross-partition pipeline left incomplete work: {incomplete}.")
        finally:
            self._report_completion = None

    def abort(self) -> None:
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
            self._report_completion = None

    def abort(self) -> None:
        """Drain submitted device collectives before pipeline scratch is released."""
        for device in self._devices:
            getattr(torch, device.type).synchronize(device)


def build_muon_swap_adapter(optimizer: Any, config: Any, runtime: Any) -> MuonSwapAdapter:
    """Build the Muon swap adapter for ``optimizer``.
hyper_parallel/core/optimizer/swap_optimizer_base.py
358
359
360
361
362
363
364
365
366
367
368
369
                state, completes batches out of order, or omits a batch.
        """
        batch_lists = [list(batch) for batch in batches]
        if not batch_lists:
            return
        has_packed_state = self.supports_packed_pipeline(batch_lists)
        if not has_packed_state and not self._supports_delayed_packed_pipeline(batch_lists):
            raise RuntimeError(
                "Delayed optimizer pipeline requires packed swap state or a packed-enabled zero-transfer step."
            )

        submitted = set()
372
373
374
375
376
377
378
379
380
381
382
383
384
385

        def submit_completion(completed_index: int) -> None:
            nonlocal next_completion
            if completed_index != next_completion:
                raise RuntimeError(
                    "Delayed optimizer pipeline must complete swap batches in order: "
                    f"expected {next_completion}, got {completed_index}."
                )
            if completed_index >= len(batch_lists):
                raise RuntimeError(
                    f"Delayed optimizer pipeline completed unknown batch {completed_index}."
                )
            self.refresh_swappable_slots(batch_lists[completed_index])
            if has_packed_state:
396
397
398
399
400
401
402
403
404
            for batch_index, batch in enumerate(batch_lists):
                consume_batch(batch_index, batch, step_context, submit_completion)
            finish_pipeline(step_context, submit_completion)
            if next_completion != len(batch_lists):
                raise RuntimeError(
                    "Delayed optimizer pipeline did not complete every swap batch: "
                    f"completed {next_completion} of {len(batch_lists)}."
                )
            return
426
427
428
429
430
431
432
433
434
                consume_batch(batch_index, batch, step_context, submit_completion)

            finish_pipeline(step_context, submit_completion)
            if next_completion != len(batch_lists):
                raise RuntimeError(
                    "Delayed optimizer pipeline did not complete every swap batch: "
                    f"completed {next_completion} of {len(batch_lists)}."
                )
            for batch_index in range(len(batch_lists)):
468
469
470
471
472
473
474
475
476
477
478
479
                not completed.
        """
        batch_lists = [list(batch) for batch in batches]
        if not batch_lists:
            return
        if self._packed_enabled:
            raise RuntimeError("Delayed per-tensor pipeline requires packed_swap=False.")
        if not self.supports_delayed_pipeline(batch_lists):
            raise RuntimeError("Delayed per-tensor pipeline does not support this swap schedule.")

        submitted = set()
        next_completion = 0
480
481
482
483
484
485
486
487
488
489
490
491
492
493

        def submit_completion(completed_index: int) -> None:
            nonlocal next_completion
            if completed_index != next_completion:
                raise RuntimeError(
                    "Delayed optimizer pipeline must complete swap batches in order: "
                    f"expected {next_completion}, got {completed_index}."
                )
            if completed_index >= len(batch_lists):
                raise RuntimeError(
                    f"Delayed optimizer pipeline completed unknown batch {completed_index}."
                )
            self.refresh_swappable_slots(batch_lists[completed_index])
            self.offload(batch_lists[completed_index])
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
        logical pipeline so its collective order matches peers that transfer
        state. Such a rank needs no device transfer storage.
        """
        if not batches:
            return False
        swappable_slots = self._swappable_pipeline_slots(batches)
        slot_ids = [id(slot) for slot in swappable_slots]
        if len(slot_ids) != len(set(slot_ids)):
            raise RuntimeError("Delayed optimizer batches contain a duplicate state slot.")
        if not self._packed_enabled:
            return True
        return not swappable_slots or self._supports_packed_slots(swappable_slots)
1075
1076
1077
1078
1079
1080
1081
1082
1083

    def _supports_delayed_packed_pipeline(self, batches: Sequence[Sequence[UpdateUnit]]) -> bool:
        """Return whether packed delayed compute can run, including without local transfers."""
        if not self._packed_enabled or not batches:
            return False
        swappable_slots = self._swappable_pipeline_slots(batches)
        return not swappable_slots or self._supports_packed_slots(swappable_slots)

    @staticmethod
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
        self.runtime.run_pipeline(batches, step_context, self.step_batch)

    def step_batch(self, batch: List[SwapUpdateUnit], step_context: Any) -> Any:
        """Update one resident batch; optimizer-family adapters must implement it."""
        del batch, step_context
        raise NotImplementedError

    def _refresh_packed_state_bindings(self) -> None:
        """Index packed slots by their live optimizer-state owner."""
        bindings = {}