Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / compile / passes / activation_checkpoint.py: 90%

383 statements  

« 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"""Activation Checkpoint Pass - static-graph activation checkpointing. 

19 

20FX-level activation recomputation for the joint forward+backward graph, 

21following torchtitan graph_trainer's ``tag_with_memory_policy_pass`` + 

22``selective_activation_remat_pass`` design while reusing the dynamic-graph 

23configuration vocabulary (``ActivationCheckpointConfig``: ``mode`` = 

24off/full/selective, with layer selection): 

25 

261. Tag: forward ``call_function`` nodes inside the checkpoint scope get a 

27 ``CheckpointPolicy`` in ``node.meta["recompute"]``. ``full`` scopes the 

28 discovered transformer blocks (the same HuggingFace-marker discovery the 

29 eager path requires), narrowed by the optional layer selectors. 

30 ``selective`` scopes only the eager-aligned module/region targets 

31 (``selective.recompute`` projected onto ``ac_selective_recompute_*``), so 

32 it recomputes the same modules as the eager path and saves everything 

33 else. Nodes outside the scope (embedding, head, the ``train_fn`` loss 

34 chain) stay saved. Structural exceptions are always saved: RNG ops (the 

35 graph cannot replay random state), in-place mutations with their consumers 

36 and the readers of every tensor sharing the mutated storage (including view 

37 aliases), SymInt scalars. 

382. Remat: every tagged node that the backward half consumes (transitively 

39 through other tagged nodes) is duplicated in front of its earliest 

40 backward consumer and the backward consumers are redirected to the 

41 duplicate. A forward original with no remaining readers is erased; one 

42 still read by forward code stays, and its backward readers now rebuild 

43 the value during backward. Either way the activation's forward lifetime 

44 ends at its last forward use instead of spanning the whole step. A 

45 cross-unit forward consumer forces the producing node to stay saved 

46 (recreating it would only waste compute), which keeps each recompute 

47 chain inside one block. 

48 

49The backward half is identified by ``meta["autograd_backward"]``, which the 

50joint tracer guarantees on every supported torch (engine tag on patched 

51torch, structural reconstruction otherwise -- see 

52``tracer/graph_tracer.py``). 

53 

54Ordering contract: the pass must run BEFORE ``FSDPPass``. Recomputed 

55duplicates are ordinary forward ops at tag time, so ``FSDPPass`` inserts 

56parameter all-gathers and the backward re-gathers around them correctly 

57(duplicates are tagged ``autograd_backward`` and count as backward 

58consumers). Running AC after FSDP would make recompute read sharded 

59placeholders. ``PpPass`` runs later and inherits the rewrite value-level. 

60 

61Transformer-block discovery is shared with the eager path 

62(``hyper_parallel.distributed.activation_checkpoint``), so a model is 

63AC-eligible in both modes under the same contract. RNG ops are saved in every 

64mode (a graph cannot replay random state). For collectives, the must-save set 

65(all-to-all/reduce-scatter/in-place allreduce) is always saved; other 

66collectives follow the mode policy. ``ac_save_forward_all_gather`` may opt 

67forward (TP/SP/CP) all-gathers into backward replay. 

68""" 

69 

70from __future__ import annotations 

71 

72__all__ = ["ActivationCheckpointPass", "prepare_activation_checkpoint"] 

73 

74import functools 

75import logging 

76import operator 

77from types import SimpleNamespace 

78from typing import Any, Callable, Dict, List, Optional, Set, Tuple 

79 

80import torch 

81from torch import fx 

82from torch._functorch import compile_utils 

83from torch._ops import OpOverload 

84from torch.utils.checkpoint import CheckpointPolicy 

85 

86# Transformer-block discovery is shared with the eager path: one HF-marker 

87# contract decides which modules form recompute units in both modes. 

88from hyper_parallel.distributed.activation_checkpoint import ( 

89 _find_transformer_layer_container_infos, 

90 _flatten_layer_container_infos, 

91) 

92 

93from ..pass_config import PassConfig 

94from .base import GraphPass 

95 

96_LOG = logging.getLogger(__name__) 

97 

98 

99def _resolve_torch_op(dotted_path: str) -> Optional[Any]: 

100 """Resolve a torch operator to its default overload when available.""" 

101 if dotted_path.count(".") == 1: 

102 dotted_path = f"{dotted_path}.default" 

103 obj = torch.ops 

104 try: 

105 for part in dotted_path.split("."): 

106 obj = getattr(obj, part) 

107 except AttributeError: 

108 return None 

109 return obj 

110 

111 

112def _resolve_op_attr(root: object, dotted_path: str) -> Optional[Any]: 

113 """Resolve an optional operator outside the regular ``torch.ops`` tree.""" 

114 obj = root 

115 try: 

116 for part in dotted_path.split("."): 

117 obj = getattr(obj, part) 

118 except AttributeError: 

119 return None 

120 return obj 

121 

122 

123def _existing_ops(*ops: Any) -> frozenset: 

124 """Return the available operators, omitting optional torch operators.""" 

