Diff Coverage

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

Source File Diff Coverage (%) Missing Lines
hyper_parallel/core/optimizer/muon.py 54.1% 322,480,496-501,520,553,563,605,615-623,637-639,644-646,664-673,677,679-681,683,693,695-697,699-711,713-714,717-718,723,726-731,734-736,738-739,750-760,961,965-966,980-981,985,998,1007,1018-1022,1441-1444,1455,1457,1460-1462,1464,1469,1472-1473,1475-1476,1478-1480,1482-1485,1487,1490-1491,1497-1502,1586-1589,1591-1592,1602-1610
hyper_parallel/core/optimizer/muon_shard.py 92.0% 219,435,497-498
hyper_parallel/core/optimizer/muon.py
318
319
320
321
322
323
324
325
326
                Both modes support distinct update and buffer coefficients.
        """
        advanced = _resolve_muon_advanced_options(advanced_options)
        if not isinstance(advanced.overlap_shard_comm, bool):
            raise TypeError("overlap_shard_comm must be a bool")
        if momentum_mode not in ("legacy", "vanilla"):
            raise ValueError(
                f"momentum_mode must be 'legacy' or 'vanilla', got {momentum_mode!r}"
            )
476
477
478
479
480
481
482
483
484
                batches = iter(shard_runs[run_idx]) if run_idx in shard_runs else self._iter_shard_batches(run)
                self._process_shard_pipeline(batches, device, broadcaster, local_batches, quotas)
        for (group_idx, _), queue in local_batches.items():
            while queue:
                self._run_local_batch(group_idx, queue)

    def _plan_overlap_batches(
            self, assignments: Iterable[_AssignmentEntry],
    ) -> Tuple[List[_AssignmentEntry], Dict[_LocalQueueKey, _LocalBatches]]:
492
493
494
495
496
497
498
499
500
501
502
503
504
505

        remaining = []
        for group_idx, assignment in entries:
            if not assignment.is_shard and not assignment.is_replicated and assignment.owned_records:
                params = assignment.owned_params
                device = to_local_if_dtensor(params[0]).device
                queue = queues.get((group_idx, device))
                if queue is not None:
                    self._queue_local_batches(params, queue)
                    continue
            remaining.append((group_idx, assignment))
        return remaining, queues

    def _queue_local_batches(self, params: List[torch.nn.Parameter], queue: _LocalBatches) -> None:
516
517
518
519
520
521
522
523
524
        shard_runs = {}
        counts = defaultdict(int)
        for run_idx, (key, run) in enumerate(runs):
            if key is None:
                continue
            device = key[0]
            batches = list(self._iter_shard_batches(run))
            shard_runs[run_idx] = batches
            if batches:
549
550
551
552
553
554
555
556
557
                    device = to_local_if_dtensor(param).device
                    if (group_idx, device) in local_batches:
                        eligible[device].append(param)
                    else:
                        eager.append(param)
                for device, device_params in eligible.items():
                    self._queue_local_batches(device_params, local_batches[(group_idx, device)])
                params = eager
            no_comm_inputs.append(self._update_muon_momentum(group, params) if params else {})
559
560
561
562
563
564
565
566
567
        for group, ns_inputs in zip(self.param_groups, no_comm_inputs):
            if ns_inputs:
                self._process_unshard_params(group, ns_inputs)
                if self.post_update_fn is not None:
                    self._run_post_update_fn(group, ns_inputs.keys())

    def _run_local_batch(self, group_idx: int, queue: Optional[_LocalBatches]) -> None:
        """Submit one local batch on the caller's compute stream."""
        if queue:
