Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / compile / passes / cpu_offload.py: 92%
449 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# Portions copyright (c) Meta Platforms, Inc. and affiliates.
2# Licensed under the BSD-3-Clause license; see
3# Third_Party_Open_Source_Software_Notice.
4# Copyright 2026 Huawei Technologies Co., Ltd
5#
6# Licensed under the Apache License, Version 2.0 (the "License");
7# you may not use this file except in compliance with the License.
8# You may obtain a copy of the License at
9#
10# http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS,
14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15# See the License for the specific language governing permissions and
16# limitations under the License.
17# ============================================================================
18"""Static-graph CPU offload - host-side activation swap.
20Graph-mode counterpart of the dynamic ``activation_swap="attention"`` setting
21(``hyper_parallel.distributed.attention_swap``). It reuses the same public
22configuration surface - the Trainer's top-level ``activation_swap`` field -
23and is driven by ``PassConfig.activation_swap``. The implementation follows
24torchtitan graph_trainer's ``cpu_offload.py``:
261. Select forward activations produced inside ``self_attn`` modules that the
27 backward half consumes (directly or through a chain of aliases), are large
28 enough to amortize a transfer, are contiguous and independently owned, are
29 never written in place, and fit the host-memory budget (largest-first).
30 Aliases are grouped by real storage identity, so replay ops without schema
31 ``alias_info`` (for example ``aten::_unsafe_view``) share the owner's single
32 offload and lifetime. In-place writes are detected from the schema (including
33 ops like ``aten::_foreach_add_`` that return no tensor), so a storage that
34 changes after an earlier offload is never moved to host.
352. Insert the asynchronous transfer after each producer:
37 ``cpu = ao.offload(gpu)`` is launched right after the producer, and
38 ``cpu = ao.wait_tensor(cpu, keepalive=gpu, last_use_of_storage=...)`` is
39 placed after the last forward read of the whole storage group. The D2H copy
40 therefore overlaps the remaining forward compute, and the GPU storage is
41 released as soon as the wait runs.
423. Insert ``gpu = ao.reload(cpu, device)`` plus a ``wait_tensor`` before the
43 first backward consumer, redirecting every backward consumer (including
44 consumers reached through replayed aliases) to the reloaded tensor. Reloads
45 may be prefetched a few attention regions
46 earlier to overlap H2D with preceding backward compute.
48The pass runs before ``FSDPPass``: it only rewrites saved forward values, so
49FSDP sees the resulting backward consumers when it inserts parameter
50re-gathers. Attention swap is incompatible with activation checkpointing (the
51dynamic rule is enforced in ``PassConfig``), so no recompute interacts with it.
53Only ``activation_swap="attention"`` is enabled because that is the only mode
54the dynamic attention-swap path exposes. Models without ``self_attn`` modules
55raise the same error as the eager path. Symbolic (dynamic-shape) activations are
56supported: selection heuristics (the 1 MiB threshold and the host budget) read
57the trace-time size hints without specializing the graph, and the transfer ops
58carry only the device so runtime shapes/strides come from the offloaded tensor.
59Unbacked (data-dependent) sizes have no hint and are skipped.
60"""
62from __future__ import annotations
64__all__ = ["CpuOffloadPass"]
66import contextlib
67import logging
68from dataclasses import dataclass
69from typing import Any, Dict, List, Optional, Tuple
71import torch
72from torch import fx
74from .base import GraphPass
75from .overlap.utils import is_view
76from ..pass_config import PassConfig
78try: # Register the upstream ``ao::`` custom ops on import.
79 import torch._functorch._activation_offloading.offload_ops # noqa: F401
81 _AO_OFFLOAD = torch.ops.ao.offload.default
82 _AO_RELOAD = torch.ops.ao.reload.default
83 _AO_WAIT = torch.ops.ao.wait_tensor.default
84 _AO_OPS = frozenset((_AO_OFFLOAD, _AO_RELOAD, _AO_WAIT))
85 _AO_AVAILABLE = True
86except (ImportError, AttributeError):
87 _AO_OFFLOAD = _AO_RELOAD = _AO_WAIT = None
88 _AO_OPS = frozenset()
89 _AO_AVAILABLE = False
91_LOG = logging.getLogger(__name__)
93# Match the dynamic attention-swap policy: only independently-owned tensors of
94# at least 1 MiB amortize the transfer; smaller views/activations stay on device.
95_MIN_OFFLOAD_BYTES = 1024 * 1024
97_COLLECTIVE_NAMESPACES = frozenset(("_c10d_functional", "_c10d_functional_autograd"))
100def _is_backward(node: fx.Node) -> bool:
101 """Whether ``node`` belongs to the joint graph's backward half."""
102 return bool(node.meta.get("autograd_backward", False))
105def _stack_fqns(node: fx.Node) -> List[str]:
106 """Module FQNs on ``node``'s ``nn_module_stack``, innermost first."""
107 stack = node.meta.get("nn_module_stack") or {}
108 return [fqn for fqn, _ in reversed(list(stack.values()))]
111def _attention_roots(
112 graph_module: fx.GraphModule, model: Optional[torch.nn.Module]
113) -> frozenset:
114 """Discover the ``self_attn`` module FQNs that define the offload scope.
116 The eager attention-swap discovery only accepts modules literally named
117 ``self_attn``; graph mode mirrors that contract and additionally accepts
118 roots recorded in the traced module stack when no live model is supplied.
119 """
120 roots = set()
121 if model is not None:
122 roots.update(
123 name
124 for name, _ in model.named_modules()
125 if name.rsplit(".", 1)[-1] == "self_attn"
126 )
127 for node in graph_module.graph.nodes:
128 for fqn in _stack_fqns(node):
129 if fqn.rsplit(".", 1)[-1] == "self_attn":
130 roots.add(fqn)
131 return frozenset(roots)
134def _in_attention_scope(node: fx.Node, roots: frozenset) -> bool:
135 """Whether a node was produced inside one of the attention roots."""
136 if not roots:
137 return False
138 for fqn in _stack_fqns(node):
139 if fqn.rsplit(".", 1)[-1] == "self_attn":
140 return True
141 if any(fqn == root or fqn.startswith(f"{root}.") for root in roots):
142 return True
143 return False
146def _attention_root_of(node: fx.Node, roots: frozenset) -> Optional[str]:
147 """Return the innermost attention root containing ``node`` (or ``None``)."""
148 for fqn in _stack_fqns(node):
149 for root in roots:
150 if fqn == root or fqn.startswith(f"{root}."):
151 return root
152 return None
155def _is_collective_or_wait(node: fx.Node) -> bool:
156 """Whether the node is a functional collective launch or its wait.
158 Both the launch namespace and the autograd-compat namespace are covered so
159 a collective result is never moved to host.
160 """
161 namespace = getattr(node.target, "namespace", None)
162 return namespace in _COLLECTIVE_NAMESPACES
165def _is_dtensor(value: torch.Tensor) -> bool:
166 """Recognize DTensor-like values that the ``ao::`` ops cannot transfer."""
167 return hasattr(value, "device_mesh") or hasattr(value, "to_local")
170def _hint_to_int(value: Any) -> Optional[int]:
171 """Convert an ``int``/``SymInt`` to a plain int without installing a guard.
173 Sizes only feed selection heuristics (the 1 MiB threshold and the host
174 budget), so a symbolic value's trace-time hint is enough. ``int(SymInt)``
175 would specialize the graph and add a shape guard; unbacked (data-dependent)
176 symbols have no hint and yield ``None`` so the candidate is skipped.
177 """
178 try:
179 if isinstance(value, torch.SymInt):
180 value = value.node.hint
181 return int(value)
182 except Exception: # pylint: disable=broad-exception-caught
183 return None
186def _tensor_bytes(value: torch.Tensor) -> Optional[int]:
187 """Return a hinted byte count, or ``None`` for unsupported values."""
188 try:
189 nbytes = value.nelement() * value.element_size()
190 except Exception: # pylint: disable=broad-exception-caught
191 return None
192 return _hint_to_int(nbytes)
195def _is_contiguous(value: torch.Tensor) -> bool:
196 """Check contiguity without tripping over symbolic fake tensors."""
197 try:
198 return bool(value.is_contiguous())
199 except Exception: # pylint: disable=broad-exception-caught
200 return False
203def _storage_key(value: torch.Tensor) -> Optional[int]:
204 """Return a stable identity for the tensor's storage, or ``None`` if unknown.
206 Aliasing is a storage property, not an operator property: replay-based view
207 ops carry no schema ``alias_info`` (``aten::_unsafe_view``), and some
208 schema-tagged views can still be full-size. FakeTensor preserves the
209 underlying storage, so grouping by the real storage (``_cdata``) detects
210 aliases that ``is_view`` misses without enumerating every op.
212 ``None`` means the storage identity cannot be proven. The Python object
213 ``id()`` is deliberately not used as a fallback: it is not stable across
214 ``untyped_storage()`` wrappers, and a mismatched identity could let an
215 alias or an in-place write slip through. Returning ``None`` instead makes
216 callers skip the candidate.
217 """
218 try:
219 storage = value.untyped_storage()
220 except Exception: # pylint: disable=broad-exception-caught
221 return None
222 cdata = getattr(storage, "_cdata", None)
223 return int(cdata) if cdata else None
226def _shares_storage(left: fx.Node, right: fx.Node) -> bool:
227 """Whether two nodes' values refer to the same storage (unknown => False)."""
228 left_value = left.meta.get("val")
229 right_value = right.meta.get("val")
230 if not isinstance(left_value, torch.Tensor) or not isinstance(
231 right_value, torch.Tensor
232 ):
233 return False
234 left_key = _storage_key(left_value)
235 return left_key is not None and left_key == _storage_key(right_value)
238def _is_alias(user: fx.Node, producer: fx.Node) -> bool:
239 """Whether ``user`` aliases ``producer``'s storage (schema view or shared)."""
240 return is_view(user) or _shares_storage(user, producer)
243def _is_mutable(node: fx.Node) -> bool:
244 """Whether the node targets an in-place/mutating op."""
245 schema = getattr(node.target, "_schema", None)
246 return schema is not None and schema.is_mutable
249def _iter_nodes(value: Any) -> List[fx.Node]:
250 """Collect the ``fx.Node`` leaves inside an argument (``Tensor[]`` etc.)."""
251 nodes: List[fx.Node] = []
252 fx.map_arg(value, nodes.append)
253 return nodes
256def _storage_keys(nodes: List[fx.Node]) -> List[int]:
257 """Resolvable storage keys of the tensor-valued ``nodes``."""
258 keys: List[int] = []
259 for node in nodes:
260 value = node.meta.get("val")
261 if isinstance(value, torch.Tensor):
262 key = _storage_key(value)
263 if key is not None:
264 keys.append(key)
265 return keys
268def _tensor_argument_keys(node: fx.Node) -> List[int]:
269 """Storage keys of every tensor-valued argument to ``node``.
271 Conservative fallback for nodes whose write target cannot be pinned down:
272 skipping an offload only costs memory, while missing a write corrupts the
273 backward reload.
274 """
275 return _storage_keys(_iter_nodes((node.args, node.kwargs)))
278def _written_storage_keys(node: fx.Node) -> List[int]:
279 """Storage keys that a mutating op writes through its arguments.
281 Schema ``alias_info.is_write`` marks the arguments an op modifies in place.
282 A node's output value is not enough to detect this: ``aten._foreach_add_``
283 returns ``()`` but still writes its ``Tensor(a!)[]`` input, so grouping only
284 returned tensors misses the write and could offload a value that the forward
285 changes afterwards (making the backward reload stale). Written arguments are
286 resolved by name first (keyword form) and then by positional index;
287 ``fx.map_arg`` walks ``Tensor[]`` and nested containers to the nodes.
289 Two conservative fallbacks keep this sound when the exact write target is
290 unknowable:
292 * a node without a schema (``call_method`` / ``call_module`` / plain
293 callable) may mutate any argument, and
294 * a mutable schema whose write argument cannot be resolved (vararg layout,
295 an omitted positional default, or a missing ``meta['val']``).
297 Both return every tensor argument's storage instead of an empty list, so an
298 unprovable write never lets a candidate be offloaded.
299 """
300 schema = getattr(node.target, "_schema", None)
301 if schema is None:
302 return _tensor_argument_keys(node)
303 if not schema.is_mutable:
304 return []
306 keys: List[int] = []
307 resolved = False
308 unresolved = False
309 position = 0
310 for argument in schema.arguments:
311 if argument.kwarg_only:
312 index = None
313 else:
314 index = position
315 position += 1
316 alias_info = argument.alias_info
317 if alias_info is None or not alias_info.is_write:
318 continue
319 if argument.name in node.kwargs:
320 value = node.kwargs[argument.name]
321 elif index is not None and index < len(node.args):
322 value = node.args[index]
323 else:
324 unresolved = True
325 continue
326 written = _iter_nodes(value)
327 if not written:
328 continue
329 resolved = True
330 written_keys = _storage_keys(written)
331 if not written_keys:
332 unresolved = True
333 keys.extend(written_keys)
334 if unresolved or not resolved:
335 return _tensor_argument_keys(node)
336 return keys
339def _group_storage_members(graph: fx.Graph) -> Dict[int, List[fx.Node]]:
340 """Group tensor-valued nodes by the real identity of their storage."""
341 members: Dict[int, List[fx.Node]] = {}
342 for node in graph.nodes:
343 if node.op not in ("call_function", "placeholder", "get_attr"):
344 continue
345 value = node.meta.get("val")
346 if not isinstance(value, torch.Tensor):
347 continue
348 key = _storage_key(value)
349 if key is not None:
350 members.setdefault(key, []).append(node)
351 return members
354def _write_unsafe_keys(graph: fx.Graph) -> set:
355 """Storage keys written in place anywhere in the graph.
357 Includes mutations whose return is not a tensor (``_foreach_add_`` returns
358 ``()``): such a write still changes a storage that may already have been
359 offloaded. ``call_method`` / ``call_module`` nodes carry no schema; their
360 tensor arguments are marked conservatively because an unseen in-place write
361 would make the backward reload stale.
362 """
363 unsafe: set = set()
364 for node in graph.nodes:
365 if node.op in ("call_function", "call_method", "call_module"):
366 unsafe.update(_written_storage_keys(node))
367 return unsafe
370def _group_is_safe(nodes: List[fx.Node]) -> bool:
371 """Whether a storage group has no external, mutating, or output sharer."""
372 if any(node.op != "call_function" for node in nodes):
373 return False
374 if any(_is_mutable(node) for node in nodes):
375 return False
376 if any(user.op == "output" for node in nodes for user in node.users):
377 return False
378 return True
381@dataclass(frozen=True)
382class _StorageIndex:
383 """Real-storage groups used to prove a candidate can be offloaded safely.
385 A storage may be offloaded only when it is owned by a single forward
386 ``call_function`` node (the ``owner``), no other node in the graph shares it
387 through an external (placeholder/get_attr) or mutating op, and it is not a
388 graph output. Writes are detected from the schema, not only from returned
389 tensors, so an in-place op with no tensor return still poisons its input
390 storage. Groups that cannot be proven safe are marked ``unsafe``.
391 """
393 owner: Dict[int, fx.Node]
394 unsafe: frozenset
396 @classmethod
397 def build(cls, graph: fx.Graph, order: Dict[fx.Node, int]) -> "_StorageIndex":
398 """Group tensor-valued nodes by storage and validate each group."""
399 members = _group_storage_members(graph)
400 unsafe = _write_unsafe_keys(graph)
401 owner: Dict[int, fx.Node] = {}
402 for key, nodes in members.items():
403 if key in unsafe:
404 continue
405 if not _group_is_safe(nodes):
406 unsafe.add(key)
407 continue
408 owner[key] = min(nodes, key=lambda node: order[node])
409 return cls(owner=owner, unsafe=frozenset(unsafe))
412def _can_offload(node: fx.Node, storage: _StorageIndex) -> bool:
413 """Whether a forward node's output is a profitable, safely-owned candidate.
415 Views are skipped because they alias their base, so offloading them frees
416 nothing and, for ``getitem`` of a multi-output op, could release storage a
417 sibling still uses. Shared storage is detected by real identity: only the
418 group owner is eligible, and ``unsafe`` groups (external or mutating
419 aliases) are left on device.
420 """
421 if node.op != "call_function":
422 return False
423 if node.target in _AO_OPS:
424 return False
425 if is_view(node):
426 return False
427 if _is_collective_or_wait(node):
428 return False
429 value = node.meta.get("val")
430 if not isinstance(value, torch.Tensor) or _is_dtensor(value):
431 return False
432 if value.dim() < 2:
433 return False
434 if not _is_contiguous(value):
435 return False
436 nbytes = _tensor_bytes(value)
437 if nbytes is None or nbytes < _MIN_OFFLOAD_BYTES:
438 return False
439 # Offload one storage at a time. Only the group owner (the node that
440 # allocated the storage) is eligible; aliases are handled by the owner's
441 # view chain, and external/mutating sharers mark the group unsafe.
442 key = _storage_key(value)
443 if key is None or key in storage.unsafe:
444 return False
445 if storage.owner.get(key) is not node:
446 return False
447 return True
450def _view_chain(
451 node: fx.Node,
452) -> Tuple[List[fx.Node], List[fx.Node], List[Tuple[fx.Node, fx.Node]]]:
453 """Collect forward aliases of ``node`` and their backward consumers.
455 Aliases are found by real storage identity as well as schema views, so
456 replay ops without ``alias_info`` (``aten::_unsafe_view``) join the chain.
458 Returns:
459 ``(lifetime_views, replay_views, view_bwd_redirects)``. ``lifetime_views``
460 are every forward alias view (needed to find the producer's true last
461 forward use, so the storage is not released while a forward-only view is
462 still live). ``replay_views`` is the subset that must be rebuilt on top
463 of the reloaded tensor because it (or a descendant view) is read in
464 backward. Each redirect pair ``(view_node, backward_user)`` must be
465 repointed after replay.
466 """
467 children: Dict[fx.Node, List[fx.Node]] = {}
468 backward_users: Dict[fx.Node, List[fx.Node]] = {}
469 lifetime_views: List[fx.Node] = []
470 visited: set = set()
472 def collect(current: fx.Node) -> None:
473 """Walk alias users and record backward readers."""
474 for user in current.users:
475 if user.op != "call_function":
476 continue
477 if _is_backward(user):
478 backward_users.setdefault(current, []).append(user)
479 elif _is_alias(user, current) and user not in visited:
480 visited.add(user)
481 children.setdefault(current, []).append(user)
482 lifetime_views.append(user)
483 collect(user)
485 collect(node)
487 needed: set = set()
488 memo: Dict[fx.Node, bool] = {}
490 def is_read_in_backward(current: fx.Node) -> bool:
491 """Whether a view subtree has any backward reader (memoized)."""
492 cached = memo.get(current)
493 if cached is not None:
494 return cached
495 needed_here = bool(backward_users.get(current))
496 for child in children.get(current, ()):
497 if is_read_in_backward(child):
498 needed_here = True
499 memo[current] = needed_here
500 if needed_here and current is not node:
501 needed.add(current)
502 return needed_here
504 is_read_in_backward(node)
505 replay_views = [view for view in lifetime_views if view in needed]
506 redirects = [
507 (view, user) for view in replay_views for user in backward_users.get(view, ())
508 ]
509 return lifetime_views, replay_views, redirects
512@dataclass
513class _OffloadInfo:
514 """Resolved backward consumers and forward lifetime of one candidate."""
516 node: fx.Node
517 direct_bwd_users: List[fx.Node]
518 lifetime_views: List[fx.Node]
519 replay_views: List[fx.Node]
520 view_bwd_redirects: List[Tuple[fx.Node, fx.Node]]
521 first_bwd_consumer: fx.Node
522 last_forward_use: fx.Node
523 last_use_arg: fx.Node
525 @property
526 def all_bwd_users(self) -> List[fx.Node]:
527 """Every backward consumer, direct or reached through a view."""
528 return self.direct_bwd_users + [user for _, user in self.view_bwd_redirects]
531def _collect_offload_info(
532 node: fx.Node, order: Dict[fx.Node, int]
533) -> Optional[_OffloadInfo]:
534 """Resolve one candidate's backward users and its last forward use."""
535 direct_bwd_users = [user for user in node.users if _is_backward(user)]
536 lifetime_views, replay_views, view_bwd_redirects = _view_chain(node)
537 all_bwd_users = direct_bwd_users + [user for _, user in view_bwd_redirects]
538 if not all_bwd_users:
539 return None
541 last_forward_use = node
542 last_index = order[node]
543 for chain_node in (node, *lifetime_views):
544 for user in chain_node.users:
545 if user.op != "call_function" or _is_backward(user):
546 continue
547 user_index = order.get(user)
548 if user_index is not None and user_index > last_index:
549 last_forward_use = user
550 last_index = user_index
552 if last_forward_use is node:
553 last_use_arg: fx.Node = node
554 elif isinstance(last_forward_use.meta.get("val"), torch.Tensor):
555 last_use_arg = last_forward_use
556 else:
557 # The forward ``ao.wait_tensor`` frees the producer's storage, so it must
558 # carry a data-dependency edge on the last forward consumer
559 # (``last_use_of_storage``). A tuple/list-returning consumer (split,
560 # chunk, max, ...) has no single tensor value to pin that edge; skip the
561 # candidate rather than risk a reordering pass hoisting the storage free
562 # before its last forward read.
563 return None
565 return _OffloadInfo(
566 node=node,
567 direct_bwd_users=direct_bwd_users,
568 lifetime_views=lifetime_views,
569 replay_views=replay_views,
570 view_bwd_redirects=view_bwd_redirects,
571 first_bwd_consumer=min(all_bwd_users, key=lambda item: order[item]),
572 last_forward_use=last_forward_use,
573 last_use_arg=last_use_arg,
574 )
577def _collect_candidates(
578 graph_module: fx.GraphModule,
579 roots: frozenset,
580 order: Dict[fx.Node, int],
581) -> List[Tuple[fx.Node, int, _OffloadInfo]]:
582 """Collect in-scope forward activations that can be offloaded."""
583 storage = _StorageIndex.build(graph_module.graph, order)
584 candidates: List[Tuple[fx.Node, int, _OffloadInfo]] = []
585 for node in list(graph_module.graph.nodes):
586 if _is_backward(node):
587 continue
588 if not _in_attention_scope(node, roots) or not _can_offload(node, storage):
589 continue
590 info = _collect_offload_info(node, order)
591 if info is None:
592 continue
593 nbytes = _tensor_bytes(node.meta["val"])
594 if nbytes is None:
595 continue
596 candidates.append((node, nbytes, info))
597 return candidates
600def _select_within_budget(
601 candidates: List[Tuple[fx.Node, int, _OffloadInfo]],
602 budget_bytes: float,
603) -> Tuple[List[_OffloadInfo], int]:
604 """Pick largest-first until the host budget is exhausted (0 means all)."""
605 candidates.sort(key=lambda item: item[1], reverse=True)
606 selected: List[_OffloadInfo] = []
607 total_bytes = 0
608 for _, nbytes, info in candidates:
609 if 0 < budget_bytes < total_bytes + nbytes:
610 continue
611 selected.append(info)
612 total_bytes += nbytes
613 return selected, total_bytes
616def _copy_meta(source: fx.Node) -> Dict[str, Any]:
617 """Copy node metadata suitable for an inserted offload-chain node."""
618 return {
619 key: value
620 for key, value in source.meta.items()
621 if key not in ("val", "recompute")
622 }
625def _insert_forward_offload(
626 graph_module: fx.GraphModule,
627 info: _OffloadInfo,
628) -> fx.Node:
629 """Insert ``ao.offload`` and the deferred forward ``ao.wait_tensor``.
631 Returns:
632 The wait node whose (CPU) result is the reload source.
633 """
634 graph = graph_module.graph
635 node = info.node
636 value = node.meta["val"]
637 src_meta = _copy_meta(node)
639 with graph.inserting_after(node):
640 offload = graph.call_function(_AO_OFFLOAD, args=(node,))
641 offload.meta.update(src_meta)
642 offload.meta["val"] = value.to(torch.device("cpu"))
644 if info.last_forward_use is node:
645 anchor = offload
646 else:
647 anchor = info.last_forward_use
649 with graph.inserting_after(anchor):
650 wait = graph.call_function(
651 _AO_WAIT,
652 args=(offload, node, info.last_use_arg),
653 )
654 wait.meta.update(src_meta)
655 wait.meta["val"] = offload.meta["val"]
656 wait.meta["autograd_backward"] = False
657 return wait
660def _insert_backward_reload(
661 graph_module: fx.GraphModule,
662 info: _OffloadInfo,
663 wait_offload: fx.Node,
664 order: Dict[fx.Node, int],
665) -> fx.Node:
666 """Insert ``ao.reload`` + ``ao.wait_tensor`` and redirect backward readers."""
667 graph = graph_module.graph
668 node = info.node
669 value = node.meta["val"]
670 src_meta = _copy_meta(node)
671 first_bwd = info.first_bwd_consumer
673 with graph.inserting_before(first_bwd):
674 # Candidates are contiguous, so the offloaded host tensor already carries
675 # the runtime shape and contiguous stride. Omitting the explicit
676 # size/stride keeps symbolic values out of the graph arguments: baking a
677 # ``SymInt`` here would render an undefined symbol in the generated
678 # forward (dynamic shapes).
679 reload = graph.call_function(
680 _AO_RELOAD,
681 args=(wait_offload, value.device, None, None),
682 )
683 reload.meta.update(src_meta)
684 reload.meta["val"] = value
685 reload.meta["autograd_backward"] = True
687 with graph.inserting_before(first_bwd):
688 wait = graph.call_function(_AO_WAIT, args=(reload, wait_offload))
689 wait.meta.update(src_meta)
690 wait.meta["val"] = value
691 wait.meta["autograd_backward"] = True
693 for user in info.direct_bwd_users:
694 user.replace_input_with(node, wait)
696 if info.replay_views:
697 replay_map: Dict[fx.Node, fx.Node] = {node: wait}
698 for view_node in sorted(info.replay_views, key=lambda item: order[item]):
699 new_args = fx.map_arg(
700 view_node.args,
701 lambda arg: (
702 replay_map.get(arg, arg) if isinstance(arg, fx.Node) else arg
703 ),
704 )
705 new_kwargs = fx.map_arg(
706 view_node.kwargs,
707 lambda arg: (
708 replay_map.get(arg, arg) if isinstance(arg, fx.Node) else arg
709 ),
710 )
711 with graph.inserting_before(first_bwd):
712 replayed = graph.call_function(
713 view_node.target, args=new_args, kwargs=new_kwargs
714 )
715 replayed.meta.update(
716 {k: v for k, v in view_node.meta.items() if k != "recompute"}
717 )
718 replayed.meta["autograd_backward"] = True
719 replay_map[view_node] = replayed
720 for consumed, user in info.view_bwd_redirects:
721 replayed = replay_map.get(consumed)
722 if replayed is not None:
723 user.replace_input_with(consumed, replayed)
724 return reload
727def _region_anchors(graph_module: fx.GraphModule, roots: frozenset) -> List[fx.Node]:
728 """Return the first backward node of each contiguous attention region."""
729 anchors: List[fx.Node] = []
730 previous_root: Optional[str] = None
731 for node in graph_module.graph.nodes:
732 if (
733 node.op != "call_function"
734 or not _is_backward(node)
735 or node.target in _AO_OPS
736 ):
737 continue
738 root = _attention_root_of(node, roots)
739 if root is not None and root != previous_root:
740 anchors.append(node)
741 previous_root = root
742 return anchors
745def _anchor_positions(anchors: List[fx.Node], roots: frozenset) -> Dict[str, List[int]]:
746 """Map each attention root to its ordered region-anchor indices."""
747 positions: Dict[str, List[int]] = {}
748 for index, anchor in enumerate(anchors):
749 root = _attention_root_of(anchor, roots)
750 if root is not None:
751 positions.setdefault(root, []).append(index)
752 return positions
755def _reload_nodes(graph: fx.Graph) -> List[fx.Node]:
756 """Return every backward ``ao.reload`` node in graph order."""
757 return [
758 node
759 for node in graph.nodes
760 if node.op == "call_function"
761 and node.target is _AO_RELOAD
762 and _is_backward(node)
763 ]
766def _move_reload(
767 reload_node: fx.Node,
768 roots: frozenset,
769 anchors: List[fx.Node],
770 anchor_positions: Dict[str, List[int]],
771 order: Dict[fx.Node, int],
772 n_regions: int,
773) -> bool:
774 """Move one reload earlier by ``n_regions`` regions when possible."""
775 root = _attention_root_of(reload_node, roots)
776 positions = anchor_positions.get(root) if root is not None else None
777 if not positions:
778 return False
779 reload_index = order[reload_node]
780 # Latest occurrence of this root at or before the reload is its own
781 # region when a module is reused across blocks; otherwise fall back to
782 # the first occurrence (reload inserted before the region's first node).
783 earlier = [pos for pos in positions if order[anchors[pos]] <= reload_index]
784 region_index = earlier[-1] if earlier else positions[0]
785 anchor = anchors[max(0, region_index - n_regions)]
786 if order[anchor] >= reload_index:
787 return False
788 anchor.prepend(reload_node)
789 return True
792def _prefetch_reloads(
793 graph_module: fx.GraphModule,
794 n_regions: int,
795 roots: frozenset,
796) -> int:
797 """Move backward reloads ``n_regions`` attention regions earlier.
799 Regions are located by graph position rather than by root name so a
800 ``self_attn`` module that appears in several blocks (same FQN, or tied
801 weights) still maps each reload to the region it actually belongs to.
802 """
803 if n_regions <= 0 or not roots:
804 return 0
806 order = {node: index for index, node in enumerate(graph_module.graph.nodes)}
808 # First backward node of each contiguous attention region. Tracking the
809 # previous node's root (including ``None`` gaps) re-opens a region when the
810 # same root resumes after out-of-scope backward work.
811 anchors = _region_anchors(graph_module, roots)
812 if not anchors:
813 return 0
815 anchor_positions = _anchor_positions(anchors, roots)
816 moved = 0
817 for reload_node in _reload_nodes(graph_module.graph):
818 if _move_reload(
819 reload_node, roots, anchors, anchor_positions, order, n_regions
820 ):
821 moved += 1
822 return moved
825def _graph_shape_env(graph_module: fx.GraphModule):
826 """Return the ``ShapeEnv`` backing the graph's fake tensors, if any."""
827 for node in graph_module.graph.nodes:
828 fake_mode = getattr(node.meta.get("val"), "fake_mode", None)
829 shape_env = getattr(fake_mode, "shape_env", None)
830 if shape_env is not None:
831 return shape_env
832 return None
835class CpuOffloadPass(GraphPass):
836 """Offload saved attention activations to host memory.
838 Configure through ``PassConfig.activation_swap`` (reusing the dynamic
839 Trainer field) and the graph-only ``offload_budget_gb`` /
840 ``offload_prefetch_n_layers`` knobs. The pass is a no-op unless
841 ``activation_swap == "attention"``.
842 """
844 name = "cpu_offload"
846 def run(
847 self,
848 graph_module: fx.GraphModule,
849 pass_config: PassConfig,
850 **kwargs: Any,
851 ) -> fx.GraphModule:
852 """Insert async host offload/reload around saved attention activations.
854 Args:
855 graph_module: The joint forward+backward FX graph.
856 pass_config: Parallel configuration. ``activation_swap`` enables
857 the pass and ``offload_budget_gb`` /
858 ``offload_prefetch_n_layers`` tune it.
859 **kwargs: ``model`` is used to discover the ``self_attn`` modules
860 (the graph's module stack is the fallback).
862 Returns:
863 The transformed graph module.
865 Raises:
866 ValueError: When ``activation_swap="attention"`` but the model has
867 no ``self_attn`` module, matching the eager attention-swap
868 contract.
869 """
870 if pass_config.activation_swap == "none":
871 return graph_module
872 if not _AO_AVAILABLE:
873 raise RuntimeError(
874 "activation_swap='attention' requires torch's "
875 "torch._functorch._activation_offloading.offload_ops (ao:: "
876 "offload/reload/wait ops), which is unavailable in this torch "
877 "build; graph-mode CPU offload cannot run"
878 )
880 shape_env = _graph_shape_env(graph_module)
881 suppress_guards = getattr(shape_env, "suppress_guards", None)
882 context = (
883 suppress_guards()
884 if suppress_guards is not None
885 else contextlib.nullcontext()
886 )
887 # Selection and rewrite only read trace-time size hints. Suppress guard
888 # recording so inspecting symbolic sizes/strides (contiguity, byte
889 # counts, the CPU meta value) can never specialize the dynamic graph.
890 with context:
891 roots = _attention_roots(graph_module, kwargs.get("model"))
892 if not roots:
893 raise ValueError(
894 "activation_swap='attention' found no self_attn modules; "
895 "expected attention modules registered as self_attn"
896 )
898 graph = graph_module.graph
899 order = {node: index for index, node in enumerate(graph.nodes)}
901 candidates = _collect_candidates(graph_module, roots, order)
902 budget_bytes = pass_config.offload_budget_gb * (1024**3)
903 selected, total_bytes = _select_within_budget(candidates, budget_bytes)
905 if not selected:
906 _LOG.info("CPU offload: no attention activations selected")
907 return graph_module
909 wait_offloads: List[Tuple[_OffloadInfo, fx.Node]] = []
910 for info in selected:
911 wait_offload = _insert_forward_offload(graph_module, info)
912 wait_offloads.append((info, wait_offload))
914 for info, wait_offload in wait_offloads:
915 _insert_backward_reload(graph_module, info, wait_offload, order)
917 moved = _prefetch_reloads(
918 graph_module,
919 pass_config.offload_prefetch_n_layers,
920 roots,
921 )
923 graph.lint()
924 graph_module.recompile()
925 _LOG.info(
926 "CPU offload: offloaded %d attention activation(s) "
927 "(%.2f MiB), prefetched %d reload(s)",
928 len(selected),
929 total_bytes / (1024 * 1024),
930 moved,
931 )
932 return graph_module