125 return frozenset(op for op in ops if op is not None) 

126 

127 

128# Collectives that must stay saved in every mode: replaying all-to-all, 

129# reduce-scatter, or an in-place all-reduce would duplicate communication and 

130# re-run a mutation. Other collectives follow the mode policy. 

131_SELECTIVE_AC_COMM_OP_NAMES = ( 

132 "aten.all_to_all_single", 

133 "aten.reduce_scatter_tensor", 

134 "_c10d_functional.all_to_all_single", 

135 "_c10d_functional.reduce_scatter_tensor", 

136 "c10d.allreduce_", 

137) 

138 

139# FSDP all-gathers are inserted after this pass, but forward (TP/SP/CP) 

140# all-gathers are already in the traced forward; saving them avoids a second 

141# collective during backward recompute. ``PassConfig.ac_save_forward_all_gather`` 

142# selects that superset. Only the selective communication set is always saved: 

143# other collectives follow the mode policy, matching the eager path. 

144_GRAPH_AC_COMM_OPS = _existing_ops( 

145 *(_resolve_torch_op(name) for name in _SELECTIVE_AC_COMM_OP_NAMES), 

146 _resolve_op_attr(torch.ops, "deepep.dispatch.default"), 

147 _resolve_op_attr(torch.ops, "deepep.combine.default"), 

148 _resolve_op_attr(torch.ops, "hybridep.dispatch.default"), 

149 _resolve_op_attr(torch.ops, "hybridep.combine.default"), 

150) 

151_GRAPH_FORWARD_ALL_GATHER_OPS = _existing_ops( 

152 _resolve_torch_op("aten.all_gather_into_tensor"), 

153 _resolve_torch_op("_c10d_functional.all_gather_into_tensor"), 

154) 

155 

156 

157def _resolve_wait_tensor() -> Optional[Any]: 

158 """Return the c10d ``wait_tensor`` overload when this torch ships it.""" 

159 functional = getattr(torch.ops, "_c10d_functional", None) 

160 wait = getattr(functional, "wait_tensor", None) 

161 if wait is None: 

162 return None 

163 return getattr(wait, "default", None) 

164 

165 

166# getitem / wait_tensor extract or await their producer's value: their 

167# save/recompute decision is inherited, and remat walks through them. 

168_TRANSPARENT_OPS: Tuple[Any, ...] = tuple( 

169 target 

170 for target in (operator.getitem, _resolve_wait_tensor()) 

171 if target is not None 

172) 

173 

174_RECOMPUTE_POLICIES = ( 

175 CheckpointPolicy.PREFER_RECOMPUTE, 

176 CheckpointPolicy.MUST_RECOMPUTE, 

177) 

178 

179 

180def _must_recompute(node: fx.Node) -> bool: 

181 """Whether ``node`` carries a policy the partitioner would recompute.""" 

182 return node.meta.get("recompute") in _RECOMPUTE_POLICIES 

183 

184 

185def _node_stack_fqns(node: fx.Node) -> List[str]: 

186 """Module FQNs on ``node``'s ``nn_module_stack``, innermost first.""" 

187 stack = node.meta.get("nn_module_stack") or {} 

188 return [fqn for fqn, _ in reversed(list(stack.values()))] 

189 

190 

191def _at_or_under(fqn: str, root: str) -> bool: 

192 """Whether ``fqn`` equals ``root`` or lives below it.""" 

193 return fqn == root or fqn.startswith(f"{root}.") 

194 

195 

196def _first_container(fqns: List[str], roots: frozenset) -> Optional[str]: 

197 """Return the first root that contains one of ``fqns`` (innermost wins). 

198 

199 ``roots`` is sorted so a (currently impossible) nested-root match is still 

200 deterministic. ``fqns`` is innermost-first, so the first hit is the 

201 innermost containing root. 

202 """ 

203 for fqn in fqns: 

204 for root in sorted(roots): 

205 if _at_or_under(fqn, root): 

206 return root 

207 return None 

208 

209 

210class _CheckpointScope: 

211 """Resolved recompute scope for one compilation. 

212 

213 ``_resolve_scope`` always fills every field; the ``None`` defaults exist 

214 for direct construction in tests and mean "no region" / "no boundary 

215 units", which makes every node ineligible / disables the cross-unit rule. 

216 

217 Attributes: 

218 region_fqns: FQNs whose subtree may recompute. Empty (or ``None``) 

219 makes every node ineligible (the pass becomes a no-op). 

220 exclude_fqns: FQNs whose subtree must stay saved. No production 

221 caller sets this now that the model-adapter region source is gone; 

222 retained for direct callers that narrow the scope. The layer 

223 selectors leave it empty. 

224 unit_fqns: Boundary units for the cross-unit save rule. Empty (or 

225 ``None``) disables the rule. 

226 on_applied: Optional hook run before the model's forward is traced. 

227 No production caller sets this now that the model-adapter region 

228 source is gone; retained for direct callers. The layer selectors 

229 leave it ``None``. 

230 """ 

