Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / distributed / activation_checkpoint.py: 93%
441 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"""Model-agnostic activation checkpoint and swap installation."""
17import logging
18import weakref
19from dataclasses import dataclass
20from typing import Any, Optional, Sequence
22from torch import nn
24from hyper_parallel.core.activation_memory import (
25 ActivationWrapper,
26 PinnedMemoryPool,
27 SwapManager,
28 checkpoint_exclude_wrapper,
29 checkpoint_wrapper,
30 swap_wrapper,
31)
32from hyper_parallel.core.activation_memory.swap import _teardown_wired_swap_layers
34logger = logging.getLogger(__name__)
36_ACTIVE_MODES = frozenset(("full", "selective", "hybrid"))
37_MIB = 1024 * 1024
40@dataclass(frozen=True)
41class _TransformerBlockInfo:
42 """One transformer block in stable model registration order."""
44 fqn: str
45 module: nn.Module
46 parent: nn.Module
47 child_name: str
48 container_fqn: str
51@dataclass(frozen=True)
52class _LayerContainerInfo:
53 """One repeated-block container and its registered children."""
55 container: nn.Module
56 path: str
57 blocks: tuple[_TransformerBlockInfo, ...]
60@dataclass(frozen=True)
61class _ResolvedTarget:
62 """One validated layer-relative module replacement target."""
64 config_path: str
65 layer_index: int
66 layer_fqn: str
67 module_path: str
68 module_fqn: str
69 module_order: int
70 parent: nn.Module
71 child_name: str
72 module: nn.Module
75@dataclass(frozen=True)
76class _ResolvedModelTarget:
77 """One validated model-root-relative module replacement target."""
79 config_path: str
80 module_path: str
81 module_fqn: str
82 parent: nn.Module
83 child_name: str
84 module: nn.Module
87@dataclass(frozen=True)
88class _ActivationPlan:
89 """Fully resolved activation-wrapper installation plan."""
91 mode: str
92 full_layers: tuple[tuple[int, _TransformerBlockInfo], ...]
93 full_save_targets: tuple[_ResolvedTarget, ...]
94 full_swap_targets: tuple[_ResolvedTarget, ...]
95 selective_recompute_targets: tuple[_ResolvedTarget, ...]
96 selective_recompute_model_targets: tuple[_ResolvedModelTarget, ...]
97 selective_swap_targets: tuple[_ResolvedTarget, ...]
98 full_group_swap: bool
99 full_cpu_pool_mb: Optional[int]
100 selective_group_swap: bool
101 selective_cpu_pool_mb: Optional[int]
104@dataclass(frozen=True)
105class _ReplacementRecord:
106 """One reversible child-module replacement."""
108 parent: nn.Module
109 child_name: str
110 original: nn.Module
113def _is_repeated_block_container(container: nn.Module, children: list[tuple[str, nn.Module]]) -> bool:
114 """Return whether one child module structurally represents repeated blocks."""
115 if isinstance(container, nn.Sequential):
116 # Sequential stems and heads may contain unrelated operations rather than repeated blocks.
117 block_types = set()
118 for _, child in children:
119 wrapped_module = _get_checkpoint_wrapped_module(child)
120 block_types.add(type(child if wrapped_module is None else wrapped_module))
121 return len(block_types) == 1
122 if isinstance(container, (nn.ModuleList, nn.ModuleDict)):
123 return bool(children)
124 # Ordinary modules may contain same-type stages with different roles, such as an aligner's projections.
125 # Repeated blocks must use an explicit collection container so they do not enter layer numbering by accident.
126 return False
129def _get_checkpoint_wrapped_module(module: nn.Module) -> Optional[nn.Module]:
130 """Return a directly wrapped module for discovery de-duplication."""
131 for attr_name in ("_wrapped_module", "_checkpoint_wrapped_module"):
132 wrapped_module = getattr(module, attr_name, None)
133 if isinstance(wrapped_module, nn.Module):
134 return wrapped_module
135 return None
138def _find_transformer_block_modules(
139 model: nn.Module,
140) -> tuple[list[_TransformerBlockInfo], set[int]]:
141 """Find repeated transformer blocks below HF checkpointing owners.
143 The owner marker and depth-first registered child order are structural
144 contracts. No model family, class name, or conventional ``model.layers``
145 path is used.
146 """
147 block_infos = []
148 discovered_block_ids = set()
149 visited_module_ids = set()
151 def _visit(owner_fqn: str, owner: nn.Module) -> None:
152 owner_id = id(owner)
153 if owner_id in visited_module_ids or owner_id in discovered_block_ids:
154 return
155 visited_module_ids.add(owner_id)
156 is_checkpoint_owner = hasattr(owner, "gradient_checkpointing")
158 for container_name, container in owner.named_children():
159 container_fqn = f"{owner_fqn}.{container_name}" if owner_fqn else container_name
160 children = list(container.named_children())
161 if not is_checkpoint_owner or not _is_repeated_block_container(container, children):
162 _visit(container_fqn, container)
163 continue
165 visited_module_ids.add(id(container))
166 for block_name, block in children:
167 if id(block) in discovered_block_ids:
168 continue
169 discovered_block_ids.add(id(block))
170 wrapped_module = _get_checkpoint_wrapped_module(block)
171 if wrapped_module is not None:
172 discovered_block_ids.add(id(wrapped_module))
173 block_infos.append(
174 _TransformerBlockInfo(
175 fqn=f"{container_fqn}.{block_name}",
176 module=block,
177 parent=container,
178 child_name=block_name,
179 container_fqn=container_fqn,
180 )
181 )
183 _visit("", model)
184 return block_infos, discovered_block_ids
187def _find_transformer_layer_container_infos(model: nn.Module) -> list[_LayerContainerInfo]:
188 """Group discovered blocks by repeated-block container."""
189 block_infos, _ = _find_transformer_block_modules(model)
190 blocks_by_container: dict[int, list[_TransformerBlockInfo]] = {}
191 for block_info in block_infos:
192 blocks_by_container.setdefault(id(block_info.parent), []).append(block_info)
194 containers = []
195 seen_container_ids = set()
196 for block_info in block_infos:
197 container_id = id(block_info.parent)
198 if container_id in seen_container_ids:
199 continue
200 seen_container_ids.add(container_id)
201 containers.append(
202 _LayerContainerInfo(
203 container=block_info.parent,
204 path=block_info.container_fqn,
205 blocks=tuple(blocks_by_container[container_id]),
206 )
207 )
208 return containers
211def _flatten_layer_container_infos(
212 containers: list[_LayerContainerInfo],
213) -> list[_TransformerBlockInfo]:
214 """Flatten container metadata into stable global layer numbering."""
215 return [block for container in containers for block in container.blocks]
218def _resolve_activation_checkpoint_containers(
219 model: nn.Module,
220 *,
221 required: bool = True,
222) -> list[_LayerContainerInfo]:
223 """Discover repeated transformer containers and optionally require one."""
224 containers = _find_transformer_layer_container_infos(model)
225 if required and not containers:
226 raise ValueError(
227 f"{type(model).__name__} has no module with a 'gradient_checkpointing' "
228 "attribute and a non-empty repeated block container"
229 )
230 return containers
233def _current_block(block_info: _TransformerBlockInfo) -> nn.Module:
234 """Return the current registered block and reject structure drift."""
235 block = block_info.parent._modules.get(block_info.child_name) # pylint: disable=protected-access
236 if not isinstance(block, nn.Module):
237 raise ValueError(f"discovered layer {block_info.fqn} is no longer an nn.Module")
238 return block
241def _module_registration_order(layer: nn.Module) -> dict[str, int]:
242 """Return stable registered-module order within one layer."""
243 try:
244 iterator = layer.named_modules(remove_duplicate=False)
245 except TypeError:
246 iterator = layer.named_modules()
247 return {module_path: index for index, (module_path, _) in enumerate(iterator)}
250def _raise_incompatible_wrapper(
251 module: nn.Module,
252 *,
253 config_path: str,
254 layer_index: Optional[int],
255 module_path: str,
256 module_fqn: str,
257) -> None:
258 """Reject existing or partially removed activation wrappers."""
259 target_location = f"layer {layer_index}" if layer_index is not None else "model target"
260 for descendant in module.modules():
261 if isinstance(descendant, ActivationWrapper) or getattr(descendant, "_is_wrapped", False):
262 raise ValueError(
263 f"{config_path}: {target_location}, module {module_path!r} ({module_fqn}) "
264 "is already covered by an incompatible activation wrapper"
265 )
268def _resolve_module_target(
269 block_info: _TransformerBlockInfo,
270 *,
271 layer_index: int,
272 module_path: str,
273 config_path: str,
274) -> _ResolvedTarget:
275 """Resolve one exact relative module path inside a transformer layer."""
276 layer = _current_block(block_info)
277 current = layer
278 parent = layer
279 parts = module_path.split(".")
280 for part_index, part in enumerate(parts):
281 if isinstance(current, ActivationWrapper):
282 raise ValueError(
283 f"{config_path}: layer {layer_index}, module {module_path!r} crosses "
284 f"an existing activation wrapper at {block_info.fqn}"
285 )
286 parent = current
287 child = current._modules.get(part) # pylint: disable=protected-access
288 if not isinstance(child, nn.Module):
289 prefix = ".".join(parts[:part_index + 1])
290 full_fqn = f"{block_info.fqn}.{prefix}"
291 if hasattr(current, part):
292 raise ValueError(
293 f"{config_path}: layer {layer_index}, module {module_path!r} resolves "
294 f"{full_fqn} to non-nn.Module {type(getattr(current, part)).__name__}"
295 )
296 raise ValueError(
297 f"{config_path}: layer {layer_index}, module {module_path!r} does not exist "
298 f"at {full_fqn}"
299 )
300 current = child
302 module_fqn = f"{block_info.fqn}.{module_path}"
303 _raise_incompatible_wrapper(
304 current,
305 config_path=config_path,
306 layer_index=layer_index,
307 module_path=module_path,
308 module_fqn=module_fqn,
309 )
310 module_order = _module_registration_order(layer).get(module_path)
311 if module_order is None:
312 raise ValueError(
313 f"{config_path}: layer {layer_index}, module {module_path!r} ({module_fqn}) "
314 "has no stable registered forward order"
315 )
316 return _ResolvedTarget(
317 config_path=config_path,
318 layer_index=layer_index,
319 layer_fqn=block_info.fqn,
320 module_path=module_path,
321 module_fqn=module_fqn,
322 module_order=module_order,
323 parent=parent,
324 child_name=parts[-1],
325 module=current,
326 )
329def _resolve_model_target(
330 model: nn.Module,
331 blocks: list[_TransformerBlockInfo],
332 *,
333 module_path: str,
334 config_path: str,
335) -> _ResolvedModelTarget:
336 """Resolve one exact model-root-relative module outside transformer layers."""
337 current = model
338 parent = model
339 parts = module_path.split(".")
340 for part_index, part in enumerate(parts):
341 if isinstance(current, ActivationWrapper):
342 prefix = ".".join(parts[:part_index]) or "<model>"
343 raise ValueError(
344 f"{config_path}: model module {module_path!r} crosses an existing "
345 f"activation wrapper at {prefix}"
346 )
347 parent = current
348 child = current._modules.get(part) # pylint: disable=protected-access
349 prefix = ".".join(parts[:part_index + 1])
350 if not isinstance(child, nn.Module):
351 if hasattr(current, part):
352 raise ValueError(
353 f"{config_path}: model module {module_path!r} resolves {prefix} "
354 f"to non-nn.Module {type(getattr(current, part)).__name__}"
355 )
356 raise ValueError(
357 f"{config_path}: model module {module_path!r} does not exist at {prefix}"
358 )
359 current = child
361 target_module_ids = {id(module) for module in current.modules()}
362 for layer_index, block_info in enumerate(blocks):
363 layer = _current_block(block_info)
364 layer_module_ids = {id(module) for module in layer.modules()}
365 if id(current) in layer_module_ids or id(layer) in target_module_ids:
366 raise ValueError(
367 f"{config_path}: model module {module_path!r} must be outside transformer "
368 f"layers, but overlaps layer {layer_index} ({block_info.fqn})"
369 )
371 _raise_incompatible_wrapper(
372 current,
373 config_path=config_path,
374 layer_index=None,
375 module_path=module_path,
376 module_fqn=module_path,
377 )
378 return _ResolvedModelTarget(
379 config_path=config_path,
380 module_path=module_path,
381 module_fqn=module_path,
382 parent=parent,
383 child_name=parts[-1],
384 module=current,
385 )
388def _validate_layer_index(layer_index: int, layer_count: int, *, config_path: str) -> None:
389 """Validate one normalized layer index against discovered model layers."""
390 if layer_index < 0 or layer_index >= layer_count:
391 maximum = layer_count - 1
392 raise ValueError(
393 f"{config_path}: layer {layer_index} is outside the discovered range 0-{maximum}"
394 )
397def _resolve_regions(
398 blocks: list[_TransformerBlockInfo],
399 regions: tuple[Any, ...],
400 *,
401 config_path: str,
402) -> tuple[_ResolvedTarget, ...]:
403 """Resolve every normalized region spec without modifying the model."""
404 targets = []
405 for region in regions:
406 for layer_index in region.layers:
407 _validate_layer_index(layer_index, len(blocks), config_path=config_path)
408 targets.append(
409 _resolve_module_target(
410 blocks[layer_index],
411 layer_index=layer_index,
412 module_path=region.module_path,
413 config_path=f"{config_path}.{region.module_path}",
414 )
415 )
416 return tuple(targets)
419def _resolve_model_targets(
420 model: nn.Module,
421 blocks: list[_TransformerBlockInfo],
422 modules: tuple[Any, ...],
423 *,
424 config_path: str,
425) -> tuple[_ResolvedModelTarget, ...]:
426 """Resolve every normalized model-root-relative module target."""
427 return tuple(
428 _resolve_model_target(
429 model,
430 blocks,
431 module_path=module.module_path,
432 config_path=f"{config_path}.{module.module_path}",
433 )
434 for module in modules
435 )
438def _target_key(target: _ResolvedTarget) -> tuple[int, str]:
439 """Return one layer/path conflict key."""
440 return target.layer_index, target.module_path
443def _validate_nested_targets(targets: tuple[_ResolvedTarget, ...], *, config_path: str) -> None:
444 """Reject ancestor/descendant target pairs within one layer."""
445 by_layer: dict[int, list[_ResolvedTarget]] = {}
446 for target in targets:
447 by_layer.setdefault(target.layer_index, []).append(target)
448 for layer_index, layer_targets in by_layer.items():
449 for index, target in enumerate(layer_targets):
450 for other in layer_targets[index + 1:]:
451 if target.module_path.startswith(f"{other.module_path}.") or other.module_path.startswith(
452 f"{target.module_path}."
453 ):
454 raise ValueError(
455 f"{config_path}: layer {layer_index} has nested activation targets "
456 f"{target.module_path!r} ({target.module_fqn}) and "
457 f"{other.module_path!r} ({other.module_fqn})"
458 )
461def _target_description(target: Any) -> str:
462 """Format one resolved target without inventing a model-level layer index."""
463 if isinstance(target, _ResolvedTarget):
464 return (
465 f"{target.config_path}: layer {target.layer_index}, module "
466 f"{target.module_path!r} ({target.module_fqn})"
467 )
468 return f"{target.config_path}: model module {target.module_path!r} ({target.module_fqn})"
471def _validate_target_aliases(targets: tuple[Any, ...]) -> None:
472 """Reject one module object selected through multiple layer/path identities."""
473 by_identity: dict[int, Any] = {}
474 for target in targets:
475 previous = by_identity.get(id(target.module))
476 if previous is not None:
477 raise ValueError(
478 f"{_target_description(target)} aliases {_target_description(previous)}"
479 )
480 by_identity[id(target.module)] = target
483def _validate_model_target_nesting(
484 model_targets: tuple[_ResolvedModelTarget, ...],
485 all_targets: tuple[Any, ...],
486) -> None:
487 """Reject model targets nested with any other activation target."""
488 for target in model_targets:
489 target_descendants = {id(module) for module in target.module.modules()}
490 for other in all_targets:
491 if other is target or other.module is target.module:
492 continue
493 other_descendants = {id(module) for module in other.module.modules()}
494 if id(other.module) in target_descendants or id(target.module) in other_descendants:
495 raise ValueError(
496 "activation_checkpoint.selective has nested activation targets: "
497 f"{_target_description(target)} and {_target_description(other)}"
498 )
501def _validate_resolved_conflicts(plan: _ActivationPlan) -> None:
502 """Validate model-level conflicts across all resolved active targets."""
503 full_layer_indices = {layer_index for layer_index, _ in plan.full_layers}
504 full_targets = plan.full_save_targets + plan.full_swap_targets
505 for target in full_targets:
506 if target.layer_index not in full_layer_indices:
507 raise ValueError(
508 f"{target.config_path}: layer {target.layer_index}, module {target.module_path!r} "
509 "is outside activation_checkpoint.full.recompute_layer"
510 )
512 full_conflicts = {_target_key(target) for target in plan.full_save_targets} & {
513 _target_key(target) for target in plan.full_swap_targets
514 }
515 if full_conflicts:
516 layer_index, module_path = sorted(full_conflicts)[0]
517 raise ValueError(
518 "activation_checkpoint.full exclude save/swap conflict on "
519 f"layer {layer_index}, module {module_path!r}"
520 )
521 selective_conflicts = {
522 _target_key(target) for target in plan.selective_recompute_targets
523 } & {_target_key(target) for target in plan.selective_swap_targets}
524 if selective_conflicts:
525 layer_index, module_path = sorted(selective_conflicts)[0]
526 raise ValueError(
527 "activation_checkpoint.selective recompute/swap conflict on "
528 f"layer {layer_index}, module {module_path!r}"
529 )
531 if plan.mode == "hybrid":
532 selective_layers = {
533 target.layer_index
534 for target in plan.selective_recompute_targets + plan.selective_swap_targets
535 }
536 overlap = sorted(full_layer_indices & selective_layers)
537 if overlap:
538 raise ValueError(
539 "activation_checkpoint.mode=hybrid requires disjoint full and selective layers; "
540 f"overlap={overlap}"
541 )
543 _validate_nested_targets(full_targets, config_path="activation_checkpoint.full.exclude_region")
544 _validate_nested_targets(
545 plan.selective_recompute_targets + plan.selective_swap_targets,
546 config_path="activation_checkpoint.selective",
547 )
548 layer_targets = full_targets + plan.selective_recompute_targets + plan.selective_swap_targets
549 all_targets = layer_targets + plan.selective_recompute_model_targets
550 _validate_target_aliases(all_targets)
551 _validate_model_target_nesting(plan.selective_recompute_model_targets, all_targets)
554def _resolve_full_layers(
555 blocks: list[_TransformerBlockInfo],
556 full_config: Any,
557 *,
558 default_all: bool,
559) -> tuple[tuple[int, _TransformerBlockInfo], ...]:
560 """Resolve selected full layers and reject existing wrappers."""
561 if full_config is None:
562 layer_indices = range(len(blocks)) if default_all else ()
563 else:
564 layer_indices = full_config.recompute_layers
565 full_layers = []
566 for layer_index in layer_indices:
567 _validate_layer_index(
568 layer_index,
569 len(blocks),
570 config_path="activation_checkpoint.full.recompute_layer",
571 )
572 block = blocks[layer_index]
573 _raise_incompatible_wrapper(
574 _current_block(block),
575 config_path="activation_checkpoint.full.recompute_layer",
576 layer_index=layer_index,
577 module_path="<layer>",
578 module_fqn=block.fqn,
579 )
580 full_layers.append((layer_index, block))
581 return tuple(full_layers)
584def _resolve_optional_regions(
585 blocks: list[_TransformerBlockInfo],
586 config: Any,
587 attribute: str,
588 *,
589 config_path: str,
590) -> tuple[_ResolvedTarget, ...]:
591 """Resolve one region collection from an optional active config."""
592 if config is None:
593 return ()
594 return _resolve_regions(
595 blocks,
596 getattr(config, attribute),
597 config_path=config_path,
598 )
601def _resolve_activation_plan(model: nn.Module, config: Any) -> _ActivationPlan:
602 """Resolve and validate all active targets before installing any wrapper."""
603 mode = _require_active_mode(config)
604 full_config, selective_config = _resolve_mode_configs(config, mode)
606 containers = _resolve_activation_checkpoint_containers(
607 model,
608 required=_requires_layer_targets(mode, full_config, selective_config),
609 )
610 blocks = _flatten_layer_container_infos(containers)
611 for layer_index, block in enumerate(blocks):
612 logger.info("Activation checkpoint layer index=%d fqn=%s", layer_index, block.fqn)
614 plan = _ActivationPlan(
615 mode=mode,
616 full_layers=_resolve_full_layers(
617 blocks,
618 full_config,
619 default_all=mode == "full",
620 ),
621 full_save_targets=_resolve_optional_regions(
622 blocks,
623 full_config,
624 "save_regions",
625 config_path="activation_checkpoint.full.exclude_region.save",
626 ),
627 full_swap_targets=_resolve_optional_regions(
628 blocks,
629 full_config,
630 "swap_regions",
631 config_path="activation_checkpoint.full.exclude_region.swap",
632 ),
633 selective_recompute_targets=_resolve_optional_regions(
634 blocks,
635 selective_config,
636 "recompute_regions",
637 config_path="activation_checkpoint.selective.recompute",
638 ),
639 selective_recompute_model_targets=_resolve_optional_model_targets(
640 model,
641 blocks,
642 selective_config,
643 ),
644 selective_swap_targets=_resolve_optional_regions(
645 blocks,
646 selective_config,
647 "swap_regions",
648 config_path="activation_checkpoint.selective.swap",
649 ),
650 full_group_swap=bool(getattr(full_config, "group_swap", False)),
651 full_cpu_pool_mb=getattr(full_config, "cpu_pool_mb", None),
652 selective_group_swap=bool(getattr(selective_config, "group_swap", False)),
653 selective_cpu_pool_mb=getattr(selective_config, "cpu_pool_mb", None),
654 )
655 _validate_resolved_conflicts(plan)
656 return plan
659def _require_active_mode(config: Any) -> str:
660 """Return the normalized mode, rejecting missing or inactive values."""
661 mode = getattr(config, "mode", None)
662 if mode not in _ACTIVE_MODES:
663 raise ValueError(
664 "activation_checkpoint runtime requires normalized mode full, selective, or hybrid; "
665 f"got {mode!r}"
666 )
667 return mode
670def _resolve_mode_configs(config: Any, mode: str) -> tuple[Any, Any]:
671 """Select and validate the sub-configurations active for one runtime mode."""
672 full_config = getattr(config, "full", None) if mode in ("full", "hybrid") else None
673 selective_config = (
674 getattr(config, "selective", None) if mode in ("selective", "hybrid") else None
675 )
676 if mode == "hybrid" and full_config is None:
677 raise ValueError("activation_checkpoint.mode=hybrid requires activation_checkpoint.full")
678 if mode in ("selective", "hybrid") and selective_config is None:
679 raise ValueError(
680 f"activation_checkpoint.mode={mode} requires activation_checkpoint.selective"
681 )
682 return full_config, selective_config
685def _requires_layer_targets(mode: str, full_config: Any, selective_config: Any) -> bool:
686 """Return whether the active configuration needs transformer-block discovery."""
687 if mode == "full" or full_config is not None:
688 return True
689 if selective_config is None:
690 return False
691 return bool(selective_config.recompute_regions or selective_config.swap_regions)
694def _resolve_optional_model_targets(
695 model: nn.Module,
696 blocks: list[_TransformerBlockInfo],
697 selective_config: Any,
698) -> tuple[_ResolvedTarget, ...]:
699 """Resolve model-level selective targets when a selective config is active."""
700 if selective_config is None:
701 return ()
702 return _resolve_model_targets(
703 model,
704 blocks,
705 getattr(selective_config, "recompute_modules", ()),
706 config_path="activation_checkpoint.selective.recompute",
707 )
710def _snapshot_overlap_marks(model: nn.Module) -> tuple[tuple[object, bool, Any], ...]:
711 """Capture wrapper overlap marks so a failed apply can restore them."""
712 snapshots = []
713 seen = set()
714 for module in model.modules():
715 candidates = [module]
716 candidates.extend(
717 value
718 for value in vars(module).values()
719 if callable(value) and not isinstance(value, nn.Module) and hasattr(value, "__dict__")
720 )
721 for candidate in candidates:
722 if id(candidate) in seen:
723 continue
724 seen.add(id(candidate))
725 exists = hasattr(candidate, "_is_wrapped")
726 snapshots.append((candidate, exists, getattr(candidate, "_is_wrapped", None)))
727 return tuple(snapshots)
730def _restore_overlap_marks(snapshots: tuple[tuple[object, bool, Any], ...]) -> None:
731 """Restore overlap marks captured before wrapper construction."""
732 for candidate, existed, value in snapshots:
733 if existed:
734 setattr(candidate, "_is_wrapped", value)
735 elif hasattr(candidate, "_is_wrapped"):
736 delattr(candidate, "_is_wrapped")
739def _replace_target(
740 target: Any,
741 wrapped: nn.Module,
742 records: list[_ReplacementRecord],
743) -> None:
744 """Install one already-constructed wrapper and record its inverse."""
745 current = target.parent._modules.get(target.child_name) # pylint: disable=protected-access
746 if current is not target.module:
747 raise RuntimeError(
748 f"{target.config_path}: target {target.module_fqn} changed during activation wrapper apply"
749 )
750 setattr(target.parent, target.child_name, wrapped)
751 records.append(_ReplacementRecord(target.parent, target.child_name, target.module))
754def _replace_layer(
755 block_info: _TransformerBlockInfo,
756 wrapped: nn.Module,
757 records: list[_ReplacementRecord],
758) -> None:
759 """Install one full-layer wrapper and record its inverse."""
760 current = _current_block(block_info)
761 setattr(block_info.parent, block_info.child_name, wrapped)
762 records.append(_ReplacementRecord(block_info.parent, block_info.child_name, current))
765def _create_cpu_pool(cpu_pool_mb: Optional[int], *, has_targets: bool) -> Optional[PinnedMemoryPool]:
766 """Create one runtime pool only for an active swap target domain."""
767 if not has_targets or cpu_pool_mb is None:
768 return None
769 return PinnedMemoryPool(max_host_bytes=cpu_pool_mb * _MIB)
772def _dedupe_modules(modules: list[nn.Module]) -> list[nn.Module]:
773 """De-duplicate modules while preserving forward order."""
774 return list(dict.fromkeys(modules))
777def _wire_prefetch_chain(
778 model: nn.Module,
779 nodes: list[tuple[int, int, nn.Module, str]],
780) -> list[nn.Module]:
781 """Wire all active swap nodes through one ordered SwapManager flow."""
782 nodes.sort(key=lambda item: (item[0], item[1]))
783 swap_manager = SwapManager()
784 wired_modules = []
785 try:
786 for current, next_node in zip(nodes, nodes[1:]):
787 current_module, next_module = current[2], next_node[2]
788 wired_modules.extend((current_module, next_module))
789 swap_manager.set_forward_prefetch_layer(current_module, next_module)
790 logger.info("Activation swap prefetch %s -> %s", current[3], next_node[3])
791 except BaseException:
792 _teardown_wired_swap_layers(_dedupe_modules(wired_modules))
793 raise
794 wired_modules = _dedupe_modules(wired_modules)
795 if wired_modules:
796 weakref.finalize(model, _teardown_wired_swap_layers, tuple(wired_modules))
797 return wired_modules
800def _pool_description(cpu_pool_mb: Optional[int], pool: Optional[PinnedMemoryPool]) -> str:
801 """Format one pool for the activation summary log."""
802 if pool is None or cpu_pool_mb is None:
803 return "none"
804 return f"{cpu_pool_mb} MiB ({pool.max_host_bytes} bytes)"
807def _sorted_targets(targets: Sequence[_ResolvedTarget]) -> list[_ResolvedTarget]:
808 """Order replacement targets by layer index, then model registration order."""
809 return sorted(targets, key=lambda item: (item.layer_index, item.module_order))
812def _install_full_save_wrappers(
813 targets: Sequence[_ResolvedTarget],
814 replacements: list[_ReplacementRecord],
815) -> None:
816 """Wrap full-mode save targets in memory-saving-only wrappers."""
817 for target in _sorted_targets(targets):
818 wrapped = checkpoint_exclude_wrapper(target.module, swap=False)
819 _replace_target(target, wrapped, replacements)
820 logger.info(
821 "Activation wrapper=CheckpointExcludeWrapper(save) layer=%d layer_fqn=%s "
822 "module=%s module_fqn=%s pool=none",
823 target.layer_index,
824 target.layer_fqn,
825 target.module_path,
826 target.module_fqn,
827 )
830def _install_full_swap_wrappers(
831 targets: Sequence[_ResolvedTarget],
832 group_swap: bool,
833 cpu_pool: Optional[PinnedMemoryPool],
834 replacements: list[_ReplacementRecord],
835) -> None:
836 """Wrap full-mode swap targets in exclusion wrappers backed by the full pool."""
837 for target in _sorted_targets(targets):
838 wrapped = checkpoint_exclude_wrapper(
839 target.module,
840 swap=True,
841 group_swap=group_swap,
842 cpu_pool=cpu_pool,
843 )
844 _replace_target(target, wrapped, replacements)
845 logger.info(
846 "Activation wrapper=CheckpointExcludeWrapper(swap) layer=%d layer_fqn=%s "
847 "module=%s module_fqn=%s pool=full",
848 target.layer_index,
849 target.layer_fqn,
850 target.module_path,
851 target.module_fqn,
852 )
855def _install_full_layer_wrappers(
856 full_layers: Sequence[tuple[int, _TransformerBlockInfo]],
857 replacements: list[_ReplacementRecord],
858) -> dict[int, nn.Module]:
859 """Wrap full-mode transformer blocks, returning wrappers keyed by layer index."""
860 full_wrappers: dict[int, nn.Module] = {}
861 for layer_index, block_info in full_layers:
862 current_layer = _current_block(block_info)
863 wrapped = checkpoint_wrapper(current_layer)
864 _replace_layer(block_info, wrapped, replacements)
865 full_wrappers[layer_index] = wrapped
866 logger.info(
867 "Activation wrapper=CheckpointWrapper(full) layer=%d layer_fqn=%s",
868 layer_index,
869 block_info.fqn,
870 )
871 return full_wrappers
874def _install_selective_recompute_wrappers(
875 targets: Sequence[_ResolvedTarget],
876 replacements: list[_ReplacementRecord],
877) -> None:
878 """Wrap selective-mode layer-relative recompute targets."""
879 for target in _sorted_targets(targets):
880 wrapped = checkpoint_wrapper(target.module)
881 _replace_target(target, wrapped, replacements)
882 logger.info(
883 "Activation wrapper=CheckpointWrapper(selective) layer=%d layer_fqn=%s "
884 "module=%s module_fqn=%s",
885 target.layer_index,
886 target.layer_fqn,
887 target.module_path,
888 target.module_fqn,
889 )
892def _install_selective_model_wrappers(
893 targets: Sequence[_ResolvedModelTarget],
894 replacements: list[_ReplacementRecord],
895) -> None:
896 """Wrap selective-mode model-root-relative recompute targets."""
897 for target in targets:
898 wrapped = checkpoint_wrapper(target.module)
899 _replace_target(target, wrapped, replacements)
900 logger.info(
901 "Activation wrapper=CheckpointWrapper(selective) scope=model "
902 "module=%s module_fqn=%s",
903 target.module_path,
904 target.module_fqn,
905 )
908def _install_selective_swap_wrappers(
909 targets: Sequence[_ResolvedTarget],
910 group_swap: bool,
911 cpu_pool: Optional[PinnedMemoryPool],
912 replacements: list[_ReplacementRecord],
913) -> list[tuple[_ResolvedTarget, nn.Module]]:
914 """Wrap selective-mode swap targets, returning the installed wrapper pairs."""
915 swap_wrappers: list[tuple[_ResolvedTarget, nn.Module]] = []
916 for target in _sorted_targets(targets):
917 wrapped = swap_wrapper(
918 target.module,
919 group_swap=group_swap,
920 cpu_pool=cpu_pool,
921 )
922 _replace_target(target, wrapped, replacements)
923 swap_wrappers.append((target, wrapped))
924 logger.info(
925 "Activation wrapper=SwapWrapper layer=%d layer_fqn=%s module=%s "
926 "module_fqn=%s pool=selective",
927 target.layer_index,
928 target.layer_fqn,
929 target.module_path,
930 target.module_fqn,
931 )
932 return swap_wrappers
935def _collect_prefetch_nodes(
936 plan: _ActivationPlan,
937 full_wrappers: dict[int, nn.Module],
938 selective_swap_wrappers: Sequence[tuple[_ResolvedTarget, nn.Module]],
939) -> list[tuple[int, int, nn.Module, str]]:
940 """Collect every swap node in layer order for one prefetch chain."""
941 full_swap_layers = {target.layer_index for target in plan.full_swap_targets}
942 prefetch_nodes = [
943 (layer_index, -1, full_wrappers[layer_index], block_info.fqn)
944 for layer_index, block_info in plan.full_layers
945 if layer_index in full_swap_layers
946 ]
947 prefetch_nodes.extend(
948 (target.layer_index, target.module_order, wrapper, target.module_fqn)
949 for target, wrapper in selective_swap_wrappers
950 )
951 return prefetch_nodes
954def _apply_activation_plan(model: nn.Module, plan: _ActivationPlan) -> nn.Module:
955 """Create pools, install wrappers, and register one prefetch chain."""
956 full_pool = _create_cpu_pool(
957 plan.full_cpu_pool_mb,
958 has_targets=bool(plan.full_swap_targets),
959 )
960 selective_pool = _create_cpu_pool(
961 plan.selective_cpu_pool_mb,
962 has_targets=bool(plan.selective_swap_targets),
963 )
964 overlap_marks = _snapshot_overlap_marks(model)
965 replacements: list[_ReplacementRecord] = []
966 wired_modules: list[nn.Module] = []
968 try:
969 _install_full_save_wrappers(plan.full_save_targets, replacements)
970 _install_full_swap_wrappers(
971 plan.full_swap_targets,
972 plan.full_group_swap,
973 full_pool,
974 replacements,
975 )
976 full_wrappers = _install_full_layer_wrappers(plan.full_layers, replacements)
977 _install_selective_recompute_wrappers(plan.selective_recompute_targets, replacements)
978 _install_selective_model_wrappers(plan.selective_recompute_model_targets, replacements)
979 selective_swap_wrappers = _install_selective_swap_wrappers(
980 plan.selective_swap_targets,
981 plan.selective_group_swap,
982 selective_pool,
983 replacements,
984 )
985 prefetch_nodes = _collect_prefetch_nodes(plan, full_wrappers, selective_swap_wrappers)
986 wired_modules = _wire_prefetch_chain(model, prefetch_nodes)
987 except BaseException:
988 if wired_modules:
989 _teardown_wired_swap_layers(wired_modules)
990 for record in reversed(replacements):
991 setattr(record.parent, record.child_name, record.original)
992 _restore_overlap_marks(overlap_marks)
993 raise
995 logger.info(
996 "Activation checkpoint mode=%s: full_layers=%s, full_save_regions=%d, "
997 "full_swap_regions=%d, full_pool=%s; selective_recompute_regions=%d, "
998 "selective_recompute_modules=%d, selective_swap_regions=%d, selective_pool=%s",
999 plan.mode,
1000 [layer_index for layer_index, _ in plan.full_layers],
1001 len(plan.full_save_targets),
1002 len(plan.full_swap_targets),
1003 _pool_description(plan.full_cpu_pool_mb, full_pool),
1004 len(plan.selective_recompute_targets),
1005 len(plan.selective_recompute_model_targets),
1006 len(plan.selective_swap_targets),
1007 _pool_description(plan.selective_cpu_pool_mb, selective_pool),
1008 )
1009 return model
1012def _apply_activation_checkpointing(
1013 model: nn.Module,
1014 activation_checkpoint: Optional[Any],
1015 enable_compile: bool = False,
1016) -> nn.Module:
1017 """Apply one normalized activation-checkpoint configuration atomically.
1019 ``None`` and ``mode=off`` are no-ops. Full mode checkpoints every
1020 discovered transformer layer when no ``full`` sub-configuration is given.
1021 Selective and hybrid modes retain their explicit module-target semantics.
1022 Legacy string modes are intentionally unsupported.
1023 """
1024 if activation_checkpoint is None or getattr(activation_checkpoint, "mode", None) == "off":
1025 return model
1026 if isinstance(activation_checkpoint, str):
1027 raise ValueError(
1028 "legacy activation_checkpoint string modes are unsupported; pass the normalized "
1029 "activation_checkpoint configuration object"
1030 )
1031 _require_active_mode(activation_checkpoint)
1032 if enable_compile:
1033 raise ValueError(
1034 "activation_checkpoint modes full, selective, and hybrid are not supported with torch.compile"
1035 )
1036 plan = _resolve_activation_plan(model, activation_checkpoint)
1037 disable_native_checkpointing = getattr(model, "gradient_checkpointing_disable", None)
1038 if callable(disable_native_checkpointing):
1039 disable_native_checkpointing()
1040 return _apply_activation_plan(model, plan)
1043__all__ = [
1044 "_apply_activation_checkpointing",
1045 "_find_transformer_block_modules",
1046 "_find_transformer_layer_container_infos",
1047 "_flatten_layer_container_infos",
1048]