Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / core / optimizer / swap_optimizer_base.py: 95%
1507 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"""Generic optimizer-state swap runtime, slots and adapter base."""
16# pylint: disable=protected-access
18from __future__ import annotations
20import contextlib
21import copy
22import itertools
23import logging
24import weakref
25from dataclasses import dataclass, field
26from typing import Any, Callable, Dict, Iterable, List, Optional, Protocol, Sequence, Tuple
28# Optimizer runtime is Torch-only; the legacy checker still flags core imports.
29import torch
31from hyper_parallel.tools.dryrun import simulation
33logger = logging.getLogger(__name__)
35# Logical optimizer-state keys every swap family in this codebase understands.
36# This is the vocabulary ``SwapOptimizerConfig.state_keys`` may name; each
37# adapter still validates that a key belongs to its own optimizer family.
38KNOWN_STATE_KEYS = (
39 "exp_avg",
40 "exp_avg_sq",
41 "max_exp_avg_sq",
42 "momentum_buffer",
43)
44_PACKED_ALIGNMENT_BYTES = 512
45_DEVICE_TYPE = "npu"
46_MISSING_CHECKPOINT_STATE = object()
49def _restore_dtensor_metadata(template: Any, local_tensor: Any) -> Any:
50 """Wrap a local tensor with the logical DTensor layout of ``template``."""
51 to_local = getattr(template, "to_local", None)
52 if not callable(to_local):
53 return local_tensor
55 layout = getattr(template, "layout", None)
56 if hasattr(layout, "tensor_stride"):
57 logical_stride = layout.tensor_stride
58 else:
59 logical_stride = tuple(template.stride())
60 if logical_stride is None:
61 logical_stride = [1] * len(template.shape)
62 for index in range(len(logical_stride) - 2, -1, -1):
63 logical_stride[index] = logical_stride[index + 1] * max(int(template.shape[index + 1]), 1)
65 return type(template).from_local(
66 local_tensor,
67 device_mesh=template.device_mesh,
68 placements=template.placements,
69 run_check=False,
70 shape=template.shape,
71 stride=tuple(logical_stride),
72 )
75@dataclass
76class SwapSlot:
77 """One logical optimizer state tensor that may be swapped."""
79 name: str
80 tensor: Any
81 cpu_tensor: Optional[Any] = None
82 storage_nbytes: int = 0
83 swappable: bool = True
84 state: str = "device"
85 event: Optional[Any] = None
86 shape: tuple[int, ...] = ()
87 dtype: Optional[Any] = None
88 device: Optional[Any] = None
89 numel: int = 0
90 host_offset: int = 0
91 packed: bool = False
92 logical_tensor: Optional[Any] = None
94 def bind_tensor(self, tensor: Any) -> None:
95 """Bind the slot to a host or staging tensor view."""
96 device = getattr(tensor, "device", None)
97 device_type = getattr(device, "type", None)
98 if self.logical_tensor is not None:
99 # DTensor exposes no public setter for replacing its local shard.
100 # Rebind the shell on host too, so it cannot retain an arena view.
101 setattr(self.logical_tensor, "_local_tensor", tensor)
102 self.logical_tensor.data = tensor
103 if self.logical_tensor is not None and device_type != "cpu":
104 self.tensor = self.logical_tensor
105 else:
106 self.tensor = tensor
108 @property
109 def checkpoint_tensor(self) -> Any:
110 """Return the CPU tensor when present, otherwise the live tensor."""
111 return self.cpu_tensor if self.cpu_tensor is not None else self.tensor
114class SwapUpdateUnit(Protocol):
115 """Minimal contract the pipeline runtime requires of an update unit.
117 The runtime only ever reads a unit's swappable slots, so an update unit is
118 free to carry algorithm-specific metadata (a single parameter and gradient,
119 a Muon HSDP assignment, collective ordering, and so on) as long as it
120 exposes ``slots``.
121 """
123 slots: List[SwapSlot]
126@dataclass
127class UpdateUnit:
128 """Generic per-parameter update unit: parameter, gradient and swap slots.
130 Kept as a concrete unit for optimizers whose atomic update is one parameter,
131 and as the runtime's default unit type. ``adapter_index`` identifies the
132 owning parameter group. Optimizers with a richer atomic unit (Muon HSDP
133 assignments, for example) define their own unit exposing ``slots``.
134 """
136 adapter_index: int
137 param: Any
138 grad: Any
139 slots: List[SwapSlot]
142class PipelineSwapRuntime:
143 """Torch tensor storage/copy runtime and pipeline orchestration."""
145 def __init__(self, config: Any) -> None:
146 """Initialize instance-owned streams and packed storage metadata."""
147 self.config = config
148 self._copy_stream: Optional[Any] = None
149 self._packed_enabled = bool(getattr(config, "packed_swap", True))
150 self._host_buffers: Dict[Any, Any] = {}
151 self._host_layout_signature = ()
152 self._packed_batch_plans: List[_PackedBatchPlan] = []
153 self._staging_arenas: List[Optional[_StagingArena]] = [None, None]
154 self._packed_ready_events: Dict[int, Any] = {}
155 self._packed_offload_events: Dict[int, Any] = {}
156 self._packed_tail_event: Optional[Any] = None
157 self._packed_device_views: Dict[Any, Any] = {}
158 self._packed_slot_bind_hook: Optional[Callable[[SwapSlot], None]] = None
160 @property
161 def packed_enabled(self) -> bool:
162 """Return whether this runtime may build packed state candidates."""
163 return self._packed_enabled
165 @property
166 def copy_stream(self) -> Optional[Any]:
167 """Return the transfer stream after its lazy initialization."""
168 return self._copy_stream
170 def set_packed_slot_bind_hook(self, hook: Callable[[SwapSlot], None]) -> None:
171 """Install the adapter hook that republishes a packed slot's live view."""
172 self._packed_slot_bind_hook = hook
174 def _bind_packed_slot(self, slot: SwapSlot, tensor: Any) -> None:
175 """Bind a packed view and notify the owning state adapter."""
176 slot.bind_tensor(tensor)
177 if self._packed_slot_bind_hook is not None:
178 self._packed_slot_bind_hook(slot)
180 def partition(
181 self,
182 units: Sequence[SwapUpdateUnit],
183 unit_costs: Optional[Sequence[int]] = None,
184 ) -> List[List[SwapUpdateUnit]]:
185 """Partition consecutive units using explicit costs or local state bytes.
187 Args:
188 units: Atomic updates in execution order, including empty local units.
189 unit_costs: Optional non-negative integer costs, one per unit. A
190 distributed adapter supplies rank-independent planning weights.
192 Returns:
193 Consecutive batches retaining every unit in its original order.
195 Raises:
196 ValueError: If explicit costs have the wrong length or invalid values.
197 """
198 ordered_units = list(units)
199 if unit_costs is None:
200 unit_costs = [self._unit_cost(unit) for unit in ordered_units]
201 else:
202 unit_costs = list(unit_costs)
203 if len(unit_costs) != len(ordered_units):
204 raise ValueError("unit_costs must contain exactly one cost per update unit.")
205 if any(isinstance(cost, bool) or not isinstance(cost, int) or cost < 0 for cost in unit_costs):
206 raise ValueError("unit_costs must contain non-negative integers.")
207 if not ordered_units:
208 return []
209 swap_times = max(1, min(int(self.config.swap_times), len(ordered_units)))
210 unit_costs = [max(1, cost) for cost in unit_costs]
211 remaining_cost = sum(unit_costs)
212 batches: List[List[SwapUpdateUnit]] = []
213 start = 0
214 for batch_index in range(swap_times - 1):
215 remaining_batches = swap_times - batch_index
217 # Compare against the remaining average without introducing floating-point rounding.
218 # Bind the loop state as defaults so the closure captures this iteration's values.
219 def should_stop_growing(
220 end: int,
221 current_cost: int,
222 next_cost: int,
223 remaining_batches: int = remaining_batches,
224 remaining_cost: int = remaining_cost,
225 start: int = start,
226 ) -> bool:
227 """Return whether adding the next unit would not improve balance."""
228 current_distance = abs(remaining_cost - current_cost * remaining_batches)
229 next_distance = abs(remaining_cost - (current_cost + next_cost) * remaining_batches)
230 return end > start and current_distance <= next_distance
232 max_end = len(ordered_units) - remaining_batches + 1
233 end, current_cost = self._grow_balanced_segment(unit_costs, start, max_end, should_stop_growing)
234 batches.append(ordered_units[start:end])
235 remaining_cost -= current_cost
236 start = end
237 batches.append(ordered_units[start:])
238 return batches
240 def run_pipeline(
241 self,
242 batches: Sequence[Sequence[UpdateUnit]],
243 step_context: Any,
244 step_batch: Callable[[List[UpdateUnit], Any], Any],
245 ) -> List[Any]:
246 """Run one-batch-ahead prefetch while releasing completed offloads before widening the window."""
247 results = []
248 batch_lists = [list(batch) for batch in batches]
249 if not batch_lists:
250 return results
252 if self.supports_packed_pipeline(batch_lists):
253 return self._run_packed_pipeline(batch_lists, step_context, step_batch)
255 try:
256 self.prefetch(batch_lists[0]) # prefetch 0
257 for index, batch_list in enumerate(batch_lists):
258 self.wait_prefetch(batch_list) # wait_prefetch n
260 previous_index = index - 1
261 if previous_index >= 0:
262 self.wait_offload(batch_lists[previous_index]) # wait_offload n-1
264 next_index = index + 1
265 if next_index < len(batch_lists):
266 self.prefetch(batch_lists[next_index]) # prefetch n+1
268 results.append(step_batch(batch_list, step_context)) # update n
269 self.refresh_swappable_slots(batch_list)
270 self.offload(batch_list) # offload n
272 self.wait_offload(batch_lists[-1])
273 finally:
274 self._drain_pending_transfers(batch_lists)
275 return results
277 def _drain_pending_transfers(self, batch_lists: Sequence[Sequence[UpdateUnit]]) -> None:
278 """Settle slots left in an intermediate ``h2d``/``d2h`` state.
280 Called from ``run_pipeline``'s ``finally`` so that an exception raised
281 mid-pipeline (for example in ``step_batch``) cannot leave prefetched or
282 offloaded slots holding device storage and a pending stream event. Slots
283 that already reached a terminal state (``device`` or ``host``) are left
284 untouched.
285 """
286 for batch_list in batch_lists:
287 self.wait_prefetch(batch_list)
288 self.wait_offload(batch_list)
290 def _run_packed_pipeline(
291 self,
292 batches: Sequence[List[UpdateUnit]],
293 step_context: Any,
294 step_batch: Callable[[List[UpdateUnit], Any], Any],
295 ) -> List[Any]:
296 """Run updates with two reusable staging buffers.
298 Buffer parity is fixed by batch index. D2H batch ``n`` and H2D batch
299 ``n + 2`` share one copy-stream chain while the other arena updates.
300 """
301 results = []
302 try:
303 self.begin_packed_step(batches)
304 self.enqueue_packed_prefetch(0, 0)
305 if len(batches) > 1:
306 self.enqueue_packed_prefetch(1, 1)
307 for batch_index, batch in enumerate(batches):
308 staging_index = batch_index % 2
309 self.wait_packed_prefetch(batch_index, staging_index)
310 completed_index = batch_index - 2
311 if completed_index >= 0:
312 self.wait_packed_offload(completed_index)
313 self.finish_packed_offload(completed_index)
314 self.activate_packed_batch(batch_index, staging_index)
315 results.append(step_batch(batch, step_context))
316 self.refresh_swappable_slots(batch)
317 next_index = batch_index + 2
318 self.enqueue_packed_offload_prefetch(
319 batch_index,
320 next_index if next_index < len(batches) else None,
321 staging_index,
322 )
323 drain_start = max(0, len(batches) - 2)
324 for batch_index in range(drain_start, len(batches)):
325 self.wait_packed_offload(batch_index)
326 self.finish_packed_offload(batch_index)
327 finally:
328 self.release_packed_step_results(results)
329 self.end_packed_step()
330 return results
332 def run_delayed_packed_pipeline(
333 self,
334 batches: Sequence[Sequence[UpdateUnit]],
335 step_context: Any,
336 consume_batch: Callable[[int, List[UpdateUnit], Any, Callable[[int], None]], None],
337 finish_pipeline: Callable[[Any, Callable[[int], None]], None],
338 ) -> None:
339 """Run a packed or zero-transfer pipeline whose compute may outlive one batch.
341 ``consume_batch`` feeds resident work into a family-specific pipeline and
342 invokes its completion callback as soon as a batch's optimizer state is
343 no longer needed. Completion must remain in batch order. When state is
344 transferred, it may not lag by more than the two staging arenas and a
345 completed batch is copied out before its same-parity ``n + 2`` batch is
346 copied in. A state-free rank runs the same callbacks without transfers.
348 Args:
349 batches: Logical swap batches in execution order.
350 step_context: Family-specific context for the current step.
351 consume_batch: Incrementally consume one newly resident batch and
352 report completed batch indices through the supplied callback.
353 finish_pipeline: Flush family-specific work and report the remaining
354 completed batch indices through the supplied callback.
356 Raises:
357 RuntimeError: If the completion protocol would reuse live staging
358 state, completes batches out of order, or omits a batch.
359 """
360 batch_lists = [list(batch) for batch in batches]
361 if not batch_lists:
362 return
363 has_packed_state = self.supports_packed_pipeline(batch_lists)
364 if not has_packed_state and not self._supports_delayed_packed_pipeline(batch_lists):
365 raise RuntimeError(
366 "Delayed optimizer pipeline requires packed swap state or a packed-enabled zero-transfer step."
367 )
369 submitted = set()
370 finished = set()
371 next_completion = 0
373 def submit_completion(completed_index: int) -> None:
374 nonlocal next_completion
375 if completed_index != next_completion:
376 raise RuntimeError(
377 "Delayed optimizer pipeline must complete swap batches in order: "
378 f"expected {next_completion}, got {completed_index}."
379 )
380 if completed_index >= len(batch_lists):
381 raise RuntimeError(
382 f"Delayed optimizer pipeline completed unknown batch {completed_index}."
383 )
384 self.refresh_swappable_slots(batch_lists[completed_index])
385 if has_packed_state:
386 next_index = completed_index + 2
387 self.enqueue_packed_offload_prefetch(
388 completed_index,
389 next_index if next_index < len(batch_lists) else None,
390 completed_index % 2,
391 )
392 submitted.add(completed_index)
393 next_completion += 1
395 if not has_packed_state:
396 for batch_index, batch in enumerate(batch_lists):
397 consume_batch(batch_index, batch, step_context, submit_completion)
398 finish_pipeline(step_context, submit_completion)
399 if next_completion != len(batch_lists):
400 raise RuntimeError(
401 "Delayed optimizer pipeline did not complete every swap batch: "
402 f"completed {next_completion} of {len(batch_lists)}."
403 )
404 return
406 try:
407 self.begin_packed_step(batch_lists)
408 self.enqueue_packed_prefetch(0, 0)
409 if len(batch_lists) > 1:
410 self.enqueue_packed_prefetch(1, 1)
412 for batch_index, batch in enumerate(batch_lists):
413 staging_index = batch_index % 2
414 if batch_index >= 2 and batch_index - 2 not in submitted:
415 raise RuntimeError(
416 "Delayed optimizer pipeline retained a swap batch for more "
417 "than two staging windows."
418 )
419 self.wait_packed_prefetch(batch_index, staging_index)
420 completed_index = batch_index - 2
421 if completed_index >= 0:
422 self.wait_packed_offload(completed_index)
423 self.finish_packed_offload(completed_index)
424 finished.add(completed_index)
425 self.activate_packed_batch(batch_index, staging_index)
426 consume_batch(batch_index, batch, step_context, submit_completion)
428 finish_pipeline(step_context, submit_completion)
429 if next_completion != len(batch_lists):
430 raise RuntimeError(
431 "Delayed optimizer pipeline did not complete every swap batch: "
432 f"completed {next_completion} of {len(batch_lists)}."
433 )
434 for batch_index in range(len(batch_lists)):
435 if batch_index in finished:
436 continue
437 self.wait_packed_offload(batch_index)
438 self.finish_packed_offload(batch_index)
439 finally:
440 self.end_packed_step()
442 def run_delayed_per_tensor_pipeline(
443 self,
444 batches: Sequence[Sequence[UpdateUnit]],
445 step_context: Any,
446 consume_batch: Callable[[int, List[UpdateUnit], Any, Callable[[int], None]], None],
447 finish_pipeline: Callable[[Any, Callable[[int], None]], None],
448 ) -> None:
449 """Run delayed compute while transferring optimizer state tensor by tensor.
451 Two logical swap batches are resident at most. ``consume_batch`` reports
452 completion once a batch's optimizer state is no longer read. The runtime
453 then submits that batch's D2H and, before widening the window, waits for
454 the oldest D2H to release its device storage and prefetches the following
455 batch.
457 Args:
458 batches: Logical swap batches in execution order.
459 step_context: Family-specific context for the current step.
460 consume_batch: Incrementally consume one newly resident batch and
461 report completed batch indices through the supplied callback.
462 finish_pipeline: Flush family-specific work and report the remaining
463 completed batch indices through the supplied callback.
465 Raises:
466 RuntimeError: If packed swap is enabled, completion is out of order,
467 compute retains state beyond two residency windows, or a batch is
468 not completed.
469 """
470 batch_lists = [list(batch) for batch in batches]
471 if not batch_lists:
472 return
473 if self._packed_enabled:
474 raise RuntimeError("Delayed per-tensor pipeline requires packed_swap=False.")
475 if not self.supports_delayed_pipeline(batch_lists):
476 raise RuntimeError("Delayed per-tensor pipeline does not support this swap schedule.")
478 submitted = set()
479 next_completion = 0
481 def submit_completion(completed_index: int) -> None:
482 nonlocal next_completion
483 if completed_index != next_completion:
484 raise RuntimeError(
485 "Delayed optimizer pipeline must complete swap batches in order: "
486 f"expected {next_completion}, got {completed_index}."
487 )
488 if completed_index >= len(batch_lists):
489 raise RuntimeError(
490 f"Delayed optimizer pipeline completed unknown batch {completed_index}."
491 )
492 self.refresh_swappable_slots(batch_lists[completed_index])
493 self.offload(batch_lists[completed_index])
494 submitted.add(completed_index)
495 next_completion += 1
497 try:
498 self.prefetch(batch_lists[0])
499 if len(batch_lists) > 1:
500 self.prefetch(batch_lists[1])
502 for batch_index, batch in enumerate(batch_lists):
503 self.wait_prefetch(batch)
504 consume_batch(batch_index, batch, step_context, submit_completion)
506 next_index = batch_index + 1
507 completed_index = batch_index - 1
508 if next_index >= len(batch_lists) or completed_index < 0:
509 continue
510 if completed_index not in submitted:
511 raise RuntimeError(
512 "Delayed optimizer pipeline retained a swap batch for more "
513 "than two residency windows."
514 )
515 self.wait_offload(batch_lists[completed_index])
516 self.prefetch(batch_lists[next_index])
518 finish_pipeline(step_context, submit_completion)
519 if next_completion != len(batch_lists):
520 raise RuntimeError(
521 "Delayed optimizer pipeline did not complete every swap batch: "
522 f"completed {next_completion} of {len(batch_lists)}."
523 )
524 for batch in batch_lists:
525 self.wait_offload(batch)
526 finally:
527 self._drain_delayed_per_tensor_pipeline(batch_lists)
529 def run_delayed_pipeline(
530 self,
531 batches: Sequence[Sequence[UpdateUnit]],
532 step_context: Any,
533 consume_batch: Callable[[int, List[UpdateUnit], Any, Callable[[int], None]], None],
534 finish_pipeline: Callable[[Any, Callable[[int], None]], None],
535 ) -> None:
536 """Dispatch delayed compute to the configured transfer backend."""
537 if self._packed_enabled:
538 self.run_delayed_packed_pipeline(batches, step_context, consume_batch, finish_pipeline)
539 return
540 self.run_delayed_per_tensor_pipeline(batches, step_context, consume_batch, finish_pipeline)
542 def _drain_delayed_per_tensor_pipeline(
543 self,
544 batch_lists: Sequence[Sequence[UpdateUnit]],
545 ) -> None:
546 """Return every delayed per-tensor slot to host residency after completion or failure."""
547 self._drain_pending_transfers(batch_lists)
548 for batch in batch_lists:
549 self.refresh_swappable_slots(batch)
550 self.offload(batch)
551 for batch in batch_lists:
552 self.wait_offload(batch)
554 # Both hooks below are dispatched through ``self`` from the packed pipeline
555 # above and are overridden per backend, so they stay instance
556 # methods even though the base bodies only discard their arguments.
557 def release_packed_step_results(self, results: List[Any]) -> None:
558 """Release backend-specific update outputs before staging teardown."""
559 del results
561 def refresh_swappable_slots(self, batch: Sequence[UpdateUnit]) -> None:
562 """Refresh slots that become swappable after the optimizer update."""
563 del batch
565 def synchronize_cpu_mirrors(self, slots: Iterable[SwapSlot]) -> None:
566 """Ensure CPU mirrors contain latest data for checkpointing."""
567 slot_list = [slot for slot in _iter_unique_slot_objects(slots) if slot.swappable]
568 if not slot_list:
569 return
571 compute_stream = self.current_stream()
572 with self.stream_context(compute_stream):
573 for event in _iter_unique_events(slot_list):
574 self.wait_event(event, compute_stream)
576 for slot in slot_list:
577 if slot.state == "host":
578 if slot.cpu_tensor is None:
579 raise RuntimeError(f"Swap slot {slot.name!r} is host-resident but has no CPU mirror.")
580 continue
581 if slot.state != "d2h":
582 self.copy_to_cpu(slot)
583 self.wait_offload_slot(slot)
585 checkpoint_event = self.record_event(compute_stream) if compute_stream is not None else None
587 # Storage release only needs stream ordering above. Host completion is
588 # required separately because checkpoint_state_dict reads CPU mirrors.
589 self.wait_event(checkpoint_event, None)
590 for slot in slot_list:
591 slot.event = None
592 self.restore_packed_host_views(slot_list)
594 def materialize_slots(self, slots: Iterable[SwapSlot]) -> None:
595 """Materialize host-resident slots on their original device.
597 HSDP checkpoint broadcasts operate on device tensors. Swap slots are
598 normally host-resident between optimizer steps, so checkpoint code uses
599 this helper to reuse the normal H2D stream/event ordering before issuing
600 a collective.
601 """
602 slot_list = [
603 slot for slot in _iter_unique_slot_objects(slots)
604 if slot.swappable and slot.state == "host"
605 ]
606 if not slot_list:
607 return
608 for slot in slot_list:
609 if slot.packed:
610 device_tensor = torch.empty(slot.shape, dtype=slot.dtype, device=slot.device)
611 self._bind_packed_slot(slot, device_tensor)
612 self.prefetch([UpdateUnit(0, None, None, slot_list)])
613 self.wait_prefetch([UpdateUnit(0, None, None, slot_list)])
615 def restore_packed_host_views(self, slots: Iterable[SwapSlot]) -> None:
616 """Restore persistent packed host views after temporary materialization."""
617 for slot in _iter_unique_slot_objects(slots):
618 if (slot.packed and slot.state == "host" and slot.cpu_tensor is not None
619 and slot.tensor is not slot.cpu_tensor):
620 self._bind_packed_slot(slot, slot.cpu_tensor)
622 def prefetch(self, batch: Sequence[UpdateUnit]) -> None:
623 """Prefetch batch slots from CPU to device."""
624 slots = [slot for slot in _iter_unique_slots(batch) if slot.swappable and slot.state == "host"]
625 if not slots:
626 return
628 for slot in slots:
629 if slot.cpu_tensor is None:
630 raise RuntimeError(f"Swap slot {slot.name!r} is host-resident but has no CPU mirror.")
632 restored_slots = []
633 try:
634 for slot in slots:
635 self.restore_device_storage(slot)
636 restored_slots.append(slot)
637 except Exception:
638 for restored_slot in reversed(restored_slots):
639 self.release_device_storage(restored_slot)
640 raise
642 copy_stream = self._get_copy_stream()
643 compute_event = self._record_current_stream_event() if copy_stream is not None else None
644 with self.stream_context(copy_stream):
645 self.wait_event(compute_event, copy_stream)
646 for slot in slots:
647 self.copy_to_device(slot)
648 slot.state = "h2d"
649 copy_event = self.record_event(copy_stream) if copy_stream is not None else None
650 for slot in slots:
651 slot.event = copy_event
653 def wait_prefetch(self, batch: Sequence[UpdateUnit]) -> None:
654 """Wait for batch prefetch copies."""
655 slots = [slot for slot in _iter_unique_slots(batch) if slot.swappable and slot.state == "h2d"]
656 if not slots:
657 return
659 compute_stream = self.current_stream()
660 with self.stream_context(compute_stream):
661 for event in _iter_unique_events(slots):
662 self.wait_event(event, compute_stream)
663 for slot in slots:
664 self.wait_prefetch_slot(slot)
665 slot.event = None
667 def offload(self, batch: Sequence[UpdateUnit]) -> None:
668 """Offload batch slots from device to CPU."""
669 slots = [slot for slot in _iter_unique_slots(batch) if slot.swappable and slot.state == "device"]
670 if not slots:
671 return
673 self._enqueue_offload_slots(slots)
675 def offload_initial_slots(self, slots: Iterable[SwapSlot]) -> None:
676 """Offload existing device-resident slots before the first optimizer update."""
677 slot_list = [
678 slot for slot in _iter_unique_slot_objects(slots)
679 if slot.swappable and slot.state == "device"
680 ]
681 if not slot_list:
682 return
684 self._enqueue_offload_slots(slot_list)
685 # Waiting here also releases device storage. Deferring this until the first
686 # prefetch would leave cold optimizer states resident during forward/backward.
687 self._wait_offload_slots(slot_list)
689 def _enqueue_offload_slots(self, slots: Sequence[SwapSlot]) -> None:
690 """Enqueue D2H copies for device-resident slots."""
691 copy_stream = self._get_copy_stream()
692 compute_event = self._record_current_stream_event() if copy_stream is not None else None
693 with self.stream_context(copy_stream):
694 self.wait_event(compute_event, copy_stream)
695 for slot in slots:
696 self.copy_to_cpu(slot)
697 slot.state = "d2h"
698 copy_event = self.record_event(copy_stream) if copy_stream is not None else None
699 for slot in slots:
700 slot.event = copy_event
702 def wait_offload(self, batch: Sequence[UpdateUnit]) -> None:
703 """Wait for batch offload copies."""
704 slots = [slot for slot in _iter_unique_slots(batch) if slot.swappable and slot.state == "d2h"]
705 if not slots:
706 return
708 self._wait_offload_slots(slots)
710 def _wait_offload_slots(self, slots: Sequence[SwapSlot]) -> None:
711 """Wait for D2H copies and release device storage for copied slots."""
712 compute_stream = self.current_stream()
713 with self.stream_context(compute_stream):
714 for event in _iter_unique_events(slots):
715 self.wait_event(event, compute_stream)
716 for slot in slots:
717 self.wait_offload_slot(slot)
718 slot.event = None
720 @staticmethod
721 def _unit_cost(unit: UpdateUnit) -> int:
722 return sum(slot.storage_nbytes for slot in unit.slots if slot.swappable)
724 @staticmethod
725 def _grow_balanced_segment(
726 unit_costs: Sequence[int],
727 start: int,
728 max_end: int,
729 should_stop: Callable[[int, int, int], bool],
730 ) -> Tuple[int, int]:
731 """Extend a segment from ``start`` while ``should_stop`` stays false.
733 Returns the exclusive end index and the accumulated cost of ``[start, end)``.
734 """
735 end = start
736 current_cost = 0
737 while end < max_end:
738 next_cost = unit_costs[end]
739 if should_stop(end, current_cost, next_cost):
740 break
741 current_cost += next_cost
742 end += 1
743 return end, current_cost
745 def _get_copy_stream(self) -> Any:
746 if self._copy_stream is None:
747 self._copy_stream = self.new_stream()
748 return self._copy_stream
750 def _record_current_stream_event(self) -> Any:
751 current_stream = self.current_stream()
752 return self.record_event(current_stream)
754 def populate_slot_metadata(self, slot: SwapSlot, template: Any) -> None:
755 """Populate stable logical tensor metadata without allocating device state."""
756 storage_tensor = self._storage_tensor(template)
757 slot.shape = tuple(storage_tensor.shape)
758 slot.dtype = storage_tensor.dtype
759 slot.device = storage_tensor.device
760 slot.numel = int(storage_tensor.numel())
761 slot.storage_nbytes = slot.numel * int(storage_tensor.element_size())
763 def is_packable_template(self, tensor: Any, min_numel: int) -> bool:
764 """Return whether a state shaped like ``tensor`` can use packed staging."""
765 if not self._packed_enabled:
766 return False
767 return self.is_swappable_tensor(tensor, min_numel)
769 @staticmethod
770 def is_distributed_tensor(tensor: Any) -> bool:
771 """Return whether ``tensor`` exposes a DTensor local shard."""
772 return tensor is not None and callable(getattr(tensor, "to_local", None))
774 def prepare_packed_host(self, slots: Sequence[SwapSlot]) -> None:
775 """Pack logical optimizer states into persistent pinned buffers by dtype."""
776 if not self._packed_enabled:
777 return
779 packed_slots = [slot for slot in slots if slot.swappable and slot.packed]
780 signature = self._validate_packed_host_layout(packed_slots)
781 if signature == self._host_layout_signature:
782 return
784 self._prepare_packed_host_sources(packed_slots)
785 slots_by_dtype: Dict[Any, List[SwapSlot]] = {}
786 for slot in packed_slots:
787 slots_by_dtype.setdefault(slot.dtype, []).append(slot)
789 self._host_buffers = {
790 dtype: self._pack_dtype_slots(dtype, dtype_slots)
791 for dtype, dtype_slots in slots_by_dtype.items()
792 }
793 self._host_layout_signature = signature
795 def _validate_packed_host_layout(
796 self, packed_slots: Sequence[SwapSlot],
797 ) -> Tuple[Tuple[Any, ...], ...]:
798 """Validate candidates and return their persistent layout signature."""
799 if self._packed_batch_plans or self._packed_tail_event is not None:
800 raise RuntimeError("Cannot rebuild packed optimizer layout during an active transfer.")
801 slot_ids = [id(slot) for slot in packed_slots]
802 if len(slot_ids) != len(set(slot_ids)):
803 raise RuntimeError("Packed optimizer layout contains a duplicate state slot.")
804 return tuple(
805 (id(slot), slot.dtype, slot.shape, slot.numel, slot.device)
806 for slot in packed_slots
807 )
809 def _prepare_packed_host_sources(self, packed_slots: Sequence[SwapSlot]) -> None:
810 """Validate source layouts and settle copies before rebuilding host buffers."""
811 for slot in packed_slots:
812 source = slot.checkpoint_tensor
813 if source is not None:
814 local = self._storage_tensor(source)
815 if local.layout != torch.strided or not local.is_contiguous():
816 raise ValueError("Packed optimizer states must be dense and contiguous before host packing.")
817 # A layout rebuild reads CPU mirrors on the host. Stream ordering alone
818 # is insufficient, including after an initial-state offload.
819 if self._copy_stream is not None:
820 self._copy_stream.synchronize()
821 for event in _iter_unique_events(packed_slots):
822 self.wait_event(event, None)
823 if any(slot.state in ("h2d", "d2h") for slot in packed_slots):
824 self.synchronize_cpu_mirrors(packed_slots)
826 def invalidate_packed_layout(self) -> None:
827 """Discard an idle packed layout after state slots have been rebound.
829 Persistent slot mirrors retain their values until the next host packing.
830 The instance's copy stream remains available for subsequent steps.
831 """
832 if self._packed_batch_plans or self._packed_tail_event is not None:
833 raise RuntimeError("Cannot reset optimizer parameters during a packed transfer.")
834 for arena in self._staging_arenas:
835 if arena is not None:
836 arena.dtype_views.clear()
837 arena.raw_buffer.untyped_storage().resize_(0)
838 self._staging_arenas = [None, None]
839 self._packed_device_views.clear()
840 self._packed_ready_events.clear()
841 self._packed_offload_events.clear()
842 self._host_buffers = {}
843 self._host_layout_signature = ()
845 def _pack_dtype_slots(self, dtype: Any, dtype_slots: Sequence[SwapSlot]) -> Any:
846 """Pack every slot of one dtype into a single pinned host buffer.
848 Each slot is re-pointed at its own view inside the new buffer and marked
849 host-resident, so the packed buffer becomes the slot's CPU mirror from
850 here on. Any device copy that fed the mirror is released immediately
851 afterwards, because the host view now owns the only valid values.
852 """
853 total_numel = sum(slot.numel for slot in dtype_slots)
854 host_buffer = torch.empty(total_numel, dtype=dtype, device="cpu", pin_memory=True)
855 host_offset = 0
856 for slot in dtype_slots:
857 flat_view = host_buffer.narrow(0, host_offset, slot.numel)
858 host_view = flat_view.view(slot.shape)
859 source = slot.tensor if slot.state == "device" else slot.checkpoint_tensor
860 if source is None:
861 host_view.zero_()
862 else:
863 source_tensor = self._storage_tensor(source)
864 host_view.copy_(source_tensor.detach().reshape(-1).view(slot.shape), non_blocking=False)
865 if source_tensor.device.type != "cpu" and source is slot.tensor:
866 self.release_device_storage(slot)
867 slot.host_offset = host_offset
868 slot.cpu_tensor = host_view
869 slot.bind_tensor(host_view)
870 slot.state = "host"
871 slot.event = None
872 host_offset += slot.numel
873 return host_buffer
875 def is_swappable_tensor(self, tensor: Any, min_numel: int) -> bool:
876 """Return whether ``tensor`` can participate in swap."""
877 storage_tensor = self._storage_tensor(tensor)
878 if not isinstance(storage_tensor, torch.Tensor):
879 return False
880 if not storage_tensor.is_floating_point():
881 return False
882 if int(storage_tensor.numel()) < int(min_numel):
883 return False
884 if storage_tensor.is_sparse:
885 return False
886 if not storage_tensor.is_contiguous():
887 return False
888 if storage_tensor.device.type == "cpu":
889 return False
890 try:
891 storage_size = int(storage_tensor.untyped_storage().size())
892 expected_size = int(storage_tensor.numel()) * int(storage_tensor.element_size())
893 if storage_size != expected_size:
894 return False
895 except RuntimeError:
896 return False
897 return True
899 def storage_nbytes(self, tensor: Any) -> int:
900 """Return storage bytes for a Torch tensor."""
901 storage_tensor = self._storage_tensor(tensor)
902 if not isinstance(storage_tensor, torch.Tensor):
903 return 0
904 try:
905 return int(storage_tensor.untyped_storage().size())
906 except RuntimeError:
907 return int(storage_tensor.numel()) * int(storage_tensor.element_size())
909 def make_cpu_tensor(self, tensor: Any) -> Any:
910 """Create a CPU mirror tensor."""
911 storage_tensor = self._storage_tensor(tensor)
912 if isinstance(storage_tensor, torch.Tensor):
913 source = storage_tensor.detach()
914 try:
915 cpu_tensor = torch.empty_like(source, device="cpu", pin_memory=True)
916 except RuntimeError:
917 cpu_tensor = torch.empty_like(source, device="cpu")
918 cpu_tensor.copy_(source, non_blocking=True)
919 return cpu_tensor
920 raise ValueError(f"Expected torch.Tensor for CPU mirror, got {type(tensor)!r}.")
922 def make_zero_cpu_tensor_like(self, tensor: Any) -> Any:
923 """Create a zero-valued CPU mirror without materializing device state."""
924 storage_tensor = self._storage_tensor(tensor)
925 if not isinstance(storage_tensor, torch.Tensor):
926 raise ValueError(f"Expected torch.Tensor for CPU mirror, got {type(tensor)!r}.")
927 try:
928 cpu_tensor = torch.empty_like(storage_tensor, device="cpu", pin_memory=True)
929 except RuntimeError:
930 cpu_tensor = torch.empty_like(storage_tensor, device="cpu")
931 cpu_tensor.zero_()
932 return cpu_tensor
934 @staticmethod
935 def make_device_tensor_like(param: Any, saved_tensor: Any) -> Any:
936 """Create a live state tensor on the parameter device."""
937 if not isinstance(saved_tensor, torch.Tensor):
938 raise ValueError(f"Expected torch.Tensor in optimizer state, got {type(saved_tensor)!r}.")
939 return saved_tensor.detach().to(device=param.device, dtype=saved_tensor.dtype).clone()
941 def make_empty_device_tensor_like(self, param: Any, saved_tensor: Any) -> Any:
942 """Create an uninitialized live state tensor shell on the parameter device."""
943 if not isinstance(saved_tensor, torch.Tensor):
944 raise ValueError(f"Expected torch.Tensor in optimizer state, got {type(saved_tensor)!r}.")
945 if self.is_distributed_tensor(param):
946 return self.make_empty_state_like(param)
947 return torch.empty_like(saved_tensor, device=param.device, dtype=saved_tensor.dtype)
949 def make_empty_state_like(self, param: Any) -> Any:
950 """Allocate a state shell with the parameter's local and logical metadata."""
951 local = torch.empty_like(self._storage_tensor(param), memory_format=torch.preserve_format)
952 # Explicit from_local preserves layout even inside SkipDTensorDispatch,
953 # where empty_like(param) would otherwise return a plain local tensor.
954 return _restore_dtensor_metadata(param, local)
956 def copy_to_device(self, slot: SwapSlot) -> None:
957 """Copy one CPU mirror to device tensor."""
958 if slot.state != "host":
959 return
960 if slot.cpu_tensor is None:
961 return
962 self._storage_tensor(slot.tensor).copy_(slot.cpu_tensor, non_blocking=True)
963 slot.state = "h2d"
965 def wait_prefetch_slot(self, slot: SwapSlot) -> None:
966 """Torch fallback copies are synchronous on CPU and stream-ordered on device."""
967 slot.state = "device"
969 def copy_to_cpu(self, slot: SwapSlot) -> None:
970 """Copy one device tensor to CPU mirror."""
971 source = self._storage_tensor(slot.tensor)
972 if slot.cpu_tensor is None:
973 slot.cpu_tensor = self.make_cpu_tensor(source)
974 else:
975 slot.cpu_tensor.copy_(source.detach(), non_blocking=True)
976 slot.state = "d2h"
978 def wait_offload_slot(self, slot: SwapSlot) -> None:
979 """Release device storage after D2H copy completes."""
980 if self._storage_tensor(slot.tensor).device.type != "cpu":
981 self.release_device_storage(slot)
982 slot.state = "host"
984 def restore_device_storage(self, slot: SwapSlot) -> None:
985 """Restore device tensor storage before H2D."""
986 storage_tensor = self._storage_tensor(slot.tensor)
987 if storage_tensor.device.type == "cpu":
988 return
989 storage = storage_tensor.untyped_storage()
990 if storage.size() != slot.storage_nbytes:
991 storage.resize_(slot.storage_nbytes)
993 def release_device_storage(self, slot: SwapSlot) -> None:
994 """Release device storage for a swappable tensor."""
995 storage_tensor = self._storage_tensor(slot.tensor)
996 if storage_tensor.device.type == "cpu":
997 return
998 storage = storage_tensor.untyped_storage()
999 if storage.size() != 0:
1000 storage.resize_(0)
1002 @staticmethod
1003 def device_handle() -> Any:
1004 """Return the device module (``npu`` module) that owns streams and events."""
1005 if simulation.is_device_runtime_simulated():
1006 # Logical simulation: streams and events complete in program
1007 # order, keeping the swap pipeline's host-visible storage
1008 # lifecycle without touching an accelerator runtime.
1009 return simulation.simulated_device_handle()
1010 try:
1011 return getattr(torch, _DEVICE_TYPE)
1012 except AttributeError as error:
1013 raise RuntimeError(
1014 f"Swap optimizer expects device handle: 'torch.{_DEVICE_TYPE}' failed."
1015 ) from error
1017 def current_stream(self) -> Any:
1018 """Return the current compute stream."""
1019 return self.device_handle().current_stream()
1021 def new_stream(self) -> Any:
1022 """Create the copy stream."""
1023 return self.device_handle().Stream()
1025 def stream_context(self, stream: Any) -> Any:
1026 """Return a stream context for ``stream``."""
1027 if stream is None:
1028 return contextlib.nullcontext()
1029 return self.device_handle().stream(stream)
1031 def record_event(self, stream: Any = None) -> Any:
1032 """Record an event on ``stream``."""
1033 event = self.device_handle().Event()
1034 if stream is None:
1035 event.record()
1036 else:
1037 event.record(stream)
1038 return event
1040 @staticmethod
1041 def wait_event(event: Any, stream: Any = None) -> None:
1042 """Make ``stream`` wait for ``event``."""
1043 if event is None:
1044 return
1045 if stream is None:
1046 event.synchronize()
1047 return
1048 event.wait(stream)
1050 def supports_packed_pipeline(self, batches: Sequence[Sequence[UpdateUnit]]) -> bool:
1051 """Make the final, step-specific decision to use the packed pipeline."""
1052 if not self._packed_enabled or not batches:
1053 return False
1054 swappable_slots = self._swappable_pipeline_slots(batches)
1055 if not swappable_slots:
1056 return False
1057 return self._supports_packed_slots(swappable_slots)
1059 def supports_delayed_pipeline(self, batches: Sequence[Sequence[UpdateUnit]]) -> bool:
1060 """Return whether delayed compute can use the configured transfer backend.
1062 A rank without swappable state still has to enter the optimizer family's
1063 logical pipeline so its collective order matches peers that transfer
1064 state. Such a rank needs no device transfer storage.
1065 """
1066 if not batches:
1067 return False
1068 swappable_slots = self._swappable_pipeline_slots(batches)
1069 slot_ids = [id(slot) for slot in swappable_slots]
1070 if len(slot_ids) != len(set(slot_ids)):
1071 raise RuntimeError("Delayed optimizer batches contain a duplicate state slot.")
1072 if not self._packed_enabled:
1073 return True
1074 return not swappable_slots or self._supports_packed_slots(swappable_slots)
1076 def _supports_delayed_packed_pipeline(self, batches: Sequence[Sequence[UpdateUnit]]) -> bool:
1077 """Return whether packed delayed compute can run, including without local transfers."""
1078 if not self._packed_enabled or not batches:
1079 return False
1080 swappable_slots = self._swappable_pipeline_slots(batches)
1081 return not swappable_slots or self._supports_packed_slots(swappable_slots)
1083 @staticmethod
1084 def _swappable_pipeline_slots(batches: Sequence[Sequence[UpdateUnit]]) -> List[SwapSlot]:
1085 """Collect swappable slots from logical batches in execution order."""
1086 units = itertools.chain.from_iterable(batches)
1087 slots = itertools.chain.from_iterable(unit.slots for unit in units)
1088 return [slot for slot in slots if slot.swappable]
1090 def _supports_packed_slots(self, swappable_slots: Sequence[SwapSlot]) -> bool:
1091 """Validate that every swappable slot can use one packed device layout."""
1092 if len({id(slot) for slot in swappable_slots}) != len(swappable_slots):
1093 raise RuntimeError("Packed optimizer batches contain a duplicate state slot.")
1094 devices = {slot.device for slot in swappable_slots}
1095 eligible = len(devices) == 1 and None not in devices and all(
1096 slot.packed
1097 and slot.cpu_tensor is not None
1098 and slot.dtype in self._host_buffers
1099 for slot in swappable_slots
1100 )
1101 # A packed slot always carries a host mirror and a host-buffer dtype once
1102 # ``prepare_packed_host`` has run, so the only remaining way for
1103 # ``eligible`` to be false is a device mismatch. Per-tensor swap cannot
1104 # recover from that -- the slot tensor is already a CPU host view -- so
1105 # every packed slot must fail loudly rather than fall through silently.
1106 if not eligible and any(slot.packed for slot in swappable_slots):
1107 raise RuntimeError(
1108 "Packed optimizer states cannot fall back to per-tensor swap after "
1109 f"host packing; packed pipeline eligibility failed for local devices {sorted(map(str, devices))}."
1110 )
1111 return eligible
1113 @staticmethod
1114 def _storage_tensor(tensor: Any) -> Any:
1115 """Return the local tensor whose storage is managed by this runtime."""
1116 to_local = getattr(tensor, "to_local", None)
1117 return to_local() if callable(to_local) else tensor
1119 @staticmethod
1120 def _first_swappable_slot(batches: Sequence[Sequence[UpdateUnit]]) -> SwapSlot:
1121 """Return the first swappable slot across ``batches``, in iteration order."""
1122 units = itertools.chain.from_iterable(batches)
1123 slots = itertools.chain.from_iterable(unit.slots for unit in units)
1124 swappable = (slot for slot in slots if slot.swappable)
1125 return next(swappable)
1127 def begin_packed_step(self, batches: Sequence[Sequence[UpdateUnit]]) -> None:
1128 """Build batch transfer plans and materialize two raw staging buffers.
1130 Args:
1131 batches: Update units grouped into packed pipeline batches.
1132 """
1133 first_slot = self._first_swappable_slot(batches)
1134 # FSDP may leave gradient reductions/reshards queued on auxiliary
1135 # streams. A current-stream event cannot cover those streams, so the
1136 # device-wide synchronization is required before optimizer reads state.
1137 if not simulation.is_device_runtime_simulated():
1138 getattr(torch, first_slot.device.type).synchronize(first_slot.device)
1139 self._packed_tail_event = None
1140 self._packed_batch_plans = [self._build_packed_batch_plan(batch) for batch in batches]
1141 dtype_layouts, total_bytes, device = self._packed_layout(self._packed_batch_plans)
1143 for staging_index in range(2):
1144 arena = self._materialize_staging_arena(staging_index, total_bytes, device)
1145 layout_signature = tuple(
1146 (dtype, offset, num_bytes) for dtype, (offset, num_bytes) in dtype_layouts.items()
1147 )
1148 if arena.layout_signature != layout_signature:
1149 arena.dtype_views = {
1150 dtype: arena.raw_buffer.narrow(0, offset, num_bytes).view(dtype)
1151 for dtype, (offset, num_bytes) in dtype_layouts.items()
1152 }
1153 arena.layout_signature = layout_signature
1154 self._drop_packed_views(staging_index)
1155 self._packed_ready_events = {}
1156 self._packed_offload_events = {}
1158 def enqueue_packed_prefetch(self, batch_index: int, staging_index: int) -> None:
1159 """Enqueue one packed H2D and record its ready event."""
1160 copy_stream = self._get_copy_stream()
1161 with self.stream_context(copy_stream):
1162 self._copy_packed_to_device(batch_index, staging_index)
1163 ready_event = self.record_event(copy_stream)
1164 self._packed_ready_events[batch_index] = ready_event
1165 self._packed_tail_event = ready_event
1167 def wait_packed_prefetch(self, batch_index: int, staging_index: int) -> None:
1168 """Order the compute stream after the batch's packed transfer chain."""
1169 del staging_index
1170 ready_event = self._packed_ready_events.get(batch_index)
1171 if ready_event is None:
1172 raise RuntimeError(f"Packed optimizer batch {batch_index} has no ready event.")
1173 self.wait_event(ready_event, self.current_stream())
1175 def activate_packed_batch(self, batch_index: int, staging_index: int) -> None:
1176 """Bind each swap slot to its slice of one staging arena."""
1177 batch_plan = self._packed_batch_plans[batch_index]
1178 arena = self._require_staging_arena(staging_index)
1179 for dtype, region in batch_plan.regions.items():
1180 dtype_view = arena.dtype_views[dtype]
1181 for slot in region.slots:
1182 relative_offset = slot.host_offset - region.host_offset
1183 cache_key = (
1184 staging_index,
1185 id(arena.raw_buffer),
1186 id(dtype_view),
1187 id(slot),
1188 dtype,
1189 relative_offset,
1190 slot.numel,
1191 slot.shape,
1192 )
1193 device_view = self._packed_device_views.get(cache_key)
1194 if device_view is None:
1195 device_view = dtype_view.narrow(0, relative_offset, slot.numel).view(slot.shape)
1196 self._packed_device_views[cache_key] = device_view
1197 self._bind_packed_slot(slot, device_view)
1198 slot.state = "device"
1199 slot.event = None
1201 def enqueue_packed_offload_prefetch(
1202 self,
1203 batch_index: int,
1204 next_index: Optional[int],
1205 staging_index: int,
1206 ) -> None:
1207 """Serialize current D2H and next same-parity H2D on the copy stream."""
1208 copy_stream = self._get_copy_stream()
1209 compute_event = self._record_current_stream_event()
1210 with self.stream_context(copy_stream):
1211 self.wait_event(compute_event, copy_stream)
1212 self._copy_packed_to_host(batch_index, staging_index)
1213 # This arena may be overwritten by the following H2D. Exception
1214 # cleanup must use the host result once its D2H has been submitted.
1215 for region in self._packed_batch_plans[batch_index].regions.values():
1216 for slot in region.slots:
1217 slot.state = "d2h"
1218 if next_index is not None:
1219 self._copy_packed_to_device(next_index, staging_index)
1220 chain_event = self.record_event(copy_stream)
1221 self._packed_offload_events[batch_index] = chain_event
1222 self._packed_tail_event = chain_event
1223 if next_index is not None:
1224 self._packed_ready_events[next_index] = chain_event
1226 def wait_packed_offload(self, batch_index: int) -> None:
1227 """Order the compute stream after a packed transfer chain."""
1228 offload_event = self._packed_offload_events.get(batch_index)
1229 if offload_event is None:
1230 raise RuntimeError(f"Packed optimizer batch {batch_index} has no offload event.")
1231 self.wait_event(offload_event, self.current_stream())
1233 def finish_packed_offload(self, batch_index: int) -> None:
1234 """Make persistent pinned views authoritative after D2H completion."""
1235 batch_plan = self._packed_batch_plans[batch_index]
1236 for region in batch_plan.regions.values():
1237 for slot in region.slots:
1238 self._bind_packed_slot(slot, slot.cpu_tensor)
1239 slot.state = "host"
1240 slot.event = None
1242 def end_packed_step(self) -> None:
1243 """Drain the packed copy chain and release step-local staging storage."""
1244 if self._copy_stream is not None:
1245 # A submission can fail after enqueueing a copy but before recording
1246 # its tail event, even when no batch has activated a device view yet.
1247 self._copy_stream.synchronize()
1248 elif self._packed_tail_event is not None:
1249 self.wait_event(self._packed_tail_event, None)
1250 active_slots: Dict[int, Any] = {}
1251 for batch_plan in self._packed_batch_plans:
1252 for region in batch_plan.regions.values():
1253 for slot in region.slots:
1254 if slot.state in ("device", "d2h"):
1255 active_slots[id(slot)] = slot
1256 if active_slots:
1257 compute_stream = self.current_stream()
1258 synchronize = getattr(compute_stream, "synchronize", None)
1259 if synchronize is not None:
1260 synchronize()
1261 for slot in active_slots.values():
1262 if slot.state == "device":
1263 slot.cpu_tensor.copy_(self._storage_tensor(slot.tensor).detach(), non_blocking=False)
1264 self._bind_packed_slot(slot, slot.cpu_tensor)
1265 slot.state = "host"
1266 slot.event = None
1267 for arena in self._staging_arenas:
1268 if arena is None:
1269 continue
1270 # Drop views before shrinking the raw storage; otherwise a view
1271 # can keep the device allocation alive after the step ends.
1272 arena.dtype_views = {}
1273 arena.layout_signature = None
1274 storage = arena.raw_buffer.untyped_storage()
1275 if storage.size() != 0:
1276 storage.resize_(0)
1277 self._packed_device_views = {}
1278 self._packed_batch_plans = []
1279 self._packed_ready_events = {}
1280 self._packed_offload_events = {}
1281 self._packed_tail_event = None
1283 @staticmethod
1284 def _build_packed_batch_plan(batch: Sequence[UpdateUnit]) -> _PackedBatchPlan:
1285 """Group a batch's packed slots into contiguous host regions by dtype."""
1286 slots_by_dtype: Dict[Any, List[SwapSlot]] = {}
1287 seen_slots = set()
1288 for unit in batch:
1289 for slot in unit.slots:
1290 if not slot.swappable or not slot.packed:
1291 continue
1292 if id(slot) in seen_slots:
1293 raise RuntimeError("Packed optimizer batch contains a duplicate state slot.")
1294 slots_by_dtype.setdefault(slot.dtype, []).append(slot)
1295 seen_slots.add(id(slot))
1297 regions = {}
1298 for dtype, slots in slots_by_dtype.items():
1299 host_offset = slots[0].host_offset
1300 expected_offset = host_offset
1301 for slot in slots:
1302 if slot.host_offset != expected_offset:
1303 raise RuntimeError(
1304 f"Packed optimizer batch has a non-contiguous {dtype} host range at slot {slot.name!r}."
1305 )
1306 expected_offset += slot.numel
1307 regions[dtype] = _PackedBatchRegion(dtype, host_offset, expected_offset - host_offset, slots)
1308 return _PackedBatchPlan(regions)
1310 def _materialize_staging_arena(self, staging_index: int, total_bytes: int, device: Any) -> _StagingArena:
1311 """Allocate or resize one packed device staging arena for the requested layout."""
1312 arena = self._staging_arenas[staging_index]
1313 if arena is None or arena.raw_buffer.device != device:
1314 raw_buffer = torch.empty(total_bytes, dtype=torch.uint8, device=device)
1315 arena = _StagingArena(raw_buffer)
1316 self._staging_arenas[staging_index] = arena
1317 self._drop_packed_views(staging_index)
1318 return arena
1320 raw_buffer = arena.raw_buffer
1321 storage = raw_buffer.untyped_storage()
1322 if storage.size() < total_bytes:
1323 storage.resize_(total_bytes)
1324 arena.dtype_views = {}
1325 arena.layout_signature = None
1326 self._drop_packed_views(staging_index)
1327 raw_buffer.set_(storage, 0, (total_bytes,), (1,))
1328 return arena
1330 def _drop_packed_views(self, staging_index: int) -> None:
1331 """Drop cached views for one arena after its storage/layout changes."""
1332 self._packed_device_views = {
1333 key: value for key, value in self._packed_device_views.items() if key[0] != staging_index
1334 }
1336 def _copy_packed_to_device(self, batch_index: int, staging_index: int) -> None:
1337 batch_plan = self._packed_batch_plans[batch_index]
1338 arena = self._require_staging_arena(staging_index)
1339 for dtype, region in batch_plan.regions.items():
1340 host_view = self._host_buffers[dtype].narrow(0, region.host_offset, region.numel)
1341 arena.dtype_views[dtype].narrow(0, 0, region.numel).copy_(host_view, non_blocking=True)
1343 def _copy_packed_to_host(self, batch_index: int, staging_index: int) -> None:
1344 batch_plan = self._packed_batch_plans[batch_index]
1345 arena = self._require_staging_arena(staging_index)
1346 for dtype, region in batch_plan.regions.items():
1347 host_view = self._host_buffers[dtype].narrow(0, region.host_offset, region.numel)
1348 host_view.copy_(arena.dtype_views[dtype].narrow(0, 0, region.numel), non_blocking=True)
1350 def _require_staging_arena(self, staging_index: int) -> _StagingArena:
1351 arena = self._staging_arenas[staging_index]
1352 if arena is None:
1353 raise RuntimeError(f"Packed optimizer staging arena {staging_index} is not materialized.")
1354 return arena
1356 @staticmethod
1357 def _align_bytes(num_bytes: int) -> int:
1358 return ((num_bytes + _PACKED_ALIGNMENT_BYTES - 1) // _PACKED_ALIGNMENT_BYTES) * _PACKED_ALIGNMENT_BYTES
1360 def _packed_layout(self, batch_plans: Sequence[_PackedBatchPlan]) -> Tuple[Dict[Any, Tuple[int, int]], int, Any]:
1361 """Return the dtype -> (offset, bytes) staging layout shared by every batch."""
1362 max_numel_by_dtype: Dict[Any, int] = {}
1363 device = None
1364 for batch_plan in batch_plans:
1365 for dtype, region in batch_plan.regions.items():
1366 max_numel_by_dtype[dtype] = max(max_numel_by_dtype.get(dtype, 0), region.numel)
1367 if device is None and region.slots:
1368 device = region.slots[0].device
1369 if device is None:
1370 raise RuntimeError("Packed optimizer pipeline has no device-resident state metadata.")
1372 dtype_layouts = {}
1373 byte_offset = 0
1374 for dtype in sorted(max_numel_by_dtype, key=str):
1375 byte_offset = self._align_bytes(byte_offset)
1376 element_size = int(self._host_buffers[dtype].element_size())
1377 num_bytes = max_numel_by_dtype[dtype] * element_size
1378 dtype_layouts[dtype] = (byte_offset, num_bytes)
1379 byte_offset += num_bytes
1380 return dtype_layouts, self._align_bytes(byte_offset), device
1383@dataclass
1384class _PackedBatchRegion:
1385 """One dtype-contiguous host range transferred for a pipeline batch."""
1387 dtype: Any
1388 host_offset: int
1389 numel: int
1390 slots: List[SwapSlot]
1393@dataclass
1394class _PackedBatchPlan:
1395 """Packed transfer regions for one optimizer pipeline batch."""
1397 regions: Dict[Any, _PackedBatchRegion] = field(default_factory=dict)
1400@dataclass
1401class _StagingArena:
1402 """One raw device allocation and its dtype-specific views."""
1404 raw_buffer: Any
1405 dtype_views: Dict[Any, Any] = field(default_factory=dict)
1406 layout_signature: Any = None
1409def _iter_unique_slots(units: Sequence[UpdateUnit]) -> Iterable[SwapSlot]:
1410 """Yield slots once by object identity."""
1411 slots = itertools.chain.from_iterable(unit.slots for unit in units)
1412 return _iter_unique_slot_objects(slots)
1415def _iter_unique_slot_objects(slots: Iterable[SwapSlot]) -> Iterable[SwapSlot]:
1416 """Yield slots once by tensor object identity."""
1417 unique_slots: Dict[int, SwapSlot] = {}
1418 for slot in slots:
1419 unique_slots.setdefault(id(slot.tensor), slot)
1420 return unique_slots.values()
1423def _iter_unique_events(slots: Iterable[SwapSlot]) -> Iterable[Any]:
1424 """Yield non-empty events once by object identity."""
1425 seen = set()
1426 for slot in slots:
1427 event = slot.event
1428 if event is None:
1429 continue
1430 key = id(event)
1431 if key in seen:
1432 continue
1433 seen.add(key)
1434 yield event
1437def _slot_tensor(unit: SwapUpdateUnit, key: str, fallback: Any) -> Any:
1438 """Return an active swap slot tensor for ``key``, or ``fallback``.
1440 A slot is authoritative only while it is swappable, still resident on the
1441 local device and bound to a live tensor; otherwise the optimizer state entry
1442 is the source of truth for this step.
1443 """
1444 for slot in unit.slots:
1445 if slot.name == key and slot.swappable and slot.state == "device" and slot.tensor is not None:
1446 return slot.tensor
1447 return fallback
1450def validate_state_keys(state_keys: Optional[Sequence[str]]) -> Optional[tuple[str, ...]]:
1451 """Validate user-provided optimizer state keys.
1453 Only lexical validity is checked here: a key must appear in
1454 :data:`KNOWN_STATE_KEYS`. Whether the wrapped optimizer family actually
1455 owns that state is decided later by the family adapter, which fails during
1456 ``validate()``/wrap time.
1457 """
1458 if state_keys is None:
1459 return None
1460 normalized = tuple(state_keys)
1461 invalid = sorted(set(normalized) - set(KNOWN_STATE_KEYS))
1462 if invalid:
1463 raise ValueError(
1464 "SwapOptimizerConfig.state_keys only supports optimizer state slots "
1465 f"{KNOWN_STATE_KEYS}, but got {invalid}."
1466 )
1467 return normalized
1470#: Builds the family adapter for a wrapped optimizer.
1471AdapterFactory = Callable[[Any, Any, PipelineSwapRuntime], "StateSwapAdapter"]
1474def _build_profiled_step(wrapper: Any) -> Callable[..., Any]:
1475 """Build a PyTorch step-hook dispatcher without retaining ``wrapper`` strongly."""
1476 wrapper_ref = weakref.ref(wrapper)
1478 def hooked_leaf_step(optimizer: Any, *args: Any, **kwargs: Any) -> Any:
1479 """Dispatch one raw optimizer leaf through its swap wrapper."""
1480 current = wrapper_ref()
1481 if current is None:
1482 raise RuntimeError("Swap optimizer wrapper has been released.")
1483 if optimizer is not current.optimizer:
1484 raise ValueError("Optimizer step hooks cannot replace optimizer identity.")
1485 return current._step_impl(*args, **kwargs)
1487 return torch.optim.Optimizer.profile_hook_step(hooked_leaf_step)
1490class StateSwapAdapter:
1491 """Algorithm-independent optimizer-state swap adapter base.
1493 Owns the slot map, the configured/default state-key selection framework, the
1494 checkpoint strip/export/restore path and packed-state publication. The
1495 numerical update and the per-parameter unit construction belong to the
1496 optimizer family subclasses, which implement :meth:`default_state_keys`,
1497 :meth:`prepare_step`, :meth:`iter_update_units` and :meth:`step_batch`.
1498 """
1500 @staticmethod
1501 def default_state_keys() -> Tuple[str, ...]:
1502 """Return the family's default swap state keys.
1504 Subclasses must override this; the base class deliberately assumes
1505 nothing about an optimizer's state layout, so there is no default.
1507 Raises:
1508 NotImplementedError: Always, unless a subclass overrides it.
1509 """
1510 raise NotImplementedError
1512 def __init__(self, optimizer: Any, config: Any, runtime: Any) -> None:
1513 """Bind a leaf optimizer to its state slots and transfer runtime."""
1514 self.optimizer = optimizer
1515 self.config = config
1516 self.runtime = runtime
1517 self._slots: Dict[Tuple[int, str], SwapSlot] = {}
1518 self._packed_state_bindings: Dict[int, Tuple[Any, str]] = {}
1519 self._checkpoint_active = False
1520 self._checkpoint_broadcasted = False
1521 self._checkpoint_state_bindings: List[Tuple[Any, str, Any]] = []
1522 self.runtime.set_packed_slot_bind_hook(self.on_packed_slot_bound)
1524 def iter_update_units(self, step_context: Dict[str, Any]) -> List[UpdateUnit]:
1525 """Return units collected in ``prepare_step``."""
1526 return step_context["units"]
1528 def partition_costs(
1529 self,
1530 units: Sequence[SwapUpdateUnit],
1531 step_context: Any,
1532 ) -> Optional[Sequence[int]]:
1533 """Return optional planning costs; default to the runtime's local bytes."""
1534 del units, step_context
1536 def partition_update_units(
1537 self,
1538 units: Sequence[SwapUpdateUnit],
1539 step_context: Any,
1540 ) -> List[List[SwapUpdateUnit]]:
1541 """Partition update units while preserving family-specific atomic work.
1543 Args:
1544 units: Ordered algorithm update units.
1545 step_context: Family-specific context for the current step.
1547 Returns:
1548 Consecutive swap batches in execution order.
1549 """
1550 return self.runtime.partition(
1551 units,
1552 unit_costs=self.partition_costs(units, step_context),
1553 )
1555 def prepare_pipeline(
1556 self,
1557 batches: Sequence[Sequence[SwapUpdateUnit]],
1558 step_context: Any,
1559 ) -> None:
1560 """Pack local slots in execution order after logical partitioning."""
1561 del step_context
1562 if not self.runtime.packed_enabled:
1563 return
1564 self._refresh_packed_state_bindings()
1565 active_slots = [slot for batch in batches for unit in batch for slot in unit.slots]
1566 active_ids = {id(slot) for slot in active_slots}
1567 # Inactive state stays on host at the layout tail. It must not leave
1568 # holes inside active dtype regions or keep old packed buffers alive.
1569 inactive_slots = [slot for slot in self._ordered_slots() if id(slot) not in active_ids]
1570 self.runtime.prepare_packed_host(active_slots + inactive_slots)
1571 self.publish_packed_state()
1573 def run_pipeline(
1574 self,
1575 batches: Sequence[Sequence[SwapUpdateUnit]],
1576 step_context: Any,
1577 ) -> None:
1578 """Run the family update through the shared swap pipeline."""
1579 self.runtime.run_pipeline(batches, step_context, self.step_batch)
1581 def step_batch(self, batch: List[SwapUpdateUnit], step_context: Any) -> Any:
1582 """Update one resident batch; optimizer-family adapters must implement it."""
1583 del batch, step_context
1584 raise NotImplementedError
1586 def _refresh_packed_state_bindings(self) -> None:
1587 """Index packed slots by their live optimizer-state owner."""
1588 bindings = {}
1589 for group in self.optimizer.param_groups:
1590 for param in group["params"]:
1591 for key in self._configured_state_keys():
1592 slot = self._slots.get((id(param), key))
1593 if slot is not None and slot.packed:
1594 bindings[id(slot)] = (param, key)
1595 self._packed_state_bindings = bindings
1597 def on_packed_slot_bound(self, slot: SwapSlot) -> None:
1598 """Publish a packed host or staging view into optimizer state."""
1599 binding = self._packed_state_bindings.get(id(slot))
1600 if binding is None:
1601 raise RuntimeError(f"Packed optimizer slot {slot.name!r} has no live state binding.")
1602 param, key = binding
1603 state = self.optimizer.state.get(param)
1604 if state is None:
1605 raise RuntimeError(f"Packed optimizer slot {slot.name!r} has no optimizer state entry.")
1606 state[key] = slot.tensor
1608 def initial_slots(self) -> Iterable[SwapSlot]:
1609 """Discover optimizer states materialized before the swap wrapper was created."""
1610 slots = []
1611 for group in self.optimizer.param_groups:
1612 for param in group["params"]:
1613 state = self.optimizer.state.get(param)
1614 if state:
1615 slots.extend(self._build_slots(param, state))
1616 return tuple(slots)
1618 def finish_step(self, step_context: Any) -> Any:
1619 """Finish one outer optimizer step."""
1620 del step_context
1622 def _checkpoint_broadcast_state_keys(self) -> Tuple[str, ...]:
1623 """Return the wrapped optimizer state fields consumed by its broadcast."""
1624 get_state_keys = getattr(self.optimizer, "_state_keys_for_checkpoint_broadcast", None)
1625 if not callable(get_state_keys):
1626 return ()
1627 return tuple(get_state_keys())
1629 def _make_checkpoint_cpu_tensor(self, param: Any) -> torch.Tensor:
1630 """Allocate one host receiver matching the optimizer broadcast contract."""
1631 local_param = self.runtime._storage_tensor(param)
1632 try:
1633 return torch.empty_like(local_param, dtype=torch.float32, device="cpu", pin_memory=True)
1634 except RuntimeError:
1635 return torch.empty_like(local_param, dtype=torch.float32, device="cpu")
1637 def _publish_checkpoint_cpu_state(self) -> None:
1638 """Expose CPU mirrors and host receivers to the fused state broadcast.
1640 The wrapped broadcast packs these tensors into one bounded device buffer
1641 per batch. Existing swap slots therefore stay host-resident, while ranks
1642 without owner state receive directly into temporary CPU tensors.
1643 """
1644 broadcast_info = getattr(self.optimizer, "_param_to_broadcast_info", None)
1645 state_keys = self._checkpoint_broadcast_state_keys()
1646 if not broadcast_info or not state_keys:
1647 return
1649 for param in broadcast_info:
1650 param_state = self.optimizer.state.get(param)
1651 if param_state is None:
1652 param_state = {}
1653 for key in state_keys:
1654 slot = self._slots.get((id(param), key))
1655 replacement = None
1656 if slot is not None and slot.swappable:
1657 if slot.state != "host" or slot.cpu_tensor is None:
1658 raise RuntimeError(
1659 f"Checkpoint state slot {key!r} must have an authoritative CPU mirror."
1660 )
1661 replacement = slot.cpu_tensor
1662 elif key not in param_state:
1663 replacement = self._make_checkpoint_cpu_tensor(param)
1665 if replacement is None:
1666 continue
1667 if param not in self.optimizer.state:
1668 self.optimizer.state[param] = param_state
1669 previous = param_state.get(key, _MISSING_CHECKPOINT_STATE)
1670 self._checkpoint_state_bindings.append((param, key, previous))
1671 param_state[key] = replacement
1673 def _restore_checkpoint_state_bindings(self) -> None:
1674 """Restore live state entries after exporting the CPU checkpoint values."""
1675 for param, key, previous in reversed(self._checkpoint_state_bindings):
1676 param_state = self.optimizer.state.get(param)
1677 if param_state is None:
1678 continue
1679 if previous is _MISSING_CHECKPOINT_STATE:
1680 param_state.pop(key, None)
1681 if not param_state:
1682 self.optimizer.state.pop(param, None)
1683 else:
1684 param_state[key] = previous
1685 self._checkpoint_state_bindings.clear()
1687 def prepare_checkpoint(self) -> None:
1688 """Publish host-resident swap state for an optional HSDP broadcast."""
1689 if self._checkpoint_active:
1690 return
1691 self._checkpoint_active = True
1692 self._checkpoint_broadcasted = False
1693 try:
1694 self._refresh_packed_state_bindings()
1695 # A previous optimizer step may still have a completed D2H event or
1696 # a live device state. Make the host mirror authoritative first;
1697 # the broadcast streams it through its bounded device buffer.
1698 self.runtime.synchronize_cpu_mirrors(self.all_slots())
1699 self._publish_checkpoint_cpu_state()
1700 except Exception:
1701 try:
1702 self.runtime.synchronize_cpu_mirrors(self.all_slots())
1703 except RuntimeError: # pragma: no cover - best effort after a transfer failure
1704 logger.exception("Failed to restore swap slots after checkpoint preparation failed")
1705 finally:
1706 self._restore_checkpoint_state_bindings()
1707 self._checkpoint_active = False
1708 self._checkpoint_broadcasted = False
1709 raise
1711 def finish_checkpoint(self) -> None:
1712 """Return checkpoint-broadcast state to the normal host-resident form."""
1713 if not self._checkpoint_active:
1714 return
1715 try:
1716 self.runtime.synchronize_cpu_mirrors(self.all_slots())
1717 finally:
1718 self._restore_checkpoint_state_bindings()
1719 self._checkpoint_active = False
1720 self._checkpoint_broadcasted = False
1722 def recovery_state(self, param: Any) -> Dict[str, Any]:
1723 """Return committed local state values from their authoritative storage."""
1724 state = dict(self.optimizer.state.get(param, {}))
1725 for key in self._configured_state_keys():
1726 slot = self._slots.get((id(param), key))
1727 if slot is None or not slot.swappable:
1728 continue
1729 if slot.event is not None or not self.has_host_mirror(slot):
1730 raise RuntimeError(f"Swap slot {key!r} has not finished writing its CPU mirror.")
1731 state[key] = slot.cpu_tensor
1732 return state
1734 def clear_recovery_slots(self) -> None:
1735 """Forget receiver slots before binding the donor's state layout."""
1736 self._slots.clear()
1737 self._packed_state_bindings.clear()
1738 self.runtime.invalidate_packed_layout()
1740 def step_state_device(self, param: Any, group: Dict[str, Any]) -> Any:
1741 """Return the local device for a scalar optimizer step tensor."""
1742 del group
1743 return param.device
1745 def allocate_recovery_state(self, param: Any, key: str, dtype: torch.dtype) -> Any:
1746 """Allocate a moment and bind a slot using the local swap policy."""
1747 param_local = self.runtime._storage_tensor(param)
1748 tensor = _restore_dtensor_metadata(param, torch.empty_like(param_local, dtype=dtype))
1749 if key not in self._configured_state_keys():
1750 return tensor
1751 slot = self._make_slot(key, tensor)
1752 self._slots[(id(param), key)] = slot
1753 if not slot.swappable:
1754 return tensor
1755 slot.cpu_tensor = self.runtime.make_zero_cpu_tensor_like(tensor)
1756 self.runtime.release_device_storage(slot)
1757 slot.state = "host"
1758 if slot.packed:
1759 slot.bind_tensor(slot.cpu_tensor)
1760 return slot.tensor
1762 def all_slots(self) -> Iterable[SwapSlot]:
1763 """Iterate known swap slots."""
1764 return tuple(self._ordered_slots())
1766 def tracked_slots(self) -> Iterable[SwapSlot]:
1767 """Return all registered slots, including parameters removed from groups."""
1768 return tuple({id(slot): slot for slot in self._slots.values()}.values())
1770 def rebind_parameter_slots(self, new_to_old_param: Dict[Any, Any]) -> None:
1771 """Rebuild state bindings using an explicit parameter identity mapping.
1773 Args:
1774 new_to_old_param: New-to-old identities; unrelated leaf entries are
1775 ignored. CPU mirrors must already be synchronized.
1777 Raises:
1778 ValueError: If a state cannot be mapped to the new local shape.
1779 """
1780 params = [param for group in self.optimizer.param_groups for param in group["params"]]
1781 local_ids = {id(param) for param in self._params_with_local_state(params)}
1782 rebound_slots = {}
1783 rebound_state = {}
1784 for param in params:
1785 if id(param) not in local_ids:
1786 continue
1787 old_param = new_to_old_param.get(param, param)
1788 state = self.optimizer.state.get(param, self.optimizer.state.get(old_param))
1789 if state is None:
1790 continue
1791 state = dict(state)
1792 for key in self._configured_state_keys():
1793 if key not in state:
1794 continue
1795 slot = self._slots.get((id(param), key))
1796 if slot is None:
1797 slot = self._slots.get((id(old_param), key))
1798 slot = self._rebind_state_slot(param, key, state[key], slot, param is not old_param)
1799 state[key] = slot.tensor
1800 rebound_slots[(id(param), key)] = slot
1801 rebound_state[param] = state
1803 # Publish only after all sources have been read. A failed conversion must
1804 # leave the old slot map (and its authoritative CPU mirrors) recoverable.
1805 for param in list(self.optimizer.state):
1806 if isinstance(param, torch.Tensor) and param not in rebound_state:
1807 self.optimizer.state.pop(param)
1808 self.optimizer.state.update(rebound_state)
1809 self._slots = rebound_slots
1810 self._refresh_packed_state_bindings()
1812 def _rebind_state_slot(
1813 self, param: Any, key: str, tensor: Any, slot: Optional[SwapSlot], replaced: bool,
1814 ) -> SwapSlot:
1815 """Preserve a compatible binding or recreate it from authoritative values."""
1816 local_param = self.runtime._storage_tensor(param)
1817 if slot is not None and (tensor is slot.tensor or tensor is slot.cpu_tensor):
1818 if (not replaced and slot.shape == tuple(local_param.shape)
1819 and slot.dtype == local_param.dtype and slot.device == local_param.device
1820 and not self.runtime.is_distributed_tensor(param)):
1821 return slot
1822 source = slot.checkpoint_tensor
1823 else:
1824 # Identity verifies a missing map; it never infers a replacement.
1825 if any(tensor is tracked.tensor or tensor is tracked.cpu_tensor for tracked in self._slots.values()):
1826 raise ValueError("Replacing a swap parameter requires an explicit new_to_old_param mapping.")
1827 source = tensor
1828 source = self.runtime._storage_tensor(source)
1829 if source.numel() != local_param.numel():
1830 raise ValueError(
1831 f"Cannot rebind {key!r} with local shape {tuple(source.shape)} "
1832 f"to {tuple(local_param.shape)}; restore state for the new layout first."
1833 )
1834 cpu_tensor = self._cast_swappable_tensor_to_cpu(param, source).reshape(local_param.shape)
1835 device_tensor = self.runtime.make_empty_state_like(param)
1836 rebound = self._make_slot(key, device_tensor)
1837 if rebound.swappable:
1838 rebound.cpu_tensor = self.runtime.make_cpu_tensor(cpu_tensor)
1839 rebound.state = "host"
1840 self.runtime.release_device_storage(rebound)
1841 if rebound.packed:
1842 rebound.bind_tensor(rebound.cpu_tensor)
1843 else:
1844 self.runtime._storage_tensor(device_tensor).copy_(cpu_tensor)
1845 return rebound
1847 def checkpoint_state_dict(self, *args: Any, **kwargs: Any) -> Dict[str, Any]:
1848 """Return optimizer checkpoint state using CPU mirrors for swapped slots."""
1849 del args, kwargs
1850 self._refresh_packed_state_bindings()
1851 self.runtime.synchronize_cpu_mirrors(self.all_slots())
1852 return self.export_swappable_state(self.optimizer.state_dict())
1854 @contextlib.contextmanager
1855 def checkpoint_load_context(self, state_dict: Dict[str, Any], flatten: bool) -> Iterable[None]:
1856 """Provide state keys for FQN loading without an initialization step.
1858 Args:
1859 state_dict: Chain checkpoint keyed by model FQN.
1860 flatten: Whether the checkpoint uses flattened FQN entries.
1861 """
1862 previous_state = self.optimizer.state
1863 schema = copy.copy(previous_state)
1864 schema.clear()
1865 for group in self.optimizer.param_groups:
1866 for param in group["params"]:
1867 name = param.model_name
1868 if flatten:
1869 prefix = f"state.{name}."
1870 schema[param] = {
1871 key[len(prefix):].split(".", 1)[0]: None
1872 for key in state_dict if key.startswith(prefix)
1873 }
1874 else:
1875 schema[param] = dict(state_dict.get("state", {}).get(name, {}))
1876 # DCP uses live state keys to unflatten and calls step() if state is
1877 # empty. Empty owner ranks must never initiate that extra collective.
1878 self.optimizer.state = schema
1879 try:
1880 yield
1881 finally:
1882 if self.optimizer.state is schema:
1883 self.optimizer.state = previous_state
1885 def load_checkpoint_state_dict(
1886 self,
1887 state_dict: Dict[str, Any],
1888 *args: Any,
1889 **kwargs: Any,
1890 ) -> None:
1891 """Load optimizer checkpoint state while restoring swap-managed slots."""
1892 del args, kwargs
1893 stripped, removed = self.strip_swappable_state(state_dict)
1894 self.optimizer.load_state_dict(stripped)
1895 self.load_swappable_state(state_dict, removed)
1897 def _params_with_local_state(self, params: Sequence[Any]) -> Iterable[Any]:
1898 """Return parameters whose swapped state belongs to this rank.
1900 The default restores every checkpoint entry. Distributed optimizer
1901 adapters may filter the sequence to preserve rank-local state ownership.
1902 """
1903 return params
1905 def publish_packed_state(self) -> None:
1906 """Publish persistent packed CPU mirrors to the wrapped optimizer state."""
1907 if not self.runtime.packed_enabled:
1908 return
1909 self._refresh_packed_state_bindings()
1910 for group in self.optimizer.param_groups:
1911 for param in group["params"]:
1912 state = self.optimizer.state.get(param)
1913 for key in self._configured_state_keys():
1914 slot = self._slots.get((id(param), key))
1915 if slot is None or not slot.packed or slot.cpu_tensor is None:
1916 continue
1917 if state is None:
1918 state = self.optimizer.state[param]
1919 state[key] = slot.cpu_tensor
1921 def export_swappable_state(self, state_dict: Dict[str, Any]) -> Dict[str, Any]:
1922 """Build a checkpoint-safe Torch optimizer state dict.
1924 Torch optimizer state dicts are keyed by saved parameter ids, while the
1925 adapter tracks live swap slots by the current parameter objects. This
1926 method walks both orders together and exports each parameter's optimizer
1927 state with the data source that currently owns the valid tensor values.
1929 If an Adam state tensor such as ``exp_avg`` or ``exp_avg_sq`` has been
1930 offloaded, the live device tensor may only be a placeholder with its
1931 storage released. In that case, write a cloned CPU mirror into the
1932 exported state dict so checkpoints contain the real optimizer values.
1933 Non-swappable state, metadata, and tensors that are still resident on
1934 device are deep-copied from the original Torch state dict unchanged.
1935 """
1936 exported = {
1937 key: self._copy_checkpoint_value(value)
1938 for key, value in state_dict.items()
1939 if key not in ("state", "param_groups")
1940 }
1941 exported["param_groups"] = self._copy_checkpoint_value(
1942 state_dict.get("param_groups", [])
1943 )
1944 exported["state"] = {}
1945 saved_groups = exported.get("param_groups", [])
1946 params_in_order = []
1947 for group in self.optimizer.param_groups:
1948 params_in_order.extend(group["params"])
1949 ids_in_order = []
1950 for group in saved_groups:
1951 ids_in_order.extend(group["params"])
1952 for param, param_id in zip(params_in_order, ids_in_order):
1953 saved_state = state_dict.get("state", {}).get(param_id)
1954 if not saved_state:
1955 continue
1956 exported_state = {}
1957 swappable_keys = self._state_keys_for_param(param)
1958 for key in swappable_keys:
1959 slot = self._slots.get((id(param), key))
1960 if key in saved_state and self.has_host_mirror(slot):
1961 local_copy = slot.cpu_tensor.detach().clone()
1962 exported_state[key] = _restore_dtensor_metadata(param, local_copy)
1963 for key, value in saved_state.items():
1964 if key not in exported_state:
1965 copied_value = self._copy_checkpoint_value(value)
1966 # Non-owner HSDP checkpoint receivers are plain local CPU tensors.
1967 # Restore the parameter layout before DCP consumes their metadata.
1968 if (key in swappable_keys and isinstance(copied_value, torch.Tensor)
1969 and not self.runtime.is_distributed_tensor(copied_value)):
1970 copied_value = _restore_dtensor_metadata(param, copied_value)
1971 exported_state[key] = copied_value
1972 exported["state"][param_id] = exported_state
1973 return exported
1975 @staticmethod
1976 def _copy_checkpoint_value(value: Any) -> Any:
1977 """Clone checkpoint values without dispatching ``deepcopy`` on DTensor.
1979 HSDP state broadcasts may leave a distributed tensor in the wrapped
1980 optimizer state. Hyper DTensor intentionally rejects unregistered
1981 ``__deepcopy__`` dispatch, so clone its local shard and restore the
1982 global layout explicitly. Nested containers are copied recursively;
1983 scalar metadata still uses regular ``copy.deepcopy`` semantics.
1984 """
1985 if isinstance(value, torch.Tensor):
1986 to_local = getattr(value, "to_local", None)
1987 local = to_local() if callable(to_local) else value
1988 if local is not value:
1989 local_copy = local.detach().cpu().clone()
1990 return _restore_dtensor_metadata(value, local_copy)
1991 return copy.deepcopy(value)
1992 if isinstance(value, dict):
1993 return {
1994 key: StateSwapAdapter._copy_checkpoint_value(item)
1995 for key, item in value.items()
1996 }
1997 if isinstance(value, list):
1998 return [StateSwapAdapter._copy_checkpoint_value(item) for item in value]
1999 if isinstance(value, tuple):
2000 return tuple(StateSwapAdapter._copy_checkpoint_value(item) for item in value)
2001 return copy.deepcopy(value)
2003 @staticmethod
2004 def has_host_mirror(slot: Optional[SwapSlot]) -> bool:
2005 """Return whether the slot is host-resident and holds a CPU mirror."""
2006 return slot is not None and slot.state == "host" and slot.cpu_tensor is not None
2008 def strip_swappable_state(self, state_dict: Dict[str, Any]) -> Tuple[Dict[str, Any], Dict[int, Dict[str, Any]]]:
2009 """Split Adam state tensors out before delegating to Torch loading.
2011 PyTorch's ``load_state_dict`` eagerly restores tensors into the
2012 optimizer state. For swap-managed Adam buffers, that would bypass the
2013 adapter/runtime bookkeeping and can place large tensors directly on the
2014 device. This method therefore copies the checkpoint state dict's
2015 *containers*, removes the Adam buffers that may be swap-managed, and
2016 returns them in a side table keyed by the checkpoint parameter id.
2018 Only the container skeleton is rebuilt: leaf tensors are shared with the
2019 caller's checkpoint instead of being duplicated. The removed buffers are
2020 consumed by :meth:`load_swappable_state`, which either takes a reference
2021 to the checkpoint storage (CPU checkpoints, where ``to(device="cpu")`` is
2022 a no-op) or copies it once into a host mirror. Deep-copying the whole
2023 state dict would hold one extra full copy of every optimizer tensor on
2024 host memory for the duration of the load, which for large models is a
2025 needless doubling of the checkpoint-loading peak.
2027 The stripped state dict is safe to pass to the wrapped optimizer's
2028 ``load_state_dict`` for ordinary fields such as parameter groups and
2029 step counters: Torch does not mutate the tensors it reads from it. The
2030 removed tensors must be handed to ``load_swappable_state`` afterwards so
2031 they can be restored with the correct CPU mirror/device placeholder
2032 layout.
2033 """
2034 stripped = self._copy_state_dict_containers(state_dict)
2035 removed: Dict[int, Dict[str, Any]] = {}
2036 swappable_keys = self._configured_state_keys()
2037 for param_id, saved_state in list(stripped.get("state", {}).items()):
2038 if not isinstance(saved_state, dict):
2039 continue
2040 for key in swappable_keys:
2041 if key in saved_state:
2042 removed.setdefault(param_id, {})[key] = saved_state.pop(key)
2043 return stripped, removed
2045 @staticmethod
2046 def _copy_state_dict_containers(state_dict: Dict[str, Any]) -> Dict[str, Any]:
2047 """Shallow-copy a checkpoint state dict, sharing every leaf tensor.
2049 Rebuilds only the nesting Torch's ``load_state_dict`` walks: the top
2050 level, the ``state`` per-parameter mappings, and the ``param_groups``
2051 entries. Do not add tensor copies here: this helper exists to keep the
2052 checkpoint-loading host peak free of a duplicate optimizer state.
2053 """
2054 state = state_dict.get("state")
2055 copied_state = (
2056 {param_id: dict(saved_state) if isinstance(saved_state, dict) else saved_state
2057 for param_id, saved_state in state.items()}
2058 if isinstance(state, dict)
2059 else state
2060 )
2061 param_groups = state_dict.get("param_groups")
2062 copied_groups = (
2063 [dict(group) if isinstance(group, dict) else group for group in param_groups]
2064 if isinstance(param_groups, list)
2065 else param_groups
2066 )
2067 copied = {key: value for key, value in state_dict.items() if key not in ("state", "param_groups")}
2068 if state is not None:
2069 copied["state"] = copied_state
2070 if param_groups is not None:
2071 copied["param_groups"] = copied_groups
2072 return copied
2074 def load_swappable_state(self, original_state_dict: Dict[str, Any], removed: Dict[int, Dict[str, Any]]) -> None:
2075 """Restore removed Adam buffers under swap runtime control.
2077 This is the second half of checkpoint loading. After Torch has loaded
2078 the stripped state dict, this method maps checkpoint parameter ids back
2079 to the current parameter objects by walking saved and current parameter
2080 groups in order. Each removed Adam buffer is then recreated as an
2081 optimizer state entry and registered as a ``SwapSlot``.
2083 Packed runtimes place checkpoint values directly in persistent pinned
2084 host views. Legacy runtimes retain an empty device placeholder whose
2085 storage is restored only during prefetch. Buffers that do not meet the
2086 runtime's swappability criteria are materialized directly on the
2087 parameter's device and tracked as normal device-resident slots.
2088 """
2089 saved_groups = original_state_dict.get("param_groups", [])
2090 self._slots = {}
2091 # Walk saved and current parameter groups in order to map checkpoint ids
2092 # back to the live parameter objects.
2093 saved_ids = [
2094 saved_id
2095 for saved_group, current_group in zip(saved_groups, self.optimizer.param_groups)
2096 for saved_id in saved_group["params"]
2097 ]
2098 groups = self.optimizer.param_groups
2099 current_params = [param for group in groups for param in group["params"]]
2100 local_param_ids = {
2101 id(param) for param in self._params_with_local_state(current_params)
2102 }
2103 for saved_id, param in zip(saved_ids, current_params):
2104 if id(param) not in local_param_ids:
2105 self.optimizer.state.pop(param, None)
2106 continue
2107 for key, saved_tensor in removed.get(saved_id, {}).items():
2108 self._restore_swappable_entry(param, saved_id, saved_groups, key, saved_tensor)
2109 if self.runtime.packed_enabled:
2110 self.runtime.prepare_packed_host(self._ordered_slots())
2111 self.publish_packed_state()
2113 def _restore_swappable_entry(
2114 self,
2115 param: Any,
2116 saved_id: int,
2117 saved_groups: List[Dict[str, Any]],
2118 key: str,
2119 saved_tensor: Any,
2120 ) -> None:
2121 """Restore one removed checkpoint buffer as a host or device-resident slot."""
2122 state = self.optimizer.state[param]
2123 cpu_tensor = self._cast_swappable_tensor_to_cpu(param, saved_tensor)
2124 if self.runtime.packed_enabled and self.runtime.is_packable_template(param, self.config.min_numel):
2125 if self.runtime.is_distributed_tensor(param):
2126 logical_tensor = self.runtime.make_empty_state_like(param)
2127 slot = self._make_slot(key, logical_tensor)
2128 state[key] = logical_tensor
2129 self.runtime.release_device_storage(slot)
2130 else:
2131 slot = self._make_slot(key, None, template=param)
2132 state[key] = cpu_tensor
2133 slot.tensor = cpu_tensor
2134 slot.cpu_tensor = cpu_tensor
2135 slot.state = "host"
2136 self._slots[(id(param), key)] = slot
2137 return
2138 device_tensor = self.runtime.make_empty_device_tensor_like(param, cpu_tensor)
2139 slot = self._make_slot(key, device_tensor)
2140 if slot.swappable:
2141 state[key] = device_tensor
2142 slot.cpu_tensor = self.runtime.make_cpu_tensor(cpu_tensor)
2143 slot.state = "host"
2144 self._slots[(id(param), key)] = slot
2145 self.runtime.release_device_storage(slot)
2146 else:
2147 device_tensor = self._cast_state_tensor_like_torch(
2148 param,
2149 saved_tensor,
2150 saved_id,
2151 saved_groups,
2152 key,
2153 )
2154 state[key] = device_tensor
2155 self._slots[(id(param), key)] = self._make_slot(key, device_tensor)
2157 @staticmethod
2158 def _cast_state_tensor_like_torch(
2159 param: Any,
2160 saved_tensor: Any,
2161 saved_id: int,
2162 saved_groups: List[Dict[str, Any]],
2163 key: str,
2164 ) -> Any:
2165 """Cast a loaded state tensor using PyTorch optimizer load semantics."""
2166 if not isinstance(saved_tensor, torch.Tensor):
2167 raise ValueError(f"Expected torch.Tensor in optimizer state, got {type(saved_tensor)!r}.")
2168 process = getattr(torch.optim.Optimizer, "_process_value_according_to_param_policy", None)
2169 if process is not None:
2170 return process(param, saved_tensor, saved_id, saved_groups, key).detach().clone()
2171 if key == "step":
2172 return saved_tensor.detach().clone()
2173 if param.is_floating_point():
2174 return saved_tensor.detach().to(dtype=param.dtype, device=param.device).clone()
2175 return saved_tensor.detach().to(device=param.device).clone()
2177 @staticmethod
2178 def _cast_swappable_tensor_to_cpu(param: Any, saved_tensor: Any) -> Any:
2179 """Cast swappable state dtype like PyTorch while keeping values on CPU."""
2180 if not isinstance(saved_tensor, torch.Tensor):
2181 raise ValueError(f"Expected torch.Tensor in optimizer state, got {type(saved_tensor)!r}.")
2182 to_local = getattr(saved_tensor, "to_local", None)
2183 source = to_local() if callable(to_local) else saved_tensor
2184 if param.is_floating_point():
2185 return source.detach().to(dtype=param.dtype, device="cpu")
2186 return source.detach().to(device="cpu")
2188 def _register_present_slots(self, param: Any, state: Dict[str, Any]) -> None:
2189 """Register configured state tensors that already exist in an optimizer state mapping."""
2190 for key in self._configured_state_keys():
2191 tensor = state.get(key)
2192 if tensor is None or (id(param), key) in self._slots:
2193 continue
2194 self._slots[(id(param), key)] = self._make_slot(key, tensor)
2196 def _build_slots(self, param: Any, state: Dict[str, Any]) -> List[SwapSlot]:
2197 """Return swap slots associated with the current parameter state."""
2198 slots = []
2199 for key in self._state_keys_for_param(param):
2200 tensor = state.get(key)
2201 if tensor is None:
2202 continue
2203 slot = self._slots.get((id(param), key))
2204 if slot is None:
2205 slot = self._make_slot(key, tensor)
2206 self._slots[(id(param), key)] = slot
2207 elif slot.tensor is not tensor and slot.cpu_tensor is not tensor:
2208 slot = self._make_slot(key, tensor)
2209 self._slots[(id(param), key)] = slot
2210 slots.append(slot)
2211 return slots
2213 def _make_slot(self, key: str, tensor: Any, template: Optional[Any] = None) -> SwapSlot:
2214 """Create a swap slot for a state tensor or a packed-state template."""
2215 metadata_tensor = tensor if tensor is not None else template
2216 if metadata_tensor is None:
2217 raise ValueError(f"Cannot build swap slot {key!r} without a tensor or template.")
2218 if tensor is None:
2219 swappable = self.runtime.is_packable_template(metadata_tensor, self.config.min_numel)
2220 else:
2221 swappable = self.runtime.is_swappable_tensor(tensor, self.config.min_numel)
2222 packed = bool(self.runtime.packed_enabled and swappable)
2223 slot = SwapSlot(
2224 name=key,
2225 tensor=tensor,
2226 cpu_tensor=None,
2227 swappable=swappable,
2228 state="device" if tensor is not None else "pending",
2229 packed=packed,
2230 logical_tensor=tensor if packed and self.runtime.is_distributed_tensor(tensor) else None,
2231 )
2232 self.runtime.populate_slot_metadata(slot, metadata_tensor)
2233 return slot
2235 def _ordered_slots(self) -> List[SwapSlot]:
2236 """Return slots in optimizer parameter and configured state-key order."""
2237 slots = []
2238 seen_slots = set()
2239 for group in self.optimizer.param_groups:
2240 for param in group["params"]:
2241 for key in self._configured_state_keys():
2242 slot = self._slots.get((id(param), key))
2243 if slot is not None and id(slot) not in seen_slots:
2244 slots.append(slot)
2245 seen_slots.add(id(slot))
2246 return slots
2248 def _state_keys_for_param(self, param: Any) -> Tuple[str, ...]:
2249 state = self.optimizer.state[param]
2250 keys = self._configured_state_keys()
2251 result = []
2252 for key in keys:
2253 if key in state:
2254 result.append(key)
2255 elif self.config.state_keys is not None:
2256 raise ValueError(f"Requested state key '{key}' is not present for parameter.")
2257 return tuple(result)
2259 def _configured_state_keys(self) -> Tuple[str, ...]:
2260 """Return optimizer state keys selected for swap by the current config."""
2261 return tuple(self.config.state_keys or self.default_state_keys())
2264class SwapOptimizer(torch.optim.Optimizer):
2265 """Torch optimizer wrapper around a family-provided swap adapter.
2267 The wrapper is algorithm agnostic: it owns the pipeline runtime, exposes the
2268 wrapped optimizer's ``param_groups``/``state``/``defaults`` and drives one
2269 step as ``prepare_step`` -> ``partition`` -> ``run_pipeline`` ->
2270 ``finish_step``. Every step passes through PyTorch's hook dispatcher,
2271 including steps with no hooks currently registered, so hooks added later
2272 take effect. Step hooks must not access optimizer state because swapped
2273 tensors are not materialized for hook execution. The concrete adapter is
2274 built by the family factory passed as ``adapter_factory`` (see
2275 ``swap_adam.py``/``swap_muon.py``).
2276 """
2278 _is_swap_optimizer = True
2280 def __init__(self, optimizer: Any, config: Any, adapter_factory: AdapterFactory) -> None:
2281 """Wrap a leaf with its family adapter and independent transfer runtime."""
2282 # Do not call ``torch.optim.Optimizer.__init__``: the wrapped base
2283 # optimizer already owns param_groups/state/defaults. Inheriting keeps
2284 # PyTorch LR schedulers and isinstance checks happy while this wrapper
2285 # delegates all optimizer state to ``self.optimizer``.
2286 self.optimizer = optimizer
2287 self.config = config
2288 self._hooked_leaf_step = _build_profiled_step(self)
2289 self._step_active = False
2290 self._reset_active = False
2291 self._reset_required = False
2292 self._export_active = False
2293 self.runtime = PipelineSwapRuntime(config)
2294 self.adapter = adapter_factory(optimizer, config, self.runtime)
2295 self.adapter.validate()
2296 # Torch Adam states are normally lazy, but callers may materialize them
2297 # before wrapping to avoid first-step initialization in the measured loop.
2298 initial_slots = tuple(self.adapter.initial_slots())
2299 self.runtime.offload_initial_slots(initial_slots)
2300 self.runtime.prepare_packed_host(initial_slots)
2301 self.adapter.publish_packed_state()
2303 def __getattr__(self, name: str) -> Any:
2304 """Delegate unknown attributes to the base optimizer."""
2305 return getattr(self.optimizer, name)
2307 @property
2308 def param_groups(self) -> List[Dict[str, Any]]:
2309 """Proxy parameter groups."""
2310 return self.optimizer.param_groups
2312 @param_groups.setter
2313 def param_groups(self, value: List[Dict[str, Any]]) -> None:
2314 """Replace the underlying optimizer's parameter groups."""
2315 self.optimizer.param_groups = value
2317 @property
2318 def state(self) -> Dict[Any, Any]:
2319 """Proxy optimizer state."""
2320 return self.optimizer.state
2322 @property
2323 def defaults(self) -> Dict[str, Any]:
2324 """Proxy optimizer defaults."""
2325 return self.optimizer.defaults
2327 def add_param_group(self, param_group: Dict[str, Any]) -> None:
2328 """Proxy param group addition."""
2329 self.optimizer.add_param_group(param_group)
2331 def zero_grad(self, set_to_none: bool = True) -> None:
2332 """Proxy gradient clearing."""
2333 self.optimizer.zero_grad(set_to_none=set_to_none)
2335 def reset_optimizer_parameters(
2336 self, new_to_old_param: Optional[Dict[torch.nn.Parameter, torch.nn.Parameter]] = None,
2337 ) -> None:
2338 """Rebuild optimizer metadata and rebind state at an idle step boundary.
2340 Args:
2341 new_to_old_param: Explicit new-to-old identities after param_groups
2342 replacement. Omit when parameter identities are unchanged.
2344 Raises:
2345 RuntimeError: If a step, checkpoint or transfer is still active.
2346 """
2347 slots = tuple(self.adapter.tracked_slots())
2348 if (self._step_active or self._reset_active or self._export_active or self.adapter._checkpoint_active
2349 or self.runtime._packed_batch_plans or self.runtime._packed_tail_event is not None
2350 or any(slot.state in ("h2d", "d2h") for slot in slots)):
2351 raise RuntimeError("Cannot reset optimizer parameters during a step, checkpoint or transfer.")
2352 self._reset_active = True
2353 self._reset_required = True
2354 try:
2355 with self._no_grad_context():
2356 self.runtime.synchronize_cpu_mirrors(slots)
2357 reset = getattr(self.optimizer, "reset_optimizer_parameters", None)
2358 if callable(reset):
2359 reset()
2360 self.adapter.rebind_parameter_slots(new_to_old_param or {})
2361 self.runtime.invalidate_packed_layout()
2362 self._reset_required = False
2363 finally:
2364 self._reset_active = False
2366 def step(self, closure: Optional[Any] = None) -> Any:
2367 """Run one optimizer step through PyTorch's leaf hook dispatcher.
2369 The swap pipeline never runs a closure, so a non-None value is rejected
2370 before step hooks run, before any swap transfer is enqueued and before
2371 any optimizer state is rewritten. Omitted and explicit ``None`` closures
2372 are both forwarded to leaf hooks as ``closure=None``.
2374 Args:
2375 closure: Unsupported. Must be omitted or None.
2377 Raises:
2378 RuntimeError: If called recursively.
2379 ValueError: If a non-None closure is supplied.
2380 """
2381 if closure is not None:
2382 raise ValueError("Swap optimizer does not support closure.")
2383 if self._step_active:
2384 raise RuntimeError("Recursive SwapOptimizer.step() is not supported.")
2385 self._check_reset_complete()
2386 self._step_active = True
2387 try:
2388 return self._hooked_leaf_step(self.optimizer, closure=closure)
2389 finally:
2390 self._step_active = False
2392 def _step_impl(self, *args: Any, **kwargs: Any) -> Any:
2393 """Execute the swap pipeline between PyTorch pre- and post-hooks."""
2394 # ``step()`` already rejected the caller's closure; whatever arrives here
2395 # is either the forwarded ``closure=None`` or a pre-hook rewrite.
2396 if len(args) > 1 or set(kwargs) - {"closure"}:
2397 raise ValueError("Swap optimizer does not support extra step arguments.")
2398 if args and "closure" in kwargs:
2399 raise TypeError("closure was passed both positionally and by keyword.")
2400 closure = args[0] if args else kwargs.get("closure")
2401 if closure is not None:
2402 raise ValueError("Swap optimizer does not support closure.")
2404 with self._no_grad_context():
2405 step_context = self.adapter.prepare_step()
2406 units = self.adapter.iter_update_units(step_context)
2407 batches = self.adapter.partition_update_units(units, step_context)
2408 self.adapter.prepare_pipeline(batches, step_context)
2409 self.adapter.run_pipeline(batches, step_context)
2410 return self.adapter.finish_step(step_context)
2412 def _check_reset_complete(self) -> None:
2413 """Prevent using a partially rebuilt optimizer after reset failed."""
2414 if self._reset_required:
2415 raise RuntimeError("Optimizer parameter reset has not completed; retry reset before step or checkpoint.")
2417 def state_dict(self) -> Dict[str, Any]:
2418 """Return optimizer state dict using CPU mirrors for swappable tensors."""
2419 self._check_reset_complete()
2420 self._export_active = True
2421 try:
2422 return self._export_state_dict()
2423 finally:
2424 self._export_active = False
2426 def _export_state_dict(self) -> Dict[str, Any]:
2427 """Reuse an outer chain checkpoint window or open a leaf-owned window."""
2428 broadcast = getattr(self.optimizer, "_broadcast_state_fused_for_ckpt", None)
2429 if not callable(broadcast):
2430 return self.adapter.checkpoint_state_dict()
2432 owns_checkpoint_window = not self.adapter._checkpoint_active
2433 try:
2434 if owns_checkpoint_window:
2435 self._prepare_swap_checkpoint()
2436 if not self.adapter._checkpoint_broadcasted:
2437 self._broadcast_state_fused_for_ckpt()
2438 return self.adapter.checkpoint_state_dict()
2439 finally:
2440 if owns_checkpoint_window:
2441 self.cleanup_synced_state()
2443 def _prepare_swap_checkpoint(self) -> None:
2444 """Publish CPU swap state needed by an HSDP checkpoint broadcast."""
2445 self._check_reset_complete()
2446 broadcast = getattr(self.optimizer, "_broadcast_state_fused_for_ckpt", None)
2447 if callable(broadcast):
2448 self.adapter.prepare_checkpoint()
2450 @contextlib.contextmanager
2451 def _swap_checkpoint_load_context(self, state_dict: Dict[str, Any], flatten: bool) -> Iterable[None]:
2452 """Let chain loading discover state keys without updating any parameters."""
2453 previous_active = self._export_active
2454 self._export_active = True
2455 try:
2456 with self.adapter.checkpoint_load_context(state_dict, flatten):
2457 yield
2458 finally:
2459 self._export_active = previous_active
2461 def _finish_swap_checkpoint(self) -> None:
2462 """Return checkpoint-broadcast state to its normal swapped form."""
2463 self.adapter.finish_checkpoint()
2465 def _broadcast_state_fused_for_ckpt(self) -> None:
2466 """Broadcast wrapped optimizer state through bounded device buffers."""
2467 broadcast = getattr(self.optimizer, "_broadcast_state_fused_for_ckpt", None)
2468 if not callable(broadcast):
2469 return
2470 prepared_here = not self.adapter._checkpoint_active
2471 try:
2472 if prepared_here:
2473 self.adapter.prepare_checkpoint()
2474 broadcast()
2475 self.adapter._checkpoint_broadcasted = True
2476 except Exception:
2477 if prepared_here:
2478 self.cleanup_synced_state()
2479 raise
2481 def cleanup_synced_state(self) -> None:
2482 """Release HSDP checkpoint copies and restore host-resident slots."""
2483 try:
2484 self.adapter.finish_checkpoint()
2485 finally:
2486 cleanup = getattr(self.optimizer, "cleanup_synced_state", None)
2487 if callable(cleanup):
2488 cleanup()
2490 def load_state_dict(self, state_dict: Dict[str, Any]) -> None:
2491 """Load optimizer state dict while keeping swappable tensors on CPU mirrors."""
2492 previous_active = self._export_active
2493 self._export_active = True
2494 try:
2495 self.adapter.load_checkpoint_state_dict(state_dict)
2496 finally:
2497 self._export_active = previous_active
2499 @contextlib.contextmanager
2500 def _no_grad_context(self) -> Iterable[None]:
2501 with torch.no_grad():
2502 yield