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,