Diff Coverage

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

Source File Diff Coverage (%) Missing Lines
hyper_parallel/core/optimizer/muon.py 35.9% 307,441,449-450,452-453,459-464,466-473,475-476,480-481,490-495,497-500,511-514,535,541,551-559,563-567,571-573,577-579,586-592,594-612,614-615,618-620,624-632,634-635,645-652,853,857-858,871-872,876,889,897,908-914,1333-1336,1346,1348,1351-1352,1354,1359,1363-1365,1368-1369,1375-1380,1464-1467,1469-1470,1480-1488
hyper_parallel/core/optimizer/muon_shard.py 80.0% 221,407
hyper_parallel/core/optimizer/muon.py
303
304
305
306
307
308
309
310
311
                Both modes support distinct update and buffer coefficients.
        """
        advanced = _resolve_muon_advanced_options(advanced_options)
        if not isinstance(advanced.fsdp_overlap, bool):
            raise TypeError("fsdp_overlap 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}"
            )
437
438
439
440
441
442
443
444
445
        local_batches: Dict[_LocalQueueKey, _LocalBatches] = {}
        if self.fsdp_overlap and all(callback is None for callback in (
                self.momentum_update_fn, self.post_update_fn, self.reshape_fn, self.ns_transform_fn,
        )):
            assignments, local_batches = self._plan_overlap_batches(assignments)
        self._process_no_comm_params(local_batches)

        for key, run in groupby(assignments, self._shard_pipeline_key):
            if key is None:
445
446
447
448
449
450
451
452
453
454
455
456
457
            if key is None:
                for group_idx, assignment in run:
                    self._process_serial_assignment(group_idx, assignment, broadcaster)
            else:
                device, _, _ = key
                self._process_shard_pipeline(self._iter_shard_batches(run), device, broadcaster, local_batches)
        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]]:
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
    def _plan_overlap_batches(
            self, assignments: Iterable[_AssignmentEntry],
    ) -> Tuple[List[_AssignmentEntry], Dict[_LocalQueueKey, _LocalBatches]]:
        """Extract updates that need neither shard collectives nor replica synchronization."""
        entries = list(assignments)
        queues: Dict[_LocalQueueKey, _LocalBatches] = {}
        for entry in entries:
            pipeline_key = self._shard_pipeline_key(entry)
            if pipeline_key is not None:
                queues.setdefault((entry[0], pipeline_key[0]), deque())

        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:
        """Plan local work while keeping pending entries free of temporary tensors."""
        for shape_group in self._group_by_shape([param for param in params if param.grad is not None]).values():
            queue.extend(self._split_into_memory_safe_batches(shape_group, shard_size=1))

    def _process_no_comm_params(self, local_batches: Dict[_LocalQueueKey, _LocalBatches]) -> None:
        """Use the same local queue for parameters outside HSDP assignments."""
        no_comm_inputs = []
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
        for group_idx, group in enumerate(self.param_groups):
            info = self._hsdp_assignment_batches.get(group_idx)
            params = info.get("no_comm", []) if info else self.unshard_params_by_group.get(group_idx, [])
            if local_batches and params:
                eligible = defaultdict(list)
                eager = []
                for param in params:
                    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 {})

        for group, ns_inputs in zip(self.param_groups, no_comm_inputs):
            if ns_inputs:
507
508
509
510
511
512
513
514
515
516
517
518
                    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:
            with torch.profiler.record_function("muon.pipeline.local_ns"):
                group = self.param_groups[group_idx]
                self._process_unshard_params(group, self._update_muon_momentum(group, queue.popleft()))

    def _step_assignments(self) -> Iterator[_AssignmentEntry]:
        """Yield assignments in the original round-robin optimizer group order."""
        by_group = []
531
532
533
534
535
536
537
538
539
        """Keep whole-assignment callback inputs and the serial shard path."""
        group = self.param_groups[group_idx]
        ns_inputs = self._update_muon_momentum(group, assignment.owned_params)
        if assignment.is_shard:
            self._process_shard_params(
                group, ns_inputs, [assignment], group_idx, buffer_cache={}, overlap_work=overlap_work,
            )
        elif ns_inputs:
            self._process_unshard_params(group, ns_inputs)
537
538
539
540
541
542
543
544
545
            )
        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],
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
        """Only look ahead across consecutive assignments with the same communication groups."""
        _, assignment = entry
        if not self.fsdp_overlap 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:
            shard_size = dist.get_world_size(assignment.shard_pgs[0])
            batches = self._split_into_memory_safe_batches(assignment.owned_params, shard_size, shard_size)
            for batch_idx, params in enumerate(batches):
                yield _ShardBatch(group_idx, assignment, params, batch_idx == len(batches) - 1)

    def _prepare_shard_batch(self, batch: _ShardBatch, backend: Any, stream: Any) -> _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=None, fallback_dtype=torch.bfloat16,
            )
            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],
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
            self, batches: Iterator[_ShardBatch], device: torch.device, broadcaster: AsyncReplicateBroadcaster,
            local_batches: Dict[_LocalQueueKey, _LocalBatches],
    ) -> None:
        """Overlap each batch's NS with its neighbors' collectives using two in-flight batches."""
        first = next(batches)
        second = next(batches, None)
        if second is None:
            queue = local_batches.get((first.group_idx, device))
            overlap_work = partial(self._run_local_batch, first.group_idx, queue) if queue 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)
        current = self._prepare_shard_batch(first, backend, comm_stream)
        self._run_local_batch(first.group_idx, local_batches.get((first.group_idx, device)))
        previous = None
        for following in chain((second,), 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.gathered.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.
                self._run_local_batch(local_group, local_batches.get((local_group, device)))
                self._retire_shard_batch(previous, backend, apply_stream, broadcaster)
                previous = None

            # Put the next gather ahead of this broadcast on the communication
            # stream so the next NS can run while this broadcast is in flight.
            prefetched = self._prepare_shard_batch(following, backend, comm_stream) if following else None
            with backend.stream(comm_stream), torch.profiler.record_function("muon.pipeline.broadcast"):
                comm_stream.wait_event(ns_done)
                pg = batch.assignment.shard_pgs[0]
                packed = self._pack_shard_updates(batch.params, updates, current.compute_coords, (dist.get_rank(pg),))
                works = self._launch_shard_axis_broadcasts(packed, pg, 0, ())
            previous = _BroadcastShardBatch(current, updates, packed, works)
            del packed, works
            current = prefetched

        self._run_local_batch(batch.group_idx, local_batches.get((batch.group_idx, device)))
        self._retire_shard_batch(previous, backend, apply_stream, broadcaster)

    def _retire_shard_batch(
            self,
            pending: _BroadcastShardBatch,
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
            stream: Any,
            broadcaster: AsyncReplicateBroadcaster,
    ) -> None:
        """Bound the memory window while keeping apply independent of the next NS."""
        batch = pending.gathered.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)
        stream.synchronize()
        if batch.last_in_assignment:
            broadcaster.flush_group(batch.assignment)

    def _run_post_update_fn(
            self,
            group: Dict[str, Any],
849
850
851
852
853
854
855
856
857
858
859
860
861
862

        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],
867
868
869
870
871
872
873
874
875
876
877
878
879
880
            fallback_dtype: Optional[torch.dtype] = None,
            overlap_work: Optional[Callable[[], None]] = 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:
885
886
887
888
889
890
891
892
893
            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,
893
894
895
896
897
898
899
900
901
            buffer_cache=buffer_cache,
            keep_indices=my_indices,
            while_gathering=overlap_work,
        )
        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,
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
            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)
                for param in batch:
                    my_updates[param] = updates[param].contiguous()
                del updates
        return my_updates

    def _process_shard_params(
            self,
            group: Dict[str, Any],
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
            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],
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
            param_compute_coord: Dict[torch.nn.Parameter, Tuple[int, ...]],
            local_coords: Tuple[int, ...],
    ) -> _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
        packed: _PackedShardUpdates = {}
        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

            pack_buffer = torch.empty(total_padded_numel, dtype=torch.bfloat16, device=device)
            if coord == local_coords:
                for p, offset, actual_numel, padded_numel in param_offsets:
                    pack_buffer[offset:offset + actual_numel].copy_(my_updates[p].reshape(-1))
                    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:
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
    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,
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
        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,
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
            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
217
218
219
220
221
222
223
224
225

    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)
403
404
405
406
407
408
409
410
411
        dtype, device,
    )[:total_padded_numel * shard_size]

    if while_gathering is None:
        dist.all_gather_into_tensor(gathered_buffer, pack_buffer, group=shard_pg)
    else:
        work = dist.all_gather_into_tensor(gathered_buffer, pack_buffer, group=shard_pg, async_op=True)
        try:
            while_gathering()