231 

232 def __init__( 

233 self, 

234 region_fqns: Optional[frozenset] = None, 

235 exclude_fqns: frozenset = frozenset(), 

236 unit_fqns: Optional[frozenset] = None, 

237 on_applied: Optional[Callable[[torch.nn.Module], None]] = None, 

238 ) -> None: 

239 """Store the resolved scope membership sets.""" 

240 self.region_fqns = region_fqns 

241 self.exclude_fqns = exclude_fqns 

242 self.unit_fqns = unit_fqns 

243 self.on_applied = on_applied 

244 

245 

246def _validate_selected_layer_indices(layer_indices: Any, blocks: list) -> None: 

247 """Validate an explicit list of layer indices against the blocks.""" 

248 if not isinstance(layer_indices, (list, tuple)) or not layer_indices: 

249 raise ValueError( 

250 "activation checkpoint layer_indices must be a non-empty sequence" 

251 ) 

252 if any( 

253 isinstance(index, bool) or not isinstance(index, int) or index < 0 

254 for index in layer_indices 

255 ): 

256 raise ValueError( 

257 "activation checkpoint layer_indices must contain only " 

258 "non-negative integers" 

259 ) 

260 if len(set(layer_indices)) != len(layer_indices): 

261 raise ValueError( 

262 "activation checkpoint layer_indices must not contain duplicates" 

263 ) 

264 if max(layer_indices) >= len(blocks): 

265 raise ValueError( 

266 "activation checkpoint layer index " 

267 f"{max(layer_indices)} exceeds the maximum index {len(blocks) - 1}" 

268 ) 

269 

270 

271def _validate_selected_layer_count(layer_count: Any, blocks: list) -> None: 

272 """Validate a leading layer count against the blocks.""" 

273 if ( 

274 isinstance(layer_count, bool) 

275 or not isinstance(layer_count, int) 

276 or layer_count < 0 

277 ): 

278 raise ValueError( 

279 "activation checkpoint layer_count must be a non-negative integer" 

280 ) 

281 if layer_count > len(blocks): 

282 raise ValueError( 

283 f"activation checkpoint layer_count {layer_count} exceeds discovered " 

284 f"layers {len(blocks)}" 

285 ) 

286 

287 

288def _selected_checkpoint_layer_fqns( 

289 containers: list, 

290 selection: Any, 

291) -> set: 

292 """Select a leading layer count or exact layer indices.""" 

293 blocks = _flatten_layer_container_infos(containers) 

294 layer_count = getattr(selection, "layer_count", None) 

295 layer_indices = getattr(selection, "layer_indices", None) 

296 if (layer_count is None) == (layer_indices is None): 

297 raise ValueError( 

298 "activation checkpoint layer selection requires exactly one of " 

299 "layer_count or layer_indices" 

300 ) 

301 if layer_indices is not None: 

302 _validate_selected_layer_indices(layer_indices, blocks) 

303 return {blocks[index].fqn for index in layer_indices} 

304 

305 _validate_selected_layer_count(layer_count, blocks) 

306 if layer_count == 0: 

307 return set() 

308 return {blocks[index].fqn for index in range(layer_count)} 

309 

310 

311def _resolve_selective_target_fqns( 

312 model: torch.nn.Module, 

313 pass_config: PassConfig, 

314 containers: list, 

315) -> frozenset: 

316 """Resolve eager-aligned selective recompute targets to module FQNs. 

317 

318 Layer-relative region targets are expanded per selected transformer block 

319 (``<block_fqn>.<module_path>``); model-root targets are used as-is. Every 

320 resolved FQN must name a module of the live model, mirroring the eager 

321 ``activation_checkpoint.selective.recompute`` contract. 

322 """ 

323 blocks = _flatten_layer_container_infos(containers) 

324 module_by_fqn = dict(model.named_modules()) 

325 target_fqns = set() 

326 for module_path, layer_indices in pass_config.ac_selective_recompute_regions or (): 

327 for layer_index in layer_indices: 

328 if layer_index >= len(blocks): 

329 raise ValueError( 

330 "activation checkpoint selective target layer index " 

331 f"{layer_index} exceeds the maximum index {len(blocks) - 1}" 

332 ) 

333 block = blocks[layer_index] 

334 fqn = f"{block.fqn}.{module_path}" if module_path else block.fqn 

335 if fqn not in module_by_fqn: 

336 raise ValueError( 

337 "activation checkpoint selective target " 

338 f"{module_path!r} does not resolve to a module in layer " 

339 f"{block.fqn}" 

340 ) 

341 target_fqns.add(fqn) 

342 for module_path in pass_config.ac_selective_recompute_modules or (): 

343 if module_path not in module_by_fqn: 

344 raise ValueError( 

345 "activation checkpoint selective target " 

346 f"{module_path!r} is not a module of the model" 

347 ) 

348 target_fqns.add(module_path) 

349 return frozenset(target_fqns) 

350 

351 

352def _resolve_scope( 

353 model: Optional[torch.nn.Module], pass_config: PassConfig 

354) -> _CheckpointScope: 