601
602
603
604
605
606
607
608
609
            )
        elif ns_inputs:
            self._process_unshard_params(group, ns_inputs)
        if self.post_update_fn is not None:
            self._run_post_update_fn(group, ns_inputs.keys())
        broadcaster.flush_group(assignment)

    def _shard_pipeline_key(
            self, entry: Tuple[int, HSDPGroupAssignment],
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
        """Only look ahead across consecutive assignments with the same communication groups."""
        _, assignment = entry
        if not self.overlap_shard_comm or self.momentum_update_fn is not None or self.post_update_fn is not None:
            return None
        if not assignment.is_shard or len(assignment.shard_pgs) != 1 or not assignment.owned_records:
            return None
        pg = assignment.shard_pgs[0]
        if pg is None or dist.get_world_size(pg) <= 1:
            return None
        device = to_local_if_dtensor(assignment.owned_records[0].param).device
        if device.type not in ("cuda", "npu"):
            return None
        return device, assignment.shard_pgs, assignment.replicate_pgs

    def _iter_shard_batches(self, assignments: Iterable[Tuple[int, HSDPGroupAssignment]]) -> Iterator[_ShardBatch]:
        """Keep the serial shard batch membership and replica flush boundaries."""
        for group_idx, assignment in assignments:
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
    def _prepare_shard_batch(
            self, batch: _ShardBatch, backend: Any, stream: Any, buffers: _ShardPipelineBuffers, slot: int,
    ) -> _GatheredShardBatch:
        """Produce this batch's momentum and gathered inputs on the communication stream."""
        with backend.stream(stream), torch.profiler.record_function("muon.pipeline.gather"):
            ns_inputs = self._update_muon_momentum(self.param_groups[batch.group_idx], batch.params)
            gathered, coords = self._gather_shard_inputs(
                batch.params, ns_inputs, batch.assignment, self._shard_compute_coord[batch.group_idx],
                buffer_cache=buffers.gather, fallback_dtype=torch.bfloat16,
                owner_buffer_cache=buffers.owner_slots[slot],
            )
            ready = backend.Event()
            ready.record(stream)
        return _GatheredShardBatch(batch, gathered, coords, ready)

    def _process_shard_pipeline(
            self, batches: Iterator[_ShardBatch], device: torch.device, broadcaster: AsyncReplicateBroadcaster,
            local_batches: Dict[_LocalQueueKey, _LocalBatches],
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
            overlap_work = partial(self._run_local_window, first.group_idx, queue, windows) if windows else None
            self._process_serial_assignment(first.group_idx, first.assignment, broadcaster, overlap_work)
            return

        backend = getattr(torch, device.type)
        compute_stream = backend.current_stream(device)
        if device not in self._shard_pipeline_streams:
            self._shard_pipeline_streams[device] = backend.Stream(device=device), backend.Stream(device=device)
        comm_stream, apply_stream = self._shard_pipeline_streams[device]
        comm_stream.wait_stream(compute_stream)
        apply_stream.wait_stream(compute_stream)
        buffers = _ShardPipelineBuffers()
        try:
            apply_done = self._run_shard_pipeline(
                chain((first, second), batches), backend, compute_stream, comm_stream, apply_stream,
                broadcaster, local_batches, device, buffers, quotas,
            )
        except Exception:
            # The caller still owns the scratch storage while queued work drains.
            backend.synchronize(device)
            raise
        compute_stream.wait_event(apply_done)
        # The allocator can reuse these communication-stream buffers as soon as this run returns.
        comm_stream.wait_event(apply_done)

    def _run_shard_pipeline(
            self, batches: Iterator[_ShardBatch], backend: Any, compute_stream: Any, comm_stream: Any,
            apply_stream: Any, broadcaster: AsyncReplicateBroadcaster,
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
            device: torch.device, buffers: _ShardPipelineBuffers,
            quotas: _LocalWindowQuotas,
    ) -> Any:
        """Enqueue the stages while keeping the collective order identical across ranks."""
        first = next(batches)

        def run_local(group_idx: int) -> None:
            key = group_idx, device
            self._run_local_window(group_idx, local_batches.get(key), quotas.get(key))

        current = self._prepare_shard_batch(first, backend, comm_stream, buffers, 0)
        run_local(first.group_idx)
        previous = None
        apply_done = None
        for index, following in enumerate(chain(batches, (None,))):
            with torch.profiler.record_function("muon.pipeline.ns"):
                compute_stream.wait_event(current.ready)
                batch = current.batch
                shard_size = dist.get_world_size(batch.assignment.shard_pgs[0])
                group = self.param_groups[batch.group_idx]
                updates = self._compute_shard_updates(current.inputs, group, shard_size)
                ns_done = backend.Event()
                ns_done.record(compute_stream)

            if previous is not None:
                local_group = previous.batch.group_idx
                # The next shard NS is already queued on the compute stream.
                # Independent local work can cover the rest of the older broadcast.
                run_local(local_group)
                apply_done = self._apply_pipeline_batch(previous, backend, apply_stream, compute_stream, broadcaster)

            # Put the next gather ahead of this broadcast on the communication
            # stream so the next NS can run while this broadcast is in flight.
            # At this point the target owner buffer's previous broadcast pack is already queued.
            prefetched = self._prepare_shard_batch(
                following, backend, comm_stream, buffers, (index + 1) % 2,
            ) if following else None
            with backend.stream(comm_stream), torch.profiler.record_function("muon.pipeline.broadcast"):
                comm_stream.wait_event(ns_done)
                if apply_done is not None:
                    comm_stream.wait_event(apply_done)
                pg = batch.assignment.shard_pgs[0]
                packed = self._pack_shard_updates(
                    batch.params, updates, current.compute_coords, (dist.get_rank(pg),), buffers.broadcast,
                )
                works = self._launch_shard_axis_broadcasts(packed, pg, 0, ())
            previous = _BroadcastShardBatch(batch, packed, works)
            current = prefetched

        run_local(batch.group_idx)
        return self._apply_pipeline_batch(previous, backend, apply_stream, compute_stream, broadcaster)

    def _apply_pipeline_batch(
            self,
            pending: _BroadcastShardBatch,
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
            compute_stream: Any,
            broadcaster: AsyncReplicateBroadcaster,
    ) -> Any:
        """Make the apply event the release point for the broadcast slot."""
        batch = pending.batch
        with backend.stream(stream), torch.profiler.record_function("muon.pipeline.apply"):
            for work in pending.works:
                work.wait()
            self._apply_shard_updates(pending.packed, self.param_groups[batch.group_idx], batch.assignment)
            done = backend.Event()
            done.record(stream)
        if batch.last_in_assignment and batch.assignment.is_replicated:
            compute_stream.wait_event(done)
            broadcaster.flush_group(batch.assignment)
        return done

    def _run_post_update_fn(
            self,
            group: Dict[str, Any],
957
958
959
960
961
962
963
964
965
966
967
968
969
970

        Returns:
            (my_updates, param_compute_coord) for this HSDP assignment.
        """
        gathered_inputs, compute_coords = self._gather_shard_inputs(
            valid_params, param_to_ns_input, hsdp_assign, shard_compute_coord, buffer_cache,
            overlap_work=overlap_work,
        )
        shard_size = self._get_shard_info(hsdp_assign)[-1]
        return self._compute_shard_updates(gathered_inputs, group, shard_size), compute_coords

    def _gather_shard_inputs(
            self,
            params: List[torch.nn.Parameter],
976
977
978
979
980
981
982
983
984
985
986
987
988
989
            overlap_work: Optional[Callable[[], None]] = None,
            owner_buffer_cache: Optional[Dict] = None,
    ) -> Tuple[Dict[torch.nn.Parameter, torch.Tensor], Dict[torch.nn.Parameter, Tuple[int, ...]]]:
        """Gather a fused buffer and retain only locally assigned NS inputs."""
        shard_sizes, local_coords, shard_pgs, _ = self._get_shard_info(hsdp_assign)
        param_to_index = {record.param: record.index for record in hsdp_assign.owned_records}
        param_compute_coord: Dict[torch.nn.Parameter, Tuple[int, ...]] = {}
        my_indices: set = set()

        for idx, p in enumerate(params):
            p_index = param_to_index[p]
            compute_coord = shard_compute_coord.get(p_index, (0,) * len(shard_sizes))
            param_compute_coord[p] = compute_coord
            if compute_coord == local_coords:
 994
 995
 996
 997
 998
 999
1000
1001
1002
            param_to_ns_input,
            self._param_shard_metadata,
            fallback_dtype=fallback_dtype,
        )
        param_shard_metadata = [self._param_shard_metadata.get(p) for p in params]
        gathered_list = fused_allgather_dtensor_params(
            local_inputs, shard_pgs, hsdp_assign.layout_spec,
            param_shard_metadata=param_shard_metadata,
            buffer_cache=buffer_cache,
1003
1004
1005
1006
1007
1008
1009
1010
1011
            keep_indices=my_indices,
            while_gathering=overlap_work,
            owner_buffer_cache=owner_buffer_cache,
        )
        return {p: full_input for p, full_input in zip(params, gathered_list)
                if full_input is not None}, param_compute_coord

    def _compute_shard_updates(
            self,
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
            shard_size: int,
    ) -> Dict[torch.nn.Parameter, torch.Tensor]:
        """Use the same NS shape groups for serial and overlapping shard batches."""
        my_updates: Dict[torch.nn.Parameter, torch.Tensor] = {}
        for params in self._group_by_shape(list(gathered_inputs)).values():
            for batch in self._split_into_memory_safe_batches(params, shard_size=shard_size):
                updates = self._compute_batched_ns_updates(batch, gathered_inputs, group)
                my_updates.update(updates)
        return my_updates

    def _process_shard_params(
            self,
            group: Dict[str, Any],
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
            overlap_work: Optional[Callable[[], None]] = None,
    ) -> None:
        """Fused broadcast and apply for shard-group updates."""
        shard_sizes, local_coords, shard_pgs, total_shard_size = self._get_shard_info(hsdp_assign)
        packed = self._pack_shard_updates(valid_params, my_updates, param_compute_coord, local_coords)
        if total_shard_size > 1:
            self._batched_relay_broadcast(packed, shard_pgs, shard_sizes, local_coords, overlap_work)
        self._apply_shard_updates(packed, group, hsdp_assign)

    @staticmethod
    def _pack_shard_updates(
            params: List[torch.nn.Parameter],
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
            local_coords: Tuple[int, ...],
            buffer_cache: Optional[Dict] = None,
    ) -> _PackedShardUpdates:
        """Pack BF16 updates into one aligned buffer per compute owner."""
        device = to_local_if_dtensor(params[0].data).device
        coord_groups: Dict[Tuple[int, ...], List[torch.nn.Parameter]] = defaultdict(list)
        for p in params:
            coord_groups[param_compute_coord[p]].append(p)

        alignment_elements = 256  # 512 bytes in BF16
        offsets_by_coord = {}
        sizes = []
        for coord, coord_params in coord_groups.items():
            param_offsets = []
            total_padded_numel = 0
            for p in coord_params:
                actual_numel = p.numel()
                padded_numel = ((actual_numel + alignment_elements - 1) // alignment_elements) * alignment_elements
                param_offsets.append((p, total_padded_numel, actual_numel, padded_numel))
                total_padded_numel += padded_numel

            offsets_by_coord[coord] = param_offsets
            sizes.append(total_padded_numel)

        if buffer_cache is None:
            buffers = (torch.empty(size, dtype=torch.bfloat16, device=device) for size in sizes)
        else:
            total_size = sum(sizes)
            buffer = get_or_alloc_buffer(buffer_cache, device, total_size, torch.bfloat16, device)
            buffers = buffer[:total_size].split(sizes)

        packed: _PackedShardUpdates = {}
        for (coord, param_offsets), pack_buffer in zip(offsets_by_coord.items(), buffers):
            if coord == local_coords:
                for p, offset, actual_numel, padded_numel in param_offsets:
                    update = my_updates[p]
                    pack_buffer[offset:offset + actual_numel].view(update.shape).copy_(update)
                    if padded_numel > actual_numel:
                        pack_buffer[offset + actual_numel:offset + padded_numel].zero_()
            packed[coord] = pack_buffer, [(p, offset, count) for p, offset, count, _ in param_offsets]
        return packed

    def _apply_shard_updates(
            self, packed: _PackedShardUpdates, group: Dict[str, Any], hsdp_assign: HSDPGroupAssignment,
    ) -> None:
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
    def _apply_shard_updates(
            self, packed: _PackedShardUpdates, group: Dict[str, Any], hsdp_assign: HSDPGroupAssignment,
    ) -> None:
        """Apply the local shard of each update after its broadcast completes."""
        lr = group["lr"]
        weight_decay = group["weight_decay"]
        all_local_params: List[torch.Tensor] = []
        all_update_shards: List[torch.Tensor] = []
        for pack_buffer, param_offsets in packed.values():
            for p, offset, actual_numel in param_offsets:
                full_update = pack_buffer[offset:offset + actual_numel].view(tuple(p.shape))
                update_to_apply = chunk_update_by_layout(
                    full_update,
                    p,
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
        for dim_idx, pg in enumerate(shard_pgs):
            if pg is None or shard_sizes[dim_idx] <= 1:
                continue

            works = cls._launch_shard_axis_broadcasts(packed, pg, dim_idx, local_coords[dim_idx + 1:])
            try:
                if works and overlap_work is not None:
                    overlap_work()
            finally:
                for work in works:
                    work.wait()

    @staticmethod
    def _launch_shard_axis_broadcasts(
            packed: _PackedShardUpdates,
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
            dim_idx: int,
            downstream_coords: Tuple[int, ...],
    ) -> List[dist.Work]:
        """Submit the buffers whose source is present on this relay axis."""
        works = []
        for coord, (tensor, _) in packed.items():
            if coord[dim_idx + 1:] != downstream_coords:
                continue
            src = dist.get_global_rank(pg, coord[dim_idx])
            work = dist.broadcast(tensor, src=src, group=pg, async_op=True)
            if work is not None:
                works.append(work)
        return works
hyper_parallel/core/optimizer/muon_shard.py
215
216
217
218
219
220
221
222
223

    ref_tensor = next(iter(param_to_ns_input.values()), None)
    default_dtype = ref_tensor.dtype if ref_tensor is not None else fallback_dtype
    if default_dtype is None:
        default_dtype = to_local_if_dtensor(comm_params[0].data).dtype
    local_inputs: List[torch.Tensor] = []

    for param in comm_params:
        ns_input = param_to_ns_input.get(param)
431
432
433
434
435
436
437
438
        sum(meta.split_sizes) * math.prod(meta.rest_shape)
        for idx, meta in enumerate(param_meta) if keep_indices is None or idx in keep_indices
    )
    if owner_numel == 0:
        return None
    dtype, device = gathered_view.dtype, gathered_view.device
    return get_or_alloc_buffer(cache, (dtype, device), owner_numel, dtype, device)

493
494
495
496
497
498
499
500
501
502
    if split_sizes == (rows,) * len(split_sizes):
        cols = rows * rest_numel
        output.view(len(split_sizes), cols).copy_(gathered[:, :cols])
    else:
        chunks = [gathered[rank, :rows * rest_numel] for rank, rows in enumerate(split_sizes) if rows > 0]
        torch.cat(chunks, dim=0, out=output)


def fused_allgather_dtensor_params(
        local_tensors: List[torch.Tensor],