Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / compile / pass_config.py: 95%
254 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"""
16Parallel Configuration - Graph-mode parallel configuration.
18Pure configuration dataclass: no environment probes. Whether FSDP actually
19runs is decided by ``fsdp_enabled`` here (the user's intent) AND the runtime
20distributed guard inside ``FSDPPass`` (which still early-returns on
21``world_size == 1``). The previous ``fsdp_enabled`` property returned
22``dist.is_initialized() and world_size > 1`` — that turned on FSDP whenever
23distributed was initialized, leaving no way to run pure-TP / pure-PP graph
24mode. The explicit field fixes that. Pipeline-parallel (``pp_enabled``)
25follows the same contract: intent here, runtime guard in ``PpPass``.
27Note:
28 TP / SP / LP are deliberately NOT configurable here: their collectives
29 are baked into module boundary forwards by the automodel flow (shared
30 with eager mode), and no graph pass consumes them. ``PassConfig`` only
31 drives what the graph passes actually execute.
32"""
34__all__ = [
35 "PassConfig",
36 "GradientReduction",
37 "PP_SCHEDULES",
38 "INDUCTOR_MODES",
39 "INDUCTOR_BACKENDS",
40 "ACLGRAPH_MODES",
41 "DP_MODES",
42 "AC_MODES",
43 "ACTIVATION_SWAP_MODES",
44 "normalize_dp_mode",
45 "build_pass_config_from_trainer_config",
46]
48import logging
49import math
50from dataclasses import dataclass
51from typing import Any, Dict, List, Literal, Optional, Tuple
53_LOG = logging.getLogger(__name__)
56# Pipeline schedule names accepted by ``pp_schedule``. Kept torch-free here so
57# the config dataclass stays importable anywhere; ``pp_schedule``'s registry
58# (which does import torch) must expose exactly these keys.
59PP_SCHEDULES = ("gpipe", "1f1b", "interleaved_1f1b", "vpp")
61# Backend compilation modes for the terminal ``InductorPass``:
62# "off" - no Inductor compilation (graph runs as plain FX nodes)
63# "regional" - compile tagged compute regions; collectives and
64# side-effectful nodes stay eager (see InductorPass)
65# "full" - compile the whole joint graph as one Inductor region
66INDUCTOR_MODES = ("off", "regional", "full")
68# Inductor backend selection for terminal compilation. ``default`` keeps the
69# running torch/torch_npu device backend; ``dvm`` requires torch_npu's DVM
70# Inductor backend to have been selected via ``TORCHINDUCTOR_NPU_BACKEND=dvm``
71# before torch_npu was imported.
72INDUCTOR_BACKENDS = ("default", "dvm")
74ACLGRAPH_MODES = ("off", "static", "dynamic")
76# Schedule names that can drive multiple virtual stages per physical rank.
77_INTERLEAVED_SCHEDULES = ("interleaved_1f1b", "vpp")
79# Data-parallel modes, mirroring simplefsdp's ``data_parallel`` modes:
80# "fsdp" -> fully_shard (Shard(0) on the fsdp axis)
81# "ddp" -> replicate (Replicate; grads all-reduced)
82# "hsdp" -> hybrid_shard (Replicate x Shard(0); rs + all-reduce)
83DP_MODES = ("fsdp", "ddp", "hsdp")
85# simplefsdp / fully_shard spellings accepted as aliases.
86_DP_MODE_ALIASES = {
87 "fully_shard": "fsdp",
88 "replicate": "ddp",
89 "hybrid_shard": "hsdp",
90}
92# Static-graph activation checkpointing modes for ``ActivationCheckpointPass``,
93# a strict subset of the dynamic ``ActivationCheckpointConfig.mode``
94# vocabulary (``hybrid`` has no static-graph equivalent and is rejected):
95# "off" - save every forward activation (no recompute pass)
96# "full" - recompute every checkpoint-scoped module op in backward
97# "selective" - eager-aligned target selection: recompute only the declared
98# module/region targets, save everything else
99AC_MODES = ("off", "full", "selective")
101# Dynamic-graph activation-swap modes reused by graph mode. ``attention``
102# offloads saved activations inside ``self_attn`` modules to host memory
103# (the graph pass equivalent of the eager attention swap wrapper).
104ACTIVATION_SWAP_MODES = ("none", "attention")
107def normalize_dp_mode(mode: str) -> str:
108 """Return the canonical DP mode for ``mode`` (accepts simplefsdp aliases).
110 Args:
111 mode: Requested DP mode spelling.
113 Returns:
114 The canonical ``DP_MODES`` entry.
116 Raises:
117 ValueError: When ``mode`` is not a string or is unknown.
118 """
119 if not isinstance(mode, str):
120 raise ValueError(f"dp_mode must be a string, got {type(mode).__name__}")
121 key = mode.strip().lower()
122 return _DP_MODE_ALIASES.get(key, key)
125@dataclass(frozen=True)
126class GradientReduction:
127 """Reduction operation and a divisor independent of the communication mesh.
129 The divisor is applied before communication, matching eager FSDP's
130 reduction-precision scaling and its singleton-group behavior.
131 """
133 reduce_op: Literal["avg", "sum"] = "avg"
134 divisor: int = 1
136 def __post_init__(self) -> None:
137 if self.reduce_op not in ("avg", "sum"):
138 raise ValueError("Gradient reduction must be 'avg' or 'sum'")
139 if isinstance(self.divisor, bool) or not isinstance(self.divisor, int) or self.divisor < 1:
140 raise ValueError("Gradient divisor must be a positive integer")
142 @property
143 def scale(self) -> Optional[float]:
144 """Return the pre-reduction multiplier, or None for an identity scale."""
145 return 1.0 / self.divisor if self.divisor > 1 else None
149@dataclass
150class PassConfig:
151 """Parallel configuration for graph-mode FSDP (+ optional TP / SP / PP) training.
153 Attributes:
154 enable_overlap: Drive ``AutoOverlapPass`` to move ``wait_tensor`` for
155 communication/compute overlap.
156 fsdp_bucketing: Fuse compatible FSDP all-gathers and reduce-scatters before
157 overlap. Python-only, disabled by default; configure before compilation.
158 fsdp_bucket_modules: Optional module FQN groups, produced by
159 ``build_module_bucket_plans`` or supplied as a list of paths/groups.
160 None groups by immediate parameter parents; an empty list selects nothing.
161 All ranks in each FSDP group must use the same configuration.
162 fsdp_allgather_prefetch: Prefetch forward/backward FSDP all-gathers
163 and delay their wait/view nodes independently of enable_overlap.
164 fsdp_overlap_grad_reduce: Advance backward reduce-scatter launches and
165 delay their waits independently of parameter prefetch and enable_overlap.
166 max_in_flight_gb: GiB of early FSDP all-gather replicas before first use,
167 shared across anchors in each phase. Uses PyTorch's overlap scheduler
168 naming and binary units. Zero disables early launches, not wait sinking.
169 fsdp_enabled: Drive ``FSDPPass`` (data-parallel partitioning: parameter
170 all_gather + gradient reduction + live-model sharding, selected by
171 ``dp_mode``). ``False`` skips data parallelism entirely — set this
172 for pure-TP / pure-PP graph-mode runs. ``FSDPPass`` itself still
173 early-returns when distributed is not initialized or
174 ``world_size == 1``, so single-card runs are a no-op regardless.
175 fsdp_reshard_after_forward: Drive the FSDP reshard optimization.
176 When ``True`` (default, matching FSDP's ``reshard_after_forward``)
177 ``FSDPPass`` sinks each param's all_gather to its first forward
178 use, frees the replicated full parameter once its last forward
179 reader is done, and — when the backward still needs it — inserts a
180 fresh all_gather plus a rematerialization of the saved forward
181 views just before the first backward consumer. Peak memory then
182 tracks the forward working set instead of the sum of all
183 replicated parameters. Set ``False`` to keep every gathered
184 parameter resident for the whole joint graph (previous behavior).
185 fsdp_degree: Size of the FSDP group. ``None`` (default) means
186 "resolve at runtime": the trainer back-fills it from the
187 automodel ``MeshContext`` (TP+FSDP hybrid, where the FSDP group
188 is a proper sub-group of the world), and ``FSDPPass`` falls back
189 to ``world_size`` for the FSDP-only path. Mutating this after
190 construction is supported but discouraged — prefer passing the
191 resolved degree at construction time (see ``GraphTrainer``).
192 For ``dp_mode="hsdp"`` this is the *shard* axis degree.
193 dp_mode: Data-parallel mode, one of ``DP_MODES``: ``"fsdp"``
194 (fully_shard, the default), ``"ddp"`` (replicate; no parameter
195 sharding, gradients all-reduced), or ``"hsdp"`` (hybrid_shard;
196 parameters replicated on the ``dp_replicate`` axis and sharded on
197 the ``fsdp`` axis, gradients reduce-scattered then all-reduced).
198 simplefsdp spellings ``"fully_shard"`` / ``"replicate"`` /
199 ``"hybrid_shard"`` are accepted as aliases and normalized.
200 dp_replicate_degree: Size of the replicate axis for ``"ddp"`` /
201 ``"hsdp"``. ``None`` means "resolve at runtime" (from the mesh,
202 or ``world_size // fsdp_degree`` for HSDP / ``world_size`` for
203 DDP). Kept separate from ``fsdp_degree`` (the shard axis) so an
204 HSDP mesh is unambiguous.
205 pp_enabled: Drive ``PpPass`` (pipeline-parallel graph split). When
206 ``True`` the joint fwd+bwd graph is sliced to this rank's stage
207 along module-FQN boundaries declared in ``GraphParallelPlan``, cross-stage
208 activations are exchanged via P2P ``isend``/``irecv``, and a
209 self-contained pipeline schedule is installed as a ``call_module``
210 stub inside the rewritten graph, so the trainer needs no PP
211 wiring. ``PpPass`` early-returns when distributed is not
212 initialized or ``world_size == 1``.
213 pp_degree: Number of pipeline-parallel ranks (physical stages).
214 ``None`` means "resolve at runtime": pure-PP resolves it from
215 ``world_size``; the PP+DP hybrid resolves it from the 2-D
216 ``(pp, DP)`` mesh built by ``GraphCompiler._init_pp_dp_mesh``
217 (which also back-fills ``fsdp_degree`` /
218 ``dp_replicate_degree``), subject to
219 ``pp_degree * dp_degree == world_size``.
220 pp_chunks: Number of virtual pipeline stages per physical rank.
221 ``1`` (default) is the classic single-stage-per-rank layout used
222 by ``"gpipe"`` / ``"1f1b"``. Values ``> 1`` enable VPP
223 (interleaved 1F1B): the model is split into
224 ``pp_degree * pp_chunks`` virtual stages, rank ``r`` owns virtual
225 stages ``r, r + pp_degree, ...``, and the ``"interleaved_1f1b"``
226 schedule pipelines the virtual stages. Requires
227 ``pp_schedule`` to be an interleaved schedule.
228 pp_microbatch_size: Number of samples per microbatch for the
229 pipeline schedule. The per-step batch size (the leading dim of
230 the trainer's input tensor) must be divisible by this. ``1`` means
231 one sample per microbatch (maximum pipeline concurrency, most
232 P2P traffic); larger values trade bubble size for fewer P2P
233 round-trips.
234 pp_schedule: Pipeline schedule name, one of ``PP_SCHEDULES``.
235 ``"gpipe"`` (default) runs all forwards before all backwards
236 (simplest ordering, largest bubble). ``"1f1b"`` interleaves one
237 backward per forward in steady state, shrinking the pipeline
238 bubble and freeing each microbatch's activations as soon as its
239 backward runs (GPipe retains all of them until the sweep ends);
240 it requires ``num_microbatches >= pp_degree``.
241 ``"interleaved_1f1b"`` (alias ``"vpp"``) is the VPP schedule: it
242 supports ``pp_chunks > 1`` virtual stages per rank and uses the
243 classic interleaved-1F1B warmup / steady / cooldown order.
244 ``PpPass`` resolves the name to a schedule class via
245 ``pp_schedule.get_schedule_class``.
246 inductor_mode: Terminal backend compilation for the joint graph, one
247 of ``INDUCTOR_MODES``. ``"off"`` (default) runs the graph as
248 plain FX nodes; ``"regional"`` compiles tagged compute regions
249 with TorchInductor while keeping communication collectives and
250 side-effectful nodes (e.g. the FSDP reshard storage free) eager;
251 ``"full"`` compiles the whole joint graph as one region. Both
252 compiling modes force ``eager_numerics.division_rounding`` on
253 torch builds that provide it (2.11+) so compiled code stays
254 bitwise-equal to eager, and restore the positional calling
255 convention afterwards. Requires a torch with Inductor. With
256 pipeline parallel enabled, ``PpPass`` runs first and this pass
257 compiles each stage's forward/backward subgraph
258 independently (both modes); cross-stage fusion is inherently
259 impossible because the schedule's P2P sits between the stages.
260 inductor_backend: Inductor backend to use for terminal compilation, one
261 of ``INDUCTOR_BACKENDS``. ``"default"`` keeps the running
262 torch/torch_npu device backend. ``"dvm"`` selects torch_npu's DVM
263 backend and requires ``inductor_mode`` to be ``"regional"`` or
264 ``"full"``, torch >= 2.10, and ``TORCHINDUCTOR_NPU_BACKEND=dvm``
265 set before ``torch_npu`` is imported. Graph mode only declares DVM
266 support for torch 2.10+; older builds keep the default backend.
267 inductor_configs: Optional Inductor config overrides passed to the
268 compiled regions (keys validated by ``torch._inductor.config``),
269 e.g. ``{"reorder_for_peak_memory": True}``. ``"full"`` mode
270 always sets ``reorder_for_peak_memory=True`` unless overridden.
271 ac_mode: Static-graph activation checkpointing mode for
272 ``ActivationCheckpointPass``, one of ``AC_MODES``. Mirrors the
273 dynamic ``ActivationCheckpointConfig.mode`` vocabulary and is
274 projected from a trainer config's ``activation_checkpoint``
275 section by ``build_pass_config_from_trainer_config``. ``"off"``
276 (default) saves every forward activation; ``"full"`` recomputes
277 every checkpoint-scoped module op in backward; ``"selective"``
278 recomputes only the eager-aligned module/region targets carried by
279 ``ac_selective_*`` and saves everything else.
280 ac_selective_recompute_regions: Layer-relative selective recompute
281 targets as ``(module_path, layer_indices)`` pairs, mirroring
282 ``activation_checkpoint.selective.recompute``. Only
283 ``ac_mode="selective"`` may set this.
284 ac_selective_recompute_modules: Model-root-relative selective recompute
285 module paths, mirroring model-level selective ``recompute``
286 targets. Only ``ac_mode="selective"`` may set this.
287 ac_layer_count: Optional layer selector: checkpoint only the first
288 ``ac_layer_count`` discovered transformer blocks (the same
289 HuggingFace-marker discovery the eager path uses). Mutually
290 exclusive with ``ac_layer_indices`` and with target-based
291 ``"selective"``.
292 ac_layer_indices: Optional explicit zero-based indices into the
293 discovered transformer blocks; only nodes inside the selected
294 blocks recompute. Mutually exclusive with ``ac_layer_count`` and
295 with target-based ``"selective"``.
296 ac_save_forward_all_gather: Save forward (TP/SP/CP) all-gathers instead
297 of replaying them during backward recompute. Graph-mode only;
298 defaults to ``True``, so static-graph recompute does not duplicate
299 a forward collective. FSDP parameter all-gathers are inserted after
300 this pass and are unaffected. Set ``False`` to replay the
301 all-gather, trading communication for less retained memory.
302 activation_swap: Reuse the dynamic-graph ``activation_swap`` setting.
303 ``"attention"`` (the only enabled mode) runs ``CpuOffloadPass``:
304 saved activations produced inside ``self_attn`` modules are copied
305 to host memory asynchronously during forward and reloaded before
306 their first backward consumer. ``"none"`` disables offload.
307 offload_budget_gb: Host-memory budget, in GiB per rank, for activations
308 selected by ``CpuOffloadPass``. Tensors are selected largest-first
309 until the budget is exhausted; ``0`` means no budget. Graph-mode
310 only (the eager attention swap has no budget knob). The budget caps
311 offloaded activation bytes, not the pinned host buffer footprint, so
312 size it against the host's free memory to avoid host OOM.
313 offload_prefetch_n_layers: Move each backward reload this many attention
314 regions earlier to overlap H2D copies with preceding backward
315 compute. ``0`` keeps the reload immediately before its consumer.
316 Graph-mode only.
317 aclgraph_mode: NPU joint-graph capture: ``"off"`` (default),
318 ``"static"`` (reject changed replay inputs), or ``"dynamic"``
319 (coordinate recapture across ranks). Host work stays eager.
320 Requires Inductor compilation and PP to be disabled.
321 aclgraph_max_capture_regions: Maximum number of captured device regions.
322 Zero preserves every eligible region. Positive values retain the
323 largest regions by FX node count and leave the rest eager.
324 aclgraph_min_capture_nodes: Minimum FX node count for a complete device
325 region after storage-free admission. Smaller regions stay eager
326 before applying the maximum region budget. Zero disables this filter.
328 Note:
329 ``fsdp_enabled`` / ``pp_enabled`` no longer probe
330 ``torch.distributed``. The distributed-initialized check moved into
331 the respective passes' ``run`` (their original location) so this
332 dataclass stays torch-free and importable anywhere.
333 """
335 enable_overlap: bool = True
336 fsdp_enabled: bool = True
337 fsdp_reshard_after_forward: bool = True
338 fsdp_degree: Optional[int] = None
339 dp_mode: str = "fsdp"
340 dp_replicate_degree: Optional[int] = None
341 pp_enabled: bool = False
342 pp_degree: Optional[int] = None
343 pp_chunks: int = 1
344 pp_microbatch_size: int = 1
345 pp_schedule: str = "gpipe"
346 fsdp_bucketing: bool = False
347 fsdp_bucket_modules: Optional[
348 list[str | list[str]] | tuple[tuple[str, ...], ...]
349 ] = None
350 fsdp_allgather_prefetch: bool = True
351 fsdp_overlap_grad_reduce: bool = True
352 max_in_flight_gb: float = 0.25
353 inductor_mode: str = "off"
354 inductor_backend: str = "default"
355 inductor_configs: Optional[Dict[str, Any]] = None
356 ac_mode: str = "off"
357 ac_layer_count: Optional[int] = None
358 ac_layer_indices: Optional[List[int]] = None
359 ac_selective_recompute_regions: Optional[List[Tuple[str, List[int]]]] = None
360 ac_selective_recompute_modules: Optional[List[str]] = None
361 ac_save_forward_all_gather: bool = True
362 activation_swap: str = "none"
363 offload_budget_gb: float = 64.0
364 offload_prefetch_n_layers: int = 1
365 aclgraph_mode: str = "off"
366 aclgraph_max_capture_regions: int = 0
367 aclgraph_min_capture_nodes: int = 0
369 def __post_init__(self) -> None:
370 self.dp_mode = normalize_dp_mode(self.dp_mode)
371 self.validate()
373 def validate(self) -> None:
374 """Sanity-check invariants; also re-run after manual field mutation.
376 Raises:
377 ValueError: On a non-positive explicit ``fsdp_degree`` /
378 ``pp_degree``, a non-positive ``pp_microbatch_size``, an
379 unknown ``pp_schedule`` / ``dp_mode``, or a non-positive
380 ``dp_replicate_degree``, or ``pp_chunks > 1`` with a
381 non-interleaved schedule, or an invalid activation
382 checkpointing mode / layer selector.
383 """
384 self._validate_flags()
385 self._validate_dp()
386 self._validate_pp()
387 self._validate_ac()
388 self._validate_offload()
389 self._validate_aclgraph()
391 def _validate_ac(self) -> None:
392 """Validate the activation checkpointing mode and layer selectors."""
393 if not isinstance(self.ac_mode, str) or self.ac_mode not in AC_MODES:
394 raise ValueError(f"ac_mode must be one of {AC_MODES}, got {self.ac_mode!r}")
395 if not isinstance(self.ac_save_forward_all_gather, bool):
396 raise ValueError("ac_save_forward_all_gather must be a bool")
397 self._validate_ac_layer_count()
398 self._validate_ac_layer_indices()
399 if self.ac_layer_count is not None and self.ac_layer_indices is not None:
400 raise ValueError(
401 "ac_layer_count and ac_layer_indices are mutually exclusive; "
402 "set exactly one"
403 )
404 self._validate_ac_selective()
406 def _validate_ac_selective(self) -> None:
407 """Validate eager-aligned selective module/region targets."""
408 regions = self.ac_selective_recompute_regions
409 modules = self.ac_selective_recompute_modules
410 if self.ac_mode != "selective":
411 if regions is not None or modules is not None:
412 raise ValueError(
413 "ac_selective_recompute_regions / "
414 "ac_selective_recompute_modules require ac_mode='selective'"
415 )
416 return
417 if self.ac_layer_count is not None or self.ac_layer_indices is not None:
418 raise ValueError(
419 "ac_mode='selective' selects layers through its targets; "
420 "ac_layer_count / ac_layer_indices are not allowed"
421 )
422 if not regions and not modules:
423 raise ValueError(
424 "ac_mode='selective' requires at least one recompute target in "
425 "ac_selective_recompute_regions or ac_selective_recompute_modules"
426 )
427 for region in regions or ():
428 self._validate_selective_region(region)
429 for module_path in modules or ():
430 self._validate_selective_module(module_path)
432 @staticmethod
433 def _validate_selective_region(region: Any) -> None:
434 """Validate one ``(module_path, layer_indices)`` selective target."""
435 if not isinstance(region, (list, tuple)) or len(region) != 2:
436 raise ValueError(
437 "ac_selective_recompute_regions must be a non-empty list of "
438 f"(module_path, layer_indices) pairs, got {region!r}"
439 )
440 module_path, layer_indices = region
441 if not isinstance(module_path, str) or not module_path:
442 raise ValueError(
443 "ac_selective_recompute_regions entry must name a module path, "
444 f"got {region!r}"
445 )
446 if not isinstance(layer_indices, (list, tuple)) or not layer_indices:
447 raise ValueError(
448 "ac_selective_recompute_regions entry must list layer indices, "
449 f"got {region!r}"
450 )
451 for index in layer_indices:
452 if isinstance(index, bool) or not isinstance(index, int) or index < 0:
453 raise ValueError(
454 "ac_selective_recompute_regions layer indices must be "
455 f"non-negative integers, got {region!r}"
456 )
458 @staticmethod
459 def _validate_selective_module(module_path: Any) -> None:
460 """Validate one model-root selective module target."""
461 if not isinstance(module_path, str) or not module_path:
462 raise ValueError(
463 "ac_selective_recompute_modules must be a non-empty list of "
464 f"module paths, got {module_path!r}"
465 )
467 def _validate_ac_layer_count(self) -> None:
468 """Validate the optional prefix layer selector."""
469 if self.ac_layer_count is not None and (
470 isinstance(self.ac_layer_count, bool)
471 or not isinstance(self.ac_layer_count, int)
472 or self.ac_layer_count < 0
473 ):
474 raise ValueError(
475 "ac_layer_count must be None or a non-negative integer, "
476 f"got {self.ac_layer_count!r}"
477 )
479 def _validate_ac_layer_indices(self) -> None:
480 """Validate the optional explicit layer index selector."""
481 indices = self.ac_layer_indices
482 if indices is None:
483 return
484 invalid = (
485 not isinstance(indices, list)
486 or not indices
487 or any(
488 isinstance(index, bool) or not isinstance(index, int) or index < 0
489 for index in indices
490 )
491 )
492 if invalid:
493 raise ValueError(
494 "ac_layer_indices must be None or a non-empty list of "
495 f"non-negative integers, got {indices!r}"
496 )
497 if len(set(indices)) != len(indices):
498 raise ValueError(
499 f"ac_layer_indices must not contain duplicates, got {indices!r}"
500 )
502 def _validate_offload(self) -> None:
503 """Validate graph-mode activation offload (dynamic attention-swap reuse)."""
504 if (
505 not isinstance(self.activation_swap, str)
506 or self.activation_swap not in ACTIVATION_SWAP_MODES
507 ):
508 raise ValueError(
509 "activation_swap must be one of "
510 f"{ACTIVATION_SWAP_MODES}, got {self.activation_swap!r}"
511 )
512 if self.activation_swap == "none":
513 return
514 if self.ac_mode != "off":
515 raise ValueError(
516 "activation_swap='attention' is incompatible with graph-mode "
517 "activation checkpointing; the dynamic path enforces the same "
518 "combination rule"
519 )
520 if self.pp_enabled:
521 raise ValueError(
522 "activation_swap='attention' does not support pipeline "
523 "parallelism; the dynamic path enforces the same rule"
524 )
525 value = self.offload_budget_gb
526 if (
527 isinstance(value, bool)
528 or not isinstance(value, (int, float))
529 or not math.isfinite(value)
530 or value < 0
531 ):
532 raise ValueError("offload_budget_gb must be a finite non-negative number")
533 prefetch = self.offload_prefetch_n_layers
534 if isinstance(prefetch, bool) or not isinstance(prefetch, int) or prefetch < 0:
535 raise ValueError("offload_prefetch_n_layers must be a non-negative integer")
537 def _validate_aclgraph(self) -> None:
538 """Validate capture mode and the initial joint-FX execution boundary."""
539 count = self.aclgraph_max_capture_regions
540 if isinstance(count, bool) or not isinstance(count, int) or count < 0:
541 raise ValueError("aclgraph_max_capture_regions must be a non-negative integer")
542 minimum = self.aclgraph_min_capture_nodes
543 if isinstance(minimum, bool) or not isinstance(minimum, int) or minimum < 0:
544 raise ValueError("aclgraph_min_capture_nodes must be a non-negative integer")
545 if self.aclgraph_mode not in ACLGRAPH_MODES:
546 raise ValueError(f"aclgraph_mode must be one of {ACLGRAPH_MODES}, got {self.aclgraph_mode!r}")
547 if self.aclgraph_mode != "off" and (self.pp_enabled or self.inductor_mode != "off"):
548 raise ValueError("ACLGraph currently requires pp_enabled=False and inductor_mode='off'")
550 def _validate_flags(self) -> None:
551 """Validate boolean flags and the overlap memory budget."""
552 for name in (
553 "fsdp_bucketing",
554 "fsdp_allgather_prefetch",
555 "fsdp_overlap_grad_reduce",
556 ):
557 value = getattr(self, name)
558 if not isinstance(value, bool):
559 raise ValueError(f"{name} must be a bool")
560 if self.fsdp_bucket_modules is not None and not isinstance(
561 self.fsdp_bucket_modules, (list, tuple)
562 ):
563 raise ValueError(
564 "fsdp_bucket_modules must be None or a list/tuple of module groups"
565 )
566 value = self.max_in_flight_gb
567 if (
568 isinstance(value, bool)
569 or not isinstance(value, (int, float))
570 or not math.isfinite(value)
571 or value < 0
572 ):
573 raise ValueError("max_in_flight_gb must be a finite non-negative number")
574 self._validate_inductor()
576 def _validate_inductor(self) -> None:
577 """Validate the Inductor compilation mode and config overrides."""
578 if not isinstance(self.inductor_mode, str) or (
579 self.inductor_mode.lower() not in INDUCTOR_MODES
580 ):
581 raise ValueError(
582 f"inductor_mode must be one of {INDUCTOR_MODES}, "
583 f"got {self.inductor_mode!r}"
584 )
585 # Canonicalize to one spelling so the pass's mode dispatch cannot be
586 # defeated by an accepted-but-unnormalized value like "FULL".
587 self.inductor_mode = self.inductor_mode.lower()
588 if not isinstance(self.inductor_backend, str) or (
589 self.inductor_backend.lower() not in INDUCTOR_BACKENDS
590 ):
591 raise ValueError(
592 f"inductor_backend must be one of {INDUCTOR_BACKENDS}, "
593 f"got {self.inductor_backend!r}"
594 )
595 self.inductor_backend = self.inductor_backend.lower()
596 if self.inductor_backend == "dvm" and self.inductor_mode == "off":
597 raise ValueError(
598 "inductor_backend='dvm' requires inductor_mode='regional' or "
599 "'full'; DVM is a terminal Inductor backend"
600 )
601 if self.inductor_configs is not None and (
602 not isinstance(self.inductor_configs, dict)
603 or not all(isinstance(key, str) for key in self.inductor_configs)
604 ):
605 raise ValueError(
606 "inductor_configs must be None or a dict of "
607 "torch._inductor.config option names (str) to values"
608 )
610 def _validate_dp(self) -> None:
611 """Validate the tensor-parallel and data-parallel degrees."""
612 if self.fsdp_degree is not None and self.fsdp_degree < 1:
613 raise ValueError(
614 f"fsdp_degree must be None or a positive int, got {self.fsdp_degree}"
615 )
616 if self.dp_mode not in DP_MODES:
617 raise ValueError(
618 f"dp_mode must be one of {DP_MODES} "
619 f"(aliases: {tuple(_DP_MODE_ALIASES)}), got {self.dp_mode!r}"
620 )
621 if self.dp_replicate_degree is not None and self.dp_replicate_degree < 1:
622 raise ValueError(
623 f"dp_replicate_degree must be None or a positive int, "
624 f"got {self.dp_replicate_degree}"
625 )
627 def _validate_pp(self) -> None:
628 """Validate the pipeline-parallel degree, microbatch size, and schedule."""
629 if self.pp_degree is not None and self.pp_degree < 1:
630 raise ValueError(
631 f"pp_degree must be None or a positive int, got {self.pp_degree}"
632 )
633 if self.pp_chunks < 1:
634 raise ValueError(f"pp_chunks must be >= 1, got {self.pp_chunks}")
635 if self.pp_microbatch_size < 1:
636 raise ValueError(
637 f"pp_microbatch_size must be >= 1, got {self.pp_microbatch_size}"
638 )
639 if not isinstance(self.pp_schedule, str) or (
640 self.pp_schedule.lower() not in PP_SCHEDULES
641 ):
642 raise ValueError(
643 f"pp_schedule must be one of {PP_SCHEDULES}, got {self.pp_schedule!r}"
644 )
645 if (
646 self.pp_chunks > 1
647 and self.pp_schedule.lower() not in _INTERLEAVED_SCHEDULES
648 ):
649 raise ValueError(
650 f"pp_chunks={self.pp_chunks} requires an interleaved schedule "
651 f"(one of {_INTERLEAVED_SCHEDULES}), got {self.pp_schedule!r}"
652 )
655def _selective_recompute_targets(
656 selective_config: Any,
657) -> Tuple[Optional[List[Tuple[str, List[int]]]], Optional[List[str]]]:
658 """Normalize a selective config's recompute targets for the graph pass."""
659 if selective_config is None:
660 return None, None
661 regions = [
662 (region.module_path, list(region.layers))
663 for region in getattr(selective_config, "recompute_regions", ())
664 ]
665 modules = [
666 target.module_path
667 for target in getattr(selective_config, "recompute_modules", ())
668 ]
669 return (regions or None), (modules or None)
672def _full_recompute_layer_indices(full_config: Any) -> Optional[List[int]]:
673 """Read the full-mode layer selector from a full config.
675 Prefers the normalized ``recompute_layers`` field. Duck-typed configs that
676 only carry the raw ``recompute_layer`` list are accepted when it already
677 holds integer indices; range strings must go through
678 ``FullCheckpointConfig`` so ``recompute_layers`` is normalized first.
679 """
680 if full_config is None:
681 return None
682 recompute_layers = getattr(full_config, "recompute_layers", None)
683 if recompute_layers is not None:
684 return list(recompute_layers) or None
685 recompute_layer = getattr(full_config, "recompute_layer", None)
686 if not recompute_layer:
687 return None
688 if any(
689 isinstance(index, bool) or not isinstance(index, int)
690 for index in recompute_layer
691 ):
692 raise ValueError(
693 "activation_checkpoint.full.recompute_layer contains ranges; pass a "
694 "resolved FullCheckpointConfig so recompute_layers is normalized"
695 )
696 return list(recompute_layer)
699def _project_activation_checkpoint(
700 ac_config: Any,
701) -> Tuple[
702 str,
703 Optional[List[int]],
704 Optional[List[Tuple[str, List[int]]]],
705 Optional[List[str]],
706]:
707 """Project the trainer AC section onto graph-mode AC fields.
709 Returns ``(ac_mode, ac_layer_indices, recompute_regions,
710 recompute_modules)``; see ``build_pass_config_from_trainer_config`` for the
711 projection contract.
712 """
713 if ac_config is None or getattr(ac_config, "mode", None) in (None, "off"):
714 return "off", None, None, None
715 ac_mode = ac_config.mode
716 if ac_mode == "hybrid":
717 raise ValueError(
718 "activation_checkpoint.mode=hybrid is not supported in graph "
719 "mode; use mode=full or mode=selective"
720 )
721 ac_layer_indices = None
722 ac_regions = None
723 ac_modules = None
724 if ac_mode == "full":
725 full_config = getattr(ac_config, "full", None)
726 ac_layer_indices = _full_recompute_layer_indices(full_config)
727 if _has_full_exclusions(full_config):
728 _LOG.warning(
729 "activation_checkpoint.full.exclude_region is not supported in "
730 "graph mode; excluded modules will still be recomputed."
731 )
732 if ac_mode == "selective":
733 selective_config = getattr(ac_config, "selective", None)
734 ac_regions, ac_modules = _selective_recompute_targets(selective_config)
735 if getattr(selective_config, "swap_regions", ()):
736 _LOG.warning(
737 "activation_checkpoint.selective.swap is not supported in "
738 "graph mode yet; swap targets will be ignored."
739 )
740 if not ac_regions and not ac_modules:
741 raise ValueError(
742 "activation_checkpoint.selective requires at least one "
743 "recompute target in graph mode; selective.swap-only "
744 "configs are not supported yet"
745 )
746 if getattr(ac_config, "swap_inputs", False):
747 _LOG.warning(
748 "activation_checkpoint.swap_inputs is not supported in graph "
749 "mode; input swapping will be disabled."
750 )
751 if getattr(ac_config, "allow_cache_entry_mutation", False):
752 _LOG.info(
753 "activation_checkpoint.allow_cache_entry_mutation has no "
754 "effect in graph mode; ignoring it."
755 )
756 return ac_mode, ac_layer_indices, ac_regions, ac_modules
759def _has_full_exclusions(full_config: Any) -> bool:
760 """Return whether a full config declares save/swap exclusion regions."""
761 if full_config is None:
762 return False
763 return bool(
764 getattr(full_config, "save_regions", ())
765 or getattr(full_config, "swap_regions", ())
766 )
769def build_pass_config_from_trainer_config(
770 config: Any,
771 *,
772 fsdp_enabled: Optional[bool] = None,
773 enable_overlap: bool = False,
774) -> PassConfig:
775 """Project trainer topology intent onto graph-mode pass config.
777 This helper stays in the pass-config module because it computes the
778 graph-pass surface from the trainer topology without altering runtime
779 objects. Accepting ``Any`` keeps this module importable without the
780 trainer package. Only fields the graph passes actually consume are
781 projected: TP / SP / LP topology (``accelerator.tp_size`` /
782 ``sequence_parallel`` / ``loss_parallel``) is owned by the automodel
783 flow and deliberately not copied.
785 The dynamic ``activation_checkpoint`` section is projected onto the
786 static-graph AC fields: ``mode`` becomes ``ac_mode``, the full-mode
787 ``recompute_layer`` selector becomes ``ac_layer_indices``, and
788 ``selective.recompute`` targets become ``ac_selective_recompute_*`` so
789 graph selective recomputes the same modules as the eager path.
790 ``mode=hybrid`` has no static-graph equivalent (graph AC applies one
791 policy per scope) and is rejected. ``selective.swap`` targets have no
792 graph-mode equivalent yet and are ignored with a warning.
793 ``full.exclude_region`` save/swap regions are likewise not projected, so
794 graph full mode recomputes those modules too and warns when the config
795 declared exclusions.
796 ``swap_inputs`` and ``allow_cache_entry_mutation`` have no
797 static-graph counterpart (no eager checkpoint cache) and are ignored
798 with a warning when set, mirroring the dynamic compile path. The
799 top-level dynamic ``activation_swap`` field is projected onto
800 ``activation_swap`` so graph mode reuses the eager attention-swap
801 configuration (the graph pass owns offload instead of the eager wrapper).
802 The graph-only ``compile.offload_budget_gb`` and
803 ``compile.offload_prefetch_n_layers`` knobs are projected too, so Trainer
804 YAML can tune the offload budget instead of being pinned to the 64 GiB
805 default. ``compile.dvm`` selects the DVM Inductor backend and upgrades the
806 terminal pass to ``regional`` mode; see ``PassConfig.inductor_backend``.
808 Args:
809 config: Trainer topology (e.g. a ``TrainerConfig``); only the
810 ``fsdp_config``, ``compile`` and ``activation_checkpoint``
811 surfaces are read.
812 fsdp_enabled: Overrides the sharded-DP intent derived from
813 ``config.fsdp_config`` when provided.
814 enable_overlap: Value for the legacy ``AutoOverlapPass`` switch.
816 Returns:
817 The graph-mode ``PassConfig`` for this trainer topology.
818 """
819 compile_config = getattr(config, "compile", None)
820 if fsdp_enabled is None:
821 fsdp_enabled = (
822 config.fsdp_config.dp_shard_size > 1
823 or config.fsdp_config.edp_shard_size > 1
824 )
825 fsdp_degree = config.fsdp_config.dp_shard_size if fsdp_enabled else None
827 (
828 ac_mode,
829 ac_layer_indices,
830 ac_selective_recompute_regions,
831 ac_selective_recompute_modules,
832 ) = _project_activation_checkpoint(
833 getattr(config, "activation_checkpoint", None)
834 )
836 dvm_enabled = getattr(compile_config, "dvm", False)
837 if dvm_enabled is None:
838 dvm_enabled = False
839 if not isinstance(dvm_enabled, bool):
840 raise ValueError(f"compile.dvm must be a bool, got {dvm_enabled!r}")
841 return PassConfig(
842 enable_overlap=enable_overlap,
843 fsdp_enabled=fsdp_enabled,
844 fsdp_degree=fsdp_degree,
845 fsdp_reshard_after_forward=getattr(
846 config.fsdp_config, "reshard_after_forward", True
847 ),
848 fsdp_allgather_prefetch=getattr(
849 compile_config, "fsdp_allgather_prefetch", True
850 ),
851 fsdp_overlap_grad_reduce=getattr(
852 compile_config, "fsdp_overlap_grad_reduce", True
853 ),
854 max_in_flight_gb=getattr(compile_config, "max_in_flight_gb", 0.25),
855 inductor_mode="regional" if dvm_enabled else "off",
856 inductor_backend="dvm" if dvm_enabled else "default",
857 ac_mode=ac_mode,
858 ac_layer_count=None,
859 ac_layer_indices=ac_layer_indices,
860 ac_selective_recompute_regions=ac_selective_recompute_regions,
861 ac_selective_recompute_modules=ac_selective_recompute_modules,
862 activation_swap=getattr(config, "activation_swap", "none"),
863 offload_budget_gb=getattr(compile_config, "offload_budget_gb", 64.0),
864 offload_prefetch_n_layers=getattr(
865 compile_config, "offload_prefetch_n_layers", 1
866 ),
867 aclgraph_mode=getattr(compile_config, "aclgraph_mode", "off"),
868 aclgraph_max_capture_regions=getattr(compile_config, "aclgraph_max_capture_regions", 0),
869 aclgraph_min_capture_nodes=getattr(compile_config, "aclgraph_min_capture_nodes", 0),
870 )