355 """Resolve the checkpoint scope from the mode and selectors. 

356 

357 The recompute scope and the boundary units are the discovered transformer 

358 blocks — the same HuggingFace-marker discovery the eager path requires, so 

359 a model is AC-eligible in both modes under the same contract. Nodes outside 

360 the blocks (embedding, head, the ``train_fn`` loss chain) are never tagged, 

361 which also keeps the head/epilogue backward from pulling the whole forward 

362 into one recompute chain. 

363 

364 ``full`` recomputes every discovered block, or only the blocks chosen by 

365 ``ac_layer_count`` / ``ac_layer_indices``. ``selective`` recomputes only 

366 the eager-aligned module/region targets in ``ac_selective_recompute_*``; 

367 each target module is its own boundary unit. 

368 

369 Raises: 

370 ValueError: When the live model is missing, no transformer blocks are 

371 discovered, or a selective target does not resolve in the model. 

372 """ 

373 if model is None: 

374 raise ValueError( 

375 "ActivationCheckpointPass requires the live model via kwargs " 

376 "(model=...) so it can discover the transformer blocks to " 

377 "checkpoint" 

378 ) 

379 containers = _find_transformer_layer_container_infos(model) 

380 if pass_config.ac_mode == "selective": 

381 if pass_config.ac_selective_recompute_regions and not containers: 

382 raise ValueError( 

383 f"{type(model).__name__} has no module with a " 

384 "'gradient_checkpointing' attribute and a non-empty repeated " 

385 "block container; selective layer-relative targets cannot " 

386 "resolve their layers" 

387 ) 

388 target_fqns = _resolve_selective_target_fqns(model, pass_config, containers) 

389 if not target_fqns: 

390 _LOG.info("activation checkpoint selective targets matched no module") 

391 return _CheckpointScope(region_fqns=target_fqns, unit_fqns=target_fqns) 

392 if not containers: 

393 raise ValueError( 

394 f"{type(model).__name__} has no module with a 'gradient_checkpointing' " 

395 "attribute and a non-empty repeated block container; activation " 

396 "checkpointing cannot resolve its layers" 

397 ) 

398 block_fqns = frozenset( 

399 block.fqn for container in containers for block in container.blocks 

400 ) 

401 has_count = pass_config.ac_layer_count is not None 

402 has_indices = pass_config.ac_layer_indices is not None 

403 if not has_count and not has_indices: 

404 return _CheckpointScope(region_fqns=block_fqns, unit_fqns=block_fqns) 

405 selection = SimpleNamespace( 

406 layer_count=pass_config.ac_layer_count, 

407 layer_indices=pass_config.ac_layer_indices, 

408 ) 

409 selected_layers = frozenset(_selected_checkpoint_layer_fqns(containers, selection)) 

410 if not selected_layers: 

411 # Zero selected layers is a no-op, not an error. 

412 _LOG.info("activation checkpoint layer selection matched zero layers") 

413 return _CheckpointScope(region_fqns=selected_layers, unit_fqns=block_fqns) 

414 

415 

416def prepare_activation_checkpoint( 

417 model: Optional[torch.nn.Module], pass_config: PassConfig 

418) -> _CheckpointScope: 

419 """Resolve the AC scope before tracing. 

420 

421 ``GraphCompiler`` calls this once pre-trace and hands the resolved scope 

422 to the pass, so block discovery happens exactly once. A scope supplied 

423 directly (tests, or a caller that narrows the regions) may still carry an 

424 ``on_applied`` hook, which runs here before the model's forward is traced. 

425 

426 Args: 

427 model: The live model whose transformer blocks define the scope. 

428 pass_config: Parallel configuration driving ``ac_mode``. 

429 

430 Returns: 

431 The resolved scope. 

432 """ 

433 scope = _resolve_scope(model, pass_config) 

434 if scope.on_applied is not None and model is not None: 

435 scope.on_applied(model) 

436 return scope 

437 

438 

439def _is_eligible(node: fx.Node, scope: _CheckpointScope) -> bool: 

440 """Whether ``node`` may carry a recompute decision at all. 

441 

442 Nodes outside the checkpoint regions stay saved: activation 

443 checkpointing targets transformer-block forwards, mirroring the eager 

444 path that wraps the discovered blocks only. 

445 """ 

446 if not scope.region_fqns: 

447 return False 

448 fqns = _node_stack_fqns(node) 

449 if not fqns: 

450 return False 

451 if _first_container(fqns, scope.exclude_fqns) is not None: 

452 return False 

453 return _first_container(fqns, scope.region_fqns) is not None 

454 

455 

456def _unit_of(node: fx.Node, scope: _CheckpointScope) -> Optional[str]: 

457 """Return ``node``'s boundary block unit, if any.""" 

458 if not scope.unit_fqns: 

459 return None 

460 return _first_container(_node_stack_fqns(node), scope.unit_fqns) 

461 

462 

463def _tag_policy_pass( 

464 graph_module: fx.GraphModule, 

465 pass_config: PassConfig, 

466 scope: _CheckpointScope, 

467) -> None: 

468 """Tag every in-scope forward node ``MUST_RECOMPUTE``. 

469 

470 The scope already encodes the mode: ``full`` selects whole blocks (or the 

471 chosen layers), while ``selective`` selects the eager-aligned module/region 

472 targets. RNG ops and SymInt scalars stay saved; getitem/wait_tensor inherit 

473 their parent's decision. The communication set is saved in every mode; 

474 all-gathers join the saved set when ``ac_save_forward_all_gather`` is 

475 enabled. 

476 """ 

477 comm_ops = _GRAPH_AC_COMM_OPS 

478 if pass_config.ac_save_forward_all_gather: 

479 comm_ops = comm_ops | _GRAPH_FORWARD_ALL_GATHER_OPS 

480 for node in graph_module.graph.nodes: 

481 if node.op != "call_function" or node.meta.get("autograd_backward", False): 

482 continue 

483 if node.target in _TRANSPARENT_OPS: 

484 parent = node.args[0] 

485 if isinstance(parent, fx.Node) and "recompute" in parent.meta: 

486 node.meta["recompute"] = parent.meta["recompute"] 

487 continue 

488 if not _is_eligible(node, scope): 

489 continue 

490 if _is_rng_op(node) or node.target in comm_ops: 

491 node.meta["recompute"] = CheckpointPolicy.MUST_SAVE 

492 continue 

493 value = node.meta.get("val") 

494 if isinstance(value, torch.SymInt): 

495 node.meta["recompute"] = CheckpointPolicy.MUST_SAVE 

496 continue 

497 node.meta["recompute"] = CheckpointPolicy.MUST_RECOMPUTE 

498 

499 

500def _flatten_getitems(graph_module: fx.GraphModule) -> None: 

501 """Flatten tuple projections when this torch build provides the helper.""" 

502 raise_getitems = getattr(compile_utils, "raise_getitems", None) 

503 if raise_getitems is not None: 

504 raise_getitems(graph_module) 

505 

506 

507def _is_mutable_op(target: Any) -> bool: 

508 """Return whether ``target`` is an in-place ``OpOverload``.""" 

509 if not isinstance(target, OpOverload): 

510 return False 

511 return bool(getattr(getattr(target, "_schema", None), "is_mutable", False)) 

512 

513 

514def _is_rng_op(node: fx.Node) -> bool: 

515 """Return True when a node's seeded nondeterminism cannot be ruled out.""" 

516 return bool( 

517 hasattr(node.target, "tags") 

518 and torch.Tag.nondeterministic_seeded in node.target.tags 

519 ) 

520 

521 

522def _mutated_arg_nodes(node: fx.Node) -> List[fx.Node]: 

523 """Return the input nodes whose tensors ``node`` overwrites in place.""" 

524 schema = getattr(node.target, "_schema", None) 

525 if schema is None: 

526 return [] 

527 mutated: List[fx.Node] = [] 

528 for position, schema_arg in enumerate(schema.arguments): 

529 alias_info = getattr(schema_arg, "alias_info", None) 

530 if alias_info is None or not alias_info.is_write: 

531 continue 

532 arg = ( 

533 node.args[position] 

534 if position < len(node.args) 

535 else node.kwargs.get(schema_arg.name) 

536 ) 

537 if isinstance(arg, fx.Node): 

538 mutated.append(arg) 

539 return mutated 

540 

541 

542def _aliased_input_nodes(node: fx.Node) -> List[fx.Node]: 

543 """Return input nodes whose storage ``node``'s outputs may share. 

544 

545 Alias relationships come from the operator schema. A return carrying 

546 ``alias_info`` aliases the arguments whose alias sets intersect; several 

547 multi-output views (``split`` / ``chunk`` / ``unbind``) instead mark the 

548 input with an ``after_set`` and leave the returns unannotated. In-place 

549 writes always share their argument's storage. ``getitem`` picks one output 

550 of a producer, so it inherits the producer's storage even though the 

551 builtin itself has no schema. 

552 """ 

553 if node.op != "call_function": 

554 return [] 

555 if node.target is operator.getitem: 

556 producer = node.args[0] if node.args else None 

557 return [producer] if isinstance(producer, fx.Node) else [] 

558 schema = getattr(node.target, "_schema", None) 

559 if schema is None: 

560 return [] 

561 result_names: Set[str] = set() 

562 for result in schema.returns: 

563 alias_info = getattr(result, "alias_info", None) 

564 if alias_info is not None: 

565 result_names.update(alias_info.before_set) 

566 result_names.update(alias_info.after_set) 

567 wildcard_result = "*" in result_names 

568 aliased: List[fx.Node] = [] 

569 for position, schema_arg in enumerate(schema.arguments): 

570 alias_info = getattr(schema_arg, "alias_info", None) 

571 if alias_info is None: 

572 continue 

573 arg_names = set(alias_info.before_set) | set(alias_info.after_set) 

574 if not ( 

575 getattr(alias_info, "is_write", False) 

576 or wildcard_result 

577 or "*" in arg_names 

578 or bool(arg_names & result_names) 

579 ): 

580 continue 

581 arg = ( 

582 node.args[position] 

583 if position < len(node.args) 

584 else node.kwargs.get(schema_arg.name) 

585 ) 

586 if isinstance(arg, fx.Node): 

587 aliased.append(arg) 

588 return aliased 

589 

590 

591def _forward_alias_neighbors( 

592 graph_module: fx.GraphModule, 

593) -> Dict[fx.Node, Set[fx.Node]]: 

594 """Build the undirected shared-storage graph over the forward graph.""" 

595 neighbors: Dict[fx.Node, Set[fx.Node]] = {} 

596 for node in graph_module.graph.nodes: 

597 if node.meta.get("autograd_backward", False): 

598 continue 

599 for arg in _aliased_input_nodes(node): 

600 if arg.meta.get("autograd_backward", False): 

601 continue 

602 neighbors.setdefault(node, set()).add(arg) 

603 neighbors.setdefault(arg, set()).add(node) 

604 return neighbors 

605 

606 

607def _alias_closure( 

608 roots: Set[fx.Node], neighbors: Dict[fx.Node, Set[fx.Node]] 

609) -> Set[fx.Node]: 

610 """Return every forward node sharing storage with any of ``roots``. 

611 

612 The walk is undirected so a mutation through one view reaches its base 

613 (backward along the alias edge) and then the sibling views of that base 

614 (forward along their edges). 

615 """ 

616 closure = set(roots) 

617 stack = list(roots) 

618 while stack: 

619 current = stack.pop() 

620 for neighbor in neighbors.get(current, ()): 

621 if neighbor not in closure: 

622 closure.add(neighbor) 

623 stack.append(neighbor) 

624 return closure 

625 

626 

627def _tag_inplace_saves(graph_module: fx.GraphModule) -> None: 

628 """Force saves around in-place mutations and their aliased-storage readers. 

629 

630 The mutation must run exactly once in forward, so it stays saved together 

631 with its forward consumers. Every forward reader of the mutated storage 

632 stays saved as well: a recompute duplicate would re-execute against either 

633 the post-mutation original or a pre-mutation duplicate of the producer, 

634 and neither matches what forward computed at the reader's own position. 

635 Eager autograd stays silent for such a read — its value reaches backward 

636 only through the recompute chain, never as a saved tensor. 

637 Storage owners must stay saved too: backward may consume a buffer written 

638 only through a view, and replaying its allocation would discard those writes. 

639 The closure follows operator-schema aliases, so readers of a view (or of a 

640 sibling view when the write goes through another view) are covered, and 

641 mutations outside the checkpoint scope still contribute their storage. 

642 """ 

643 nodes = list(graph_module.graph.nodes) 

644 mutated_bases: Set[fx.Node] = set() 

645 for node in nodes: 

646 if ( 

647 node.op != "call_function" 

648 or node.meta.get("autograd_backward", False) 

649 or not _is_mutable_op(node.target) 

650 ): 

651 continue 

652 mutated_bases.update(_mutated_arg_nodes(node)) 

653 if "recompute" not in node.meta: 

654 continue 

655 node.meta["recompute"] = CheckpointPolicy.MUST_SAVE 

656 for user in node.users: 

657 if ( 

658 not user.meta.get("autograd_backward", False) 

659 and "recompute" in user.meta 

660 ): 

661 user.meta["recompute"] = CheckpointPolicy.MUST_SAVE 

662 if not mutated_bases: 

663 return 

664 aliased_storage = _alias_closure( 

665 mutated_bases, _forward_alias_neighbors(graph_module) 

666 ) 

667 for node in nodes: 

668 if ( 

669 node.op != "call_function" 

670 or node.meta.get("autograd_backward", False) 

671 or node.meta.get("recompute") not in _RECOMPUTE_POLICIES 

672 ): 

673 continue 

674 if not aliased_storage.isdisjoint((node, *node.all_input_nodes)): 

675 node.meta["recompute"] = CheckpointPolicy.MUST_SAVE 

676 

677 

678def _tag_cross_unit_saves( 

679 graph_module: fx.GraphModule, scope: _CheckpointScope 

680) -> None: 

681 """Save recomputable nodes read forward across a unit boundary. 

682 

683 Their original activation stays alive for the forward consumer anyway, so 

684 recomputing them in backward would be pure waste. 

685 """ 

686 for node in graph_module.graph.nodes: 

687 if ( 

688 node.op != "call_function" 

689 or node.meta.get("autograd_backward", False) 

690 or node.meta.get("recompute") not in _RECOMPUTE_POLICIES 

691 ): 

692 continue 

693 if _has_cross_unit_forward_consumer(node, scope): 

694 node.meta["recompute"] = CheckpointPolicy.MUST_SAVE 

695 

696 

697def _tag_sac_policy( 

698 graph_module: fx.GraphModule, 

699 pass_config: PassConfig, 

700 scope: _CheckpointScope, 

701) -> None: 

702 """Annotate forward nodes with ``meta["recompute"]`` policies. 

703 

704 Pass 1 tags per policy with the structural exceptions; pass 2 forces saves 

705 on in-place mutations, their consumers and the forward readers of the 

706 mutated storage (view aliases included); pass 3 forces saves on 

707 recomputable nodes read forward across a unit boundary (their original 

708 stays alive anyway, so the backward recompute would be pure waste). 

709 """ 

710 if not scope.region_fqns: 

711 return 

712 _tag_policy_pass(graph_module, pass_config, scope) 

713 _tag_inplace_saves(graph_module) 

714 if scope.unit_fqns: 

715 _tag_cross_unit_saves(graph_module, scope) 

716 

717 

718def _has_cross_unit_forward_consumer(node: fx.Node, scope: _CheckpointScope) -> bool: 

719 """Whether ``node`` is read forward outside its own boundary unit. 

720 

721 Transparent (inherited) getitem/wait_tensor chains are walked through; 

722 any other forward consumer in a different unit (or outside every unit, 

723 e.g. the epilogue) means the original must stay alive anyway. 

724 """ 

725 node_unit = _unit_of(node, scope) 

726 policy = node.meta["recompute"] 

727 seen = {node} 

728 stack = [node] 

729 while stack: 

730 current = stack.pop() 

731 for user in current.users: 

732 if user in seen: 

733 continue 

734 seen.add(user) 

735 if user.op == "output" or user.meta.get("autograd_backward", False): 

736 continue 

737 if ( 

738 user.op == "call_function" 

739 and user.target in _TRANSPARENT_OPS 

740 and user.meta.get("recompute") == policy 

741 ): 

742 stack.append(user) 

743 continue 

744 if _unit_of(user, scope) != node_unit: 

745 return True 

746 return False 

747 

748 

749def _get_attr_value(graph_module: fx.GraphModule, target: str) -> Any: 

750 """Resolve an FX ``get_attr`` target, including dotted qualified names.""" 

751 try: 

752 return graph_module.get_submodule(target) 

753 except AttributeError: 

754 return getattr(graph_module, target, None) 

755 

756 

757def _duplicate_subgraph_get_attrs( 

758 graph_module: fx.GraphModule, fwd_node: fx.Node, bwd_target: fx.Node 

759) -> Dict[fx.Node, fx.Node]: 

760 """Give a recompute duplicate private copies of HOP subgraph get_attrs. 

761 

762 Higher-order ops (flex_attention etc.) reference their subgraphs through 

763 ``get_attr`` nodes. Sharing the original would let a later regional 

764 Inductor pass place the shared subgraph in only one partition; fresh 

765 get_attr nodes keep each region self-contained. 

766 """ 

767 duplicates: Dict[fx.Node, fx.Node] = {} 

768 for arg in fwd_node.all_input_nodes: 

769 if arg.op != "get_attr": 

770 continue 

771 if not isinstance(_get_attr_value(graph_module, arg.target), fx.GraphModule): 

772 continue 

773 with graph_module.graph.inserting_before(bwd_target): 

774 dup_attr = graph_module.graph.get_attr(arg.target) 

775 dup_attr.meta.update(arg.meta) 

776 duplicates[arg] = dup_attr 

777 return duplicates 

778 

779 

780def _remat(graph_module: fx.GraphModule) -> int: 

781 """Duplicate tagged recompute nodes in front of their backward consumers. 

782 

783 Returns the number of duplicated forward nodes. The graph is mutated in 

784 place; originals whose consumers were all redirected are erased, and 

785 ``raise_getitems`` flattens output/tuple projections for better memory. 

786 """ 

787 graph = graph_module.graph 

788 all_nodes = list(graph.nodes) 

789 order = {node: idx for idx, node in enumerate(all_nodes)} 

790 

791 # Map each tagged forward node to its earliest backward consumer; the 

792 # transitive walk through tagged ancestors mirrors the partitioner's 

793 # recompute-closure gathering (saved ancestors stay live, so only tagged 

794 # ones need duplicating). 

795 remat_targets: Dict[fx.Node, fx.Node] = {} 

796 for bwd_node in all_nodes: 

797 if not bwd_node.meta.get("autograd_backward", False): 

798 continue 

799 seen: Set[fx.Node] = set() 

800 stack = list(bwd_node.all_input_nodes) 

801 while stack: 

802 current = stack.pop() 

803 if current in seen or not _must_recompute(current): 

804 continue 

805 seen.add(current) 

806 remat_targets.setdefault(current, bwd_node) 

807 stack.extend(current.all_input_nodes) 

808 

809 if not remat_targets: 

810 return 0 

811 

812 recomputed: Dict[fx.Node, fx.Node] = {} 

813 

814 def remat_arg(arg: Any, get_attr_dups: Dict[fx.Node, fx.Node]) -> Any: 

815 """Redirect duplicate args to their recompute copies.""" 

816 if isinstance(arg, fx.Node): 

817 if arg in get_attr_dups: 

818 return get_attr_dups[arg] 

819 if arg in recomputed: 

820 return recomputed[arg] 

821 return arg 

822 

823 for fwd_node in sorted(remat_targets, key=order.__getitem__): 

824 bwd_target = remat_targets[fwd_node] 

825 get_attr_dups = _duplicate_subgraph_get_attrs( 

826 graph_module, fwd_node, bwd_target 

827 ) 

828 with graph.inserting_before(bwd_target): 

829 duplicate = graph.node_copy( 

830 fwd_node, 

831 functools.partial(remat_arg, get_attr_dups=get_attr_dups), 

832 ) 

833 # Leave the name to ``node_copy``/``create_node`` so the graph's name 

834 # namespace owns uniqueness; a direct ``.name =`` assignment bypasses 

835 # it and can collide with an existing node. 

836 duplicate.meta["autograd_backward"] = True 

837 duplicate.meta["ac_recomputed"] = True 

838 duplicate.meta["ac_recomputed_from"] = fwd_node.name 

839 # node_copy shares meta, including the policy tag. Drop it so a second 

840 # pass run cannot mistake the duplicate for a recompute candidate. 

841 duplicate.meta.pop("recompute", None) 

842 recomputed[fwd_node] = duplicate 

843 

844 def redirect(arg: Any) -> Any: 

845 """Arg transform for backward consumers of recomputed originals.""" 

846 if isinstance(arg, fx.Node) and arg in recomputed: 

847 return recomputed[arg] 

848 return arg 

849 

850 direct_backward_consumers = { 

851 user 

852 for fwd_node in recomputed 

853 for user in fwd_node.users 

854 if user.meta.get("autograd_backward", False) 

855 } 

856 for bwd_node in direct_backward_consumers: 

857 bwd_node.args = fx.map_arg(bwd_node.args, redirect) 

858 bwd_node.kwargs = fx.map_arg(bwd_node.kwargs, redirect) 

859 

860 for original in reversed(list(recomputed)): 

861 if not original.users: 

862 graph.erase_node(original) 

863 

864 _flatten_getitems(graph_module) 

865 graph.lint() 

866 # ``raise_getitems`` recompiles when present; the explicit call also covers 

867 # torch builds without it, where the inserted/erased nodes would otherwise 

868 # leave the GraphModule's generated code stale. 

869 graph_module.recompile() 

870 return len(recomputed) 

871 

872 

873class ActivationCheckpointPass(GraphPass): 

874 """Static-graph activation checkpointing (tag + recompute-materialize). 

875 

876 Configure through ``PassConfig.ac_mode`` (``"off"`` / ``"full"`` / 

877 ``"selective"``). ``"full"`` uses the optional ``ac_layer_count`` / 

878 ``ac_layer_indices`` layer selectors; ``"selective"`` uses the 

879 ``ac_selective_recompute_regions`` / ``ac_selective_recompute_modules`` 

880 targets. The trainer-level ``activation_checkpoint`` section is projected 

881 onto these fields by ``build_pass_config_from_trainer_config``. 

882 """ 

883 

884 name = "activation_checkpoint" 

885 

886 def run( 

887 self, 

888 graph_module: fx.GraphModule, 

889 pass_config: PassConfig, 

890 **kwargs: Any, 

891 ) -> fx.GraphModule: 

892 """Tag the joint graph and materialize recompute duplicates. 

893 

894 Args: 

895 graph_module: The joint forward+backward FX graph. 

896 pass_config: Parallel configuration driving ``ac_mode``. 

897 **kwargs: ``model`` (the live module) is required whenever 

898 ``ac_mode != "off"``: block discovery resolves the recompute 

899 scope from it. ``ac_scope`` is the pre-resolved scope from 

900 ``GraphCompiler`` (a direct-caller scope may still carry an 

901 ``on_applied`` hook, which that pre-trace step runs); direct 

902 callers may omit it. 

903 

904 Returns: 

905 The transformed graph module. 

906 """ 

907 if pass_config.ac_mode == "off": 

908 return graph_module 

909 scope = kwargs.get("ac_scope") 

910 if scope is None: 

911 scope = prepare_activation_checkpoint(kwargs.get("model"), pass_config) 

912 already_rematted = any( 

913 node.meta.get("ac_recomputed") for node in graph_module.graph.nodes 

914 ) 

915 _tag_sac_policy(graph_module, pass_config, scope) 

916 duplicated = _remat(graph_module) 

917 _LOG.info( 

918 "Activation checkpointing (mode=%s) recomputed %d node(s)", 

919 pass_config.ac_mode, 

920 duplicated, 

921 ) 

922 if duplicated == 0 and scope.region_fqns and not already_rematted: 

923 _LOG.warning( 

924 "activation checkpointing matched scope %s but recomputed no " 

925 "node; the model may already be wrapped by eager activation " 

926 "checkpointing, so graph-mode recompute is inactive", 

927 sorted(scope.region_fqns), 

928 ) 

929 return graph_module