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

257 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""" 

19Inductor Compilation Pass - terminal backend compilation of the joint graph. 

20 

21The pass lowers the (already partitioned and overlapped) joint FX graph to 

22TorchInductor kernels via ``torch.fx.passes.regional_inductor``, which scoops 

23nodes annotated with ``meta["custom"]["compile_with_inductor"]`` into regions 

24and compiles each region with ``torch._inductor.standalone_compile``. This 

25brings kernel fusion, c10d functionalization, PG unboxing and Inductor caching 

26to the graph-mode stack without touching eager semantics. 

27 

28Modes (``PassConfig.inductor_mode``): 

29 

30- ``"off"`` (default): the pass is not added to the pipeline. 

31- ``"regional"``: tag functional compute nodes as compile regions while 

32 keeping communication (``_c10d_functional`` collectives + ``wait_tensor``) 

33 and side-effectful nodes (e.g. the FSDP reshard storage free) eager. This 

34 preserves the comm scheduling surface for the overlap passes. 

35- ``"full"``: tag every node so the whole graph compiles as one region 

36 (c10d functional collectives included), mirroring torchtitan's 

37 ``full_inductor_compilation_pass``. 

38 

39Pipeline-parallel support: when ``PpPass`` has already split the joint graph, 

40the outer graph is a ``call_module`` stub around the pipeline schedule. The 

41compute lives in the schedule's per-virtual-stage forward/backward subgraphs, 

42so the pass detects the stub and compiles every stage subgraph independently 

43(both modes), instead of compiling — or rejecting — the stub. Cross-stage 

44fusion is inherently impossible; the schedule's P2P stays outside the 

45compiled regions. Unknown ``call_module`` graphs are still rejected. PP 

46forward subgraphs export saved values verbatim, which can include multi-result 

47ops (``nll_loss_forward``); their nested output is split into ``getitem`` 

48leaves for compilation and rebuilt by a thin wrapper, because AOTAutograd's 

49regional path requires flat outputs. 

50 

51Numerics policy: ``inductor.eager_numerics.division_rounding`` is forced on 

52(where the running torch provides it, 2.11+) so compiled regions stay 

53bitwise-equal to eager execution (same guarantee torchtitan relies on). 

54 

55Compatibility: ``torch.fx.passes.regional_inductor`` only exists in newer 

56torch builds (it is absent from 2.6 / 2.7 / 2.9). On such builds the pass logs 

57a warning, leaves the graph untouched and records ``inductor_compiled = 

58"unavailable"`` instead of raising ``ModuleNotFoundError``. 

59 

60Contract notes: 

61 

62- The pass must run LAST: after compilation the FX graph is a thin wrapper 

63 around the compiled callable and is no longer authoritative for 

64 graph-level passes. PP stage subgraphs are compiled through the schedule's 

65 ``map_stage_graphs`` hook, so the stub remains the outer entry point. 

66- ``regional_inductor`` switches a compiled graph module to the boxed calling 

67 convention (``forward(self, args_list)``); the pass resets it to the 

68 default positional convention so ``graph_module(*flat_inputs)`` (and the 

69 schedule's direct ``fwd_gm(*args)`` / ``bwd_gm(*args)`` calls) keep 

70 working unchanged. 

71- The graph must be traced with ``make_fx`` (placeholders carry fake 

72 ``meta["val"]``). Nodes inserted by earlier passes lack fake values, so the 

73 pass first re-propagates them with ``FakeTensorProp`` using the graph's own 

74 ``FakeTensorMode``. 

75""" 

76 

77__all__ = ["InductorPass", "validate_inductor_backend"] 

78 

79import importlib 

80import importlib.util 

81import logging 

82import operator 

83import re 

84from typing import Any, Dict, Optional, Sequence 

85 

86import torch 

87from torch import fx, nn 

88from torch._subclasses import FakeTensor 

89from torch.fx.graph import CodeGen 

90from torch.fx.node import _side_effectful_functions 

91 

92from ..pass_config import PassConfig 

93from .base import GraphPass 

94from .graph_metadata import propagate_fake_values 

95 

96_LOG = logging.getLogger(__name__) 

97 

98# Communication nodes stay outside compiled regions in "regional" mode. The 

99# launch/wait pair is the scheduling surface the overlap passes reorder; a 

100# compiled region would fuse a collective into surrounding compute and remove 

101# the explicit reorder point. "full" mode does compile them (Inductor's c10d 

102# functionalization supports that), matching torchtitan's full pass. 

103# ``str(OpOverload)`` has no ``torch.ops.`` prefix, so match the bare namespace. 

104_C10D_FUNCTIONAL_NS = "_c10d_functional." 

105 

106# Meta key recording that (and how) a graph module was compiled. 

107_INDUCTOR_COMPILED_META = "inductor_compiled" 

108 

109# Meta key recording the Inductor backend requested for the compiled graph. 

110_INDUCTOR_BACKEND_META = "inductor_backend" 

111 

112# Meta value when the running torch predates regional_inductor (<= 2.9.x). 

113_INDUCTOR_UNAVAILABLE = "unavailable" 

114 

115# Graph mode only declares DVM support on torch builds that ship regional 

116# Inductor compilation. Older torch/torch_npu combinations use eager DVM 

117# (TORCH_NPU_LAZY_FUSION) instead. 

118_DVM_MIN_TORCH_VERSION = (2, 10) 

119 

120 

121def _regional_inductor_available() -> bool: 

122 """Whether this torch build ships ``torch.fx.passes.regional_inductor``. 

123 

124 The module first appeared after torch 2.9, while this project still 

125 supports 2.6 / 2.7 / 2.9. Importing it lazily here lets the pass degrade to 

126 a documented no-op instead of raising ``ModuleNotFoundError`` on those 

127 builds. 

128 """ 

129 try: 

130 importlib.import_module("torch.fx.passes.regional_inductor") 

131 except ImportError: 

132 return False 

133 return True 

134 

135 

136def _torch_version_tuple() -> tuple[int, int, int]: 

137 """Return ``(major, minor, patch)`` parsed from ``torch.__version__``.""" 

138 match = re.match(r"(\d+)\.(\d+)(?:\.(\d+))?", torch.__version__) 

139 if match is None: 

140 raise ValueError(f"cannot parse torch version {torch.__version__!r}") 

141 major, minor, patch = match.groups(default="0") 

142 return int(major), int(minor), int(patch) 

143 

144 

145def _loaded_npu_inductor_backend() -> Optional[str]: 

146 """Return torch_npu's loaded Inductor backend, or None without torch_npu. 

147 

148 ``_InductorNpuRegistry`` lives in ``torch_npu.utils._dynamo`` (it is not 

149 re-exported by ``torch_npu._inductor``). torch_npu loads the heavy Inductor 

150 backend lazily, so trigger the registry once to apply the configured 

151 backend before reading it. 

152 """ 

153 try: 

154 from torch_npu.utils._dynamo import ( # pylint: disable=import-outside-toplevel 

155 _InductorNpuRegistry, 

156 ) 

157 except ImportError: 

158 try: 

159 from torch_npu._inductor import ( # pylint: disable=import-outside-toplevel 

160 _InductorNpuRegistry, 

161 ) 

162 except ImportError: 

163 return None 

164 register = getattr(_InductorNpuRegistry, "register_inductor_npu", None) 

165 if register is not None: 

166 register() 

167 return getattr(_InductorNpuRegistry, "_loaded_backend", None) 

168 

169 

170_DVM_IMPORT = "from torch_npu._inductor import dvm" 

171_DVM_WRAPPER_PATCHED = "_hyper_parallel_dvm_autotune_patched" 

172 

173 

174def _patch_dvm_autotune_scope() -> None: 

175 """Make torch_npu's DVM runtime available to compile-time autotune. 

176 

177 torch_npu registers the DVM import through ``wrapper.add_import_once``, 

178 which writes to ``kernel_autotune_calls``. That section executes *after* 

179 ``kernel_autotune_defs``, but DVM builder functions reference ``dvm`` in 

180 their decorators at definition time. ``standalone_compile`` also forces 

181 ``autotune_at_compile_time=True``, so hoist the import into the autotune 

182 defs header. 

183 

184 The base autotune header also imports torch's ``AsyncCompile``, while NPU 

185 kernels (including the MLIR fallback used by DVM) call the NPU-only 

186 ``import_fx`` method. Rebind the instance to ``CustomAsyncCompile`` in the 

187 same scope. Idempotent; only applied when the DVM backend is requested. 

188 """ 

189 try: 

190 from torch_npu._inductor.ascend_npu_ir.ascend_npu_ir import ( # pylint: disable=import-outside-toplevel 

191 codecache as npu_codecache, 

192 ) 

193 from torch_npu._inductor.ascend_npu_ir.ascend_npu_ir.npu.codegen.wrapper import ( # pylint: disable=import-outside-toplevel 

194 NpuMlirWrapperCodeGen, 

195 ) 

196 except ImportError: 

197 _LOG.warning( 

198 "InductorPass: cannot patch the torch_npu DVM autotune scope " 

199 "because the expected ascend_npu_ir modules are missing; compiled " 

200 "DVM kernels may fail to resolve 'dvm' during compile-time autotune." 

201 ) 

202 return 

203 

204 if getattr(NpuMlirWrapperCodeGen, _DVM_WRAPPER_PATCHED, False): 

205 return 

206 original = NpuMlirWrapperCodeGen.write_kernel_autotune_defs_header 

207 has_custom_async_compile = hasattr(npu_codecache, "CustomAsyncCompile") 

208 if not has_custom_async_compile: 

209 _LOG.warning( 

210 "InductorPass: %s does not expose CustomAsyncCompile; DVM kernels " 

211 "keep torch's AsyncCompile, which lacks the NPU-only import_fx used " 

212 "by MLIR fallback kernels.", 

213 npu_codecache.__name__, 

214 ) 

215 

216 def _write_kernel_autotune_defs_header(self) -> None: 

217 """Write NPU/DVM imports before any autotuned kernel definition.""" 

218 original(self) 

219 self.kernel_autotune_defs.writeline(_DVM_IMPORT) 

220 if has_custom_async_compile: 

221 self.kernel_autotune_defs.writeline( 

222 f"from {npu_codecache.__name__} import CustomAsyncCompile" 

223 ) 

224 self.kernel_autotune_defs.writeline("async_compile = CustomAsyncCompile()") 

225 

226 NpuMlirWrapperCodeGen.write_kernel_autotune_defs_header = ( 

227 _write_kernel_autotune_defs_header 

228 ) 

229 setattr(NpuMlirWrapperCodeGen, _DVM_WRAPPER_PATCHED, True) 

230 

231 

232def _validate_dvm_backend() -> None: 

233 """Fail fast when the requested DVM Inductor backend is not active. 

234 

235 Raises: 

236 ValueError: When torch predates 2.10, regional Inductor compilation is 

237 unavailable, torch_npu is not importable, or torch_npu loaded a 

238 backend other than ``dvm``. 

239 """ 

240 version = _torch_version_tuple() 

241 if version[:2] < _DVM_MIN_TORCH_VERSION: 

242 raise ValueError( 

243 "inductor_backend='dvm' requires torch >= " 

244 f"{_DVM_MIN_TORCH_VERSION[0]}.{_DVM_MIN_TORCH_VERSION[1]}; " 

245 f"found torch {torch.__version__}" 

246 ) 

247 if not _regional_inductor_available(): 

248 raise ValueError( 

249 "inductor_backend='dvm' requires " 

250 "torch.fx.passes.regional_inductor (torch >= 2.10)" 

251 ) 

252 loaded = _loaded_npu_inductor_backend() 

253 if loaded is None: 

254 try: 

255 torch_npu_available = importlib.util.find_spec("torch_npu") is not None 

256 except (ImportError, ValueError): 

257 torch_npu_available = False 

258 if not torch_npu_available: 

259 raise ValueError( 

260 "inductor_backend='dvm' requires torch_npu; install a " 

261 "torch_npu build that provides the DVM Inductor backend" 

262 ) 

263 raise ValueError( 

264 "inductor_backend='dvm' could not read torch_npu's loaded Inductor " 

265 "backend; set TORCHINDUCTOR_NPU_BACKEND=dvm before importing torch, " 

266 "torch_npu, or hyper_parallel" 

267 ) 

268 if loaded != "dvm": 

269 raise ValueError( 

270 "inductor_backend='dvm' requires TORCHINDUCTOR_NPU_BACKEND=dvm " 

271 "to be set before importing torch, torch_npu, or hyper_parallel; " 

272 f"torch_npu loaded backend {loaded!r}" 

273 ) 

274 _patch_dvm_autotune_scope() 

275 

276 

277def validate_inductor_backend(pass_config: PassConfig) -> None: 

278 """Validate the configured terminal Inductor backend. 

279 

280 Args: 

281 pass_config: Graph-mode configuration carrying ``inductor_backend``. 

282 

283 Raises: 

284 ValueError: When the DVM backend is requested but unavailable. 

285 """ 

286 if pass_config.inductor_backend == "dvm": 

287 _validate_dvm_backend() 

288 

289 

290def _get_fake_mode_from_gm(gm: fx.GraphModule) -> Optional[Any]: 

291 """Return the ``FakeTensorMode`` shared by the graph's placeholder vals.""" 

292 for node in gm.graph.nodes: 

293 if node.op == "placeholder": 

294 val = node.meta.get("val") 

295 if isinstance(val, FakeTensor): 

296 return val.fake_mode 

297 return None 

298 

299 

300def _placeholder_fake_args(gm: fx.GraphModule) -> list: 

301 """Return the placeholder values in order, requiring fake ``meta["val"]``.""" 

302 args = [] 

303 for node in gm.graph.find_nodes(op="placeholder"): 

304 val = node.meta.get("val") 

305 if val is None: 

306 raise ValueError( 

307 f"InductorPass requires a fake meta['val'] on placeholder " 

308 f"'{node.name}' to size compiled regions; the graph must be " 

309 f"make_fx-traced (PP stage subgraphs copy their placeholders' " 

310 f"meta from the joint graph)" 

311 ) 

312 args.append(val) 

313 return args 

314 

315 

316def _propagate_fake_vals(gm: fx.GraphModule, model: Optional[nn.Module] = None) -> fx.GraphModule: 

317 """Fill ``meta["val"]`` on nodes inserted after tracing (FSDP collectives, 

318 pad views, reshard frees) so ``regional_inductor`` can size each region. 

319 

320 Propagation reuses the graph's own ``FakeTensorMode``: placeholder vals 

321 already belong to it and mixing modes is unsupported by ``FakeTensorProp``. 

322 Side-effectful free nodes return ``None`` and legitimately carry no val. 

323 """ 

324 fake_mode = _get_fake_mode_from_gm(gm) 

325 if fake_mode is None: 

326 raise ValueError( 

327 "InductorPass requires a make_fx-traced graph whose placeholders " 

328 "carry fake meta['val'] tensors" 

329 ) 

330 fake_args = _placeholder_fake_args(gm) 

331 return propagate_fake_values(gm, tuple(fake_args), model) 

332 

333 

334def _node_is_comm(node: fx.Node) -> bool: 

335 """Whether the node is a functional collective or its wait.""" 

336 return str(node.target).startswith(_C10D_FUNCTIONAL_NS) 

337 

338 

339def _node_is_side_effectful(node: fx.Node) -> bool: 

340 """Whether the node targets a function registered as side-effectful. 

341 

342 ``FSDPPass`` registers the reshard storage-free op there so DCE keeps it; 

343 compiling such a node would let Inductor drop or defer the free. The 

344 ``ao::`` offload/reload/wait ops are also kept eager: they own a transfer 

345 stream and an event registry outside the compiled region, and rewriting 

346 them as fused kernels would break the host/device synchronization. 

347 """ 

348 if node.op != "call_function": 

349 return False 

350 if node.target in _side_effectful_functions: 

351 return True 

352 return str(node.target).startswith("ao.") 

353 

354 

355def _flatten_nested_outputs( 

356 graph_module: fx.GraphModule, 

357) -> tuple: 

358 """Rewrite tuple/list graph outputs into a flat tuple of leaf values. 

359 

360 AOTAutograd's regional compilation expects flat tensor outputs. The joint 

361 graph is flat, but PP stage forward subgraphs export every value the 

362 backward references verbatim — including multi-result ops such as 

363 ``nll_loss_forward`` — so their output tuple can contain a nested 

364 ``(loss, total_weight)`` segment, which trips AOT's output-spec check. 

365 Splitting nested values into ``getitem`` leaves keeps every region output 

366 flat; the returned spec lets the caller rebuild the original structure 

367 for the schedule / backward subgraph, whose contract is unchanged. 

368 

369 Returns: 

370 ``(spec, graph_module)`` where ``spec`` is ``None`` when the output is 

371 already flat, otherwise a nested marker tree consumed by 

372 ``_rebuild_nested_output``. 

373 """ 

374 graph = graph_module.graph 

375 output = next((n for n in graph.nodes if n.op == "output"), None) 

376 returned = output.args[0] if output is not None else None 

377 if not isinstance(returned, (tuple, list)): 

378 return None, graph_module 

379 if not any( 

380 isinstance(node.meta.get("val"), (tuple, list)) 

381 for node in returned 

382 if isinstance(node, fx.Node) 

383 ): 

384 return None, graph_module 

385 

386 flat_nodes: list = [] 

387 

388 def build(node: fx.Node) -> tuple: 

389 """Emit ``getitem`` leaves for a nested value, else record the leaf.""" 

390 val = node.meta.get("val") 

391 if isinstance(val, (tuple, list)) and val: 

392 children = [] 

393 for index, element in enumerate(val): 

394 sub = graph.call_function(operator.getitem, (node, index)) 

395 sub.meta["val"] = element 

396 children.append(build(sub)) 

397 kind = "tuple" if isinstance(val, tuple) else "list" 

398 return kind, tuple(children) 

399 flat_nodes.append(node) 

400 return "leaf", len(flat_nodes) - 1 

401 

402 with graph.inserting_before(output): 

403 spec = tuple(build(node) for node in returned) 

404 output.args = (tuple(flat_nodes),) 

405 graph.lint() 

406 graph_module.recompile() 

407 return spec, graph_module 

408 

409 

410def _rebuild_nested_output(spec: tuple, flat: Sequence[Any]) -> list: 

411 """Rebuild the original output structure from ``spec`` and flat leaves.""" 

412 leaves = iter(flat) 

413 rebuilt = [] 

414 for kind, payload in spec: 

415 if kind == "leaf": 

416 rebuilt.append(next(leaves)) 

417 else: 

418 children = _rebuild_nested_output(payload, leaves) 

419 rebuilt.append(tuple(children) if kind == "tuple" else children) 

420 return rebuilt 

421 

422 

423class _NestedOutputWrapper(nn.Module): 

424 """Thin wrapper restoring a compiled graph's nested output structure.""" 

425 

426 def __init__( 

427 self, 

428 inner: nn.Module, 

429 spec: tuple, 

430 meta: Optional[Dict[str, Any]] = None, 

431 ) -> None: 

432 """Store the compiled inner module and its output marker tree.""" 

433 super().__init__() 

434 self.inner = inner 

435 self._output_spec = spec 

436 # Mirrors GraphModule.meta so callers can introspect compilation mode. 

437 self.meta = dict(meta or {}) 

438 

439 def forward(self, *args: Any, **kwargs: Any) -> tuple: 

440 """Run the flat compiled graph and rebuild the original structure.""" 

441 flat = self.inner(*args, **kwargs) 

442 return tuple(_rebuild_nested_output(self._output_spec, flat)) 

443 

444 

445def _tag_node(node: fx.Node, inductor_configs: Optional[Dict[str, Any]]) -> None: 

446 """Annotate ``node`` for regional_inductor with the user's Inductor config.""" 

447 node.meta.setdefault("custom", {})["compile_with_inductor"] = { 

448 "inductor_configs": dict(inductor_configs or {}), 

449 } 

450 

451 

452class InductorPass(GraphPass): 

453 """Terminal backend compilation pass (TorchInductor). 

454 

455 See the module docstring for the mode semantics, the numerics policy and 

456 the calling-convention contract. 

457 """ 

458 

459 @property 

460 def name(self) -> str: 

461 """Pass name.""" 

462 return "inductor_compilation" 

463 

464 def run( 

465 self, 

466 graph_module: fx.GraphModule, 

467 pass_config: PassConfig, 

468 example_inputs: Optional[tuple] = None, 

469 **kwargs: Any, 

470 ) -> fx.GraphModule: 

471 """Compile the joint graph (or its PP stages) with Inductor. 

472 

473 Args: 

474 graph_module: The joint FX graph produced by the tracer and 

475 transformed by the earlier partitioning / overlap passes. When 

476 ``PpPass`` already ran, this is the schedule stub and its 

477 stage subgraphs are compiled instead. 

478 pass_config: Graph-mode configuration; ``inductor_mode`` selects 

479 the behavior, ``inductor_configs`` overrides Inductor options. 

480 example_inputs: Fake inputs matching the joint graph's 

481 placeholders in order (the tracer's 

482 ``JointGraph.example_inputs``). Ignored for PP stage 

483 subgraphs, whose inputs are derived from each subgraph's 

484 placeholder metas. 

485 

486 Returns: 

487 The same graph module with compiled regions spliced in and the 

488 positional calling convention restored. On torch builds without 

489 regional Inductor support it is returned untouched, logging a 

490 warning and recording ``"unavailable"`` in its meta. 

491 

492 Raises: 

493 ValueError: When ``example_inputs`` is missing for a non-PP graph, 

494 a ``call_module`` stub is not a pipeline schedule (unknown 

495 split), or the requested DVM backend is unavailable. 

496 """ 

497 mode = pass_config.inductor_mode 

498 if mode == "off": 

499 return graph_module 

500 

501 validate_inductor_backend(pass_config) 

502 compiled = False 

503 if graph_module.graph.find_nodes(op="call_module"): 

504 compiled = self._compile_pipeline_stages(graph_module, pass_config) 

505 else: 

506 if example_inputs is None: 

507 raise ValueError( 

508 "InductorPass requires example_inputs (the tracer's " 

509 "JointGraph.example_inputs) to size compiled regions" 

510 ) 

511 if _regional_inductor_available(): 

512 self._compile_graph(graph_module, pass_config, model=kwargs.get("model")) 

513 compiled = True 

514 else: 

515 self._warn_unavailable(mode) 

516 

517 graph_module.meta[_INDUCTOR_COMPILED_META] = ( 

518 mode if compiled else _INDUCTOR_UNAVAILABLE 

519 ) 

520 graph_module.meta[_INDUCTOR_BACKEND_META] = pass_config.inductor_backend 

521 return graph_module 

522 

523 @staticmethod 

524 def _warn_unavailable(mode: str) -> None: 

525 """Warn that the running torch predates regional Inductor compilation.""" 

526 _LOG.warning( 

527 "InductorPass: torch %s does not provide " 

528 "torch.fx.passes.regional_inductor; skipping %r compilation " 

529 "(requires a newer torch build)", 

530 torch.__version__, 

531 mode, 

532 ) 

533 

534 def _compile_pipeline_stages( 

535 self, graph_module: fx.GraphModule, pass_config: PassConfig 

536 ) -> bool: 

537 """Compile every stage subgraph installed by ``PpPass``. 

538 

539 ``PpPass`` replaces the joint graph with a ``call_module`` stub around 

540 the pipeline schedule; the FX compute lives in the schedule's 

541 per-virtual-stage forward/backward subgraphs (see 

542 ``PipelineScheduleBase.map_stage_graphs``). Compiling the stub itself 

543 would be a no-op and the stub must remain the outer entry point. 

544 

545 Returns: 

546 ``True`` when the stage graphs were compiled, ``False`` when the 

547 running torch does not provide regional Inductor compilation (the 

548 pass then no-ops after ``_warn_unavailable``). 

549 """ 

550 schedules = [] 

551 for node in graph_module.graph.find_nodes(op="call_module"): 

552 submodule = graph_module.get_submodule(node.target) 

553 if not callable(getattr(submodule, "map_stage_graphs", None)): 

554 raise ValueError( 

555 f"InductorPass cannot compile call_module '{node.target}': " 

556 f"only PpPass's pipeline schedule exposes stage subgraphs " 

557 f"(map_stage_graphs) for backend compilation" 

558 ) 

559 schedules.append(submodule) 

560 

561 if not _regional_inductor_available(): 

562 self._warn_unavailable(pass_config.inductor_mode) 

563 return False 

564 

565 for schedule in schedules: 

566 schedule.map_stage_graphs( 

567 lambda stage_gm: self._compile_graph(stage_gm, pass_config) 

568 ) 

569 _LOG.info( 

570 "InductorPass: compiled %d PP schedule(s) in %r mode", 

571 len(schedules), 

572 pass_config.inductor_mode, 

573 ) 

574 return True 

575 

576 def _compile_graph( 

577 self, 

578 graph_module: fx.GraphModule, 

579 pass_config: PassConfig, 

580 model: Optional[nn.Module] = None, 

581 ) -> fx.GraphModule: 

582 """Compile one graph using its own placeholder metadata as inputs.""" 

583 mode = pass_config.inductor_mode 

584 output_spec, graph_module = _flatten_nested_outputs(graph_module) 

585 _propagate_fake_vals(graph_module, model) 

586 example_inputs = _placeholder_fake_args(graph_module) 

587 if any(isinstance(value, torch.Tensor) and value.device.type == "npu" for value in example_inputs): 

588 # standalone_compile bypasses Dynamo's lazy NPU backend setup. 

589 npu_dynamo = importlib.import_module("torch_npu.utils._dynamo") 

590 npu_dynamo.register_inductor_npu() 

591 _LOG.info( 

592 "InductorPass: compiling graph in %r mode (%d placeholders, %d nodes)", 

593 mode, 

594 len(graph_module.graph.find_nodes(op="placeholder")), 

595 len(graph_module.graph.nodes), 

596 ) 

597 

598 if mode == "full": 

599 self._tag_full(graph_module, pass_config.inductor_configs) 

600 else: 

601 self._tag_regional(graph_module, pass_config.inductor_configs) 

602 

603 # Imported lazily so this module does not pull in the (heavy) 

604 # TorchInductor stack unless compilation actually runs. 

605 import torch._inductor.config as inductor_config # pylint: disable=import-outside-toplevel 

606 from torch._guards import ( # pylint: disable=import-outside-toplevel 

607 TracingContext, 

608 tracing, 

609 ) 

610 from torch.fx.passes.regional_inductor import ( # pylint: disable=import-outside-toplevel 

611 regional_inductor, 

612 ) 

613 

614 # Bitwise-equal numerics vs eager (torchtitan's regional_inductor 

615 # policy). emulate_precision_casts / disable_ftz stay off: enabling 

616 # them is a numerics-changing opt-in, not this pass's default. Scope 

617 # the override so it cannot leak into other Inductor compiles. The 

618 # knob only exists in torch >= 2.11; older builds keep their defaults. 

619 numerics = {} 

620 if hasattr(inductor_config, "eager_numerics"): 

621 numerics["eager_numerics.division_rounding"] = True 

622 

623 fake_mode = _get_fake_mode_from_gm(graph_module) 

624 tracing_ctx = TracingContext(fake_mode) 

625 with ( 

626 inductor_config.patch( # pylint: disable=no-member 

627 numerics 

628 ), 

629 tracing(tracing_ctx), 

630 ): 

631 # ``regional_inductor`` consumes these on torch releases whose 

632 # signature expects example inputs; newer releases size regions 

633 # from the nodes' fake ``meta["val"]`` instead. 

634 regional_inductor(graph_module, example_inputs) 

635 

636 # regional_inductor compiles regions with the boxed calling 

637 # convention (one mutable args list); reset to the default positional 

638 # convention so run_traced_graph's graph_module(*flat_inputs) (and the 

639 # PP schedule's fwd_gm(*args) / bwd_gm(*args)) keeps working. Setting 

640 # the default unconditionally is a no-op when the region compiler 

641 # already used positional codegen and avoids peeking at private state. 

642 graph_module.graph.set_codegen(CodeGen()) 

643 graph_module.recompile() 

644 graph_module.meta[_INDUCTOR_COMPILED_META] = mode 

645 graph_module.meta[_INDUCTOR_BACKEND_META] = pass_config.inductor_backend 

646 if output_spec is not None: 

647 # Rebuild the stage's original (possibly nested) output structure 

648 # for the schedule / backward subgraph; only the compiled graph is 

649 # flat. 

650 return _NestedOutputWrapper(graph_module, output_spec, graph_module.meta) 

651 return graph_module 

652 

653 @staticmethod 

654 def _tag_full( 

655 graph_module: fx.GraphModule, inductor_configs: Optional[Dict[str, Any]] 

656 ) -> None: 

657 """Tag every node so the whole graph compiles as one region. 

658 

659 Mirrors torchtitan's ``full_inductor_compilation_pass``: Inductor's 

660 ``reorder_for_peak_memory`` restores the fwd/bwd interleaving that 

661 AOTAutograd flattening would otherwise drop. Side-effectful nodes 

662 (the FSDP reshard storage free) stay untagged: AOTAutograd's 

663 functionalization would re-execute them on functional tensors and 

664 lose the storage release. 

665 """ 

666 configs = dict(inductor_configs or {}) 

667 configs.setdefault("reorder_for_peak_memory", True) 

668 # Flat graph (joint graph or one PP stage subgraph): tag its nodes 

669 # directly (no nested ``call_module`` submodules to recurse into). 

670 for node in graph_module.graph.nodes: 

671 if node.op in ("placeholder", "output"): 

672 continue 

673 if _node_is_side_effectful(node): 

674 continue 

675 _tag_node(node, configs) 

676 

677 @staticmethod 

678 def _tag_regional( 

679 graph_module: fx.GraphModule, inductor_configs: Optional[Dict[str, Any]] 

680 ) -> None: 

681 """Tag functional compute nodes, keeping comms and side effects eager. 

682 

683 Untagged nodes become region boundaries: contiguous runs of tagged 

684 compute between collectives / frees are each fused and compiled, and 

685 the collective launch/wait nodes remain plain FX nodes so the overlap 

686 passes' scheduling decisions stay observable at runtime. 

687 """ 

688 region_id = 0 

689 in_region = False 

690 for node in graph_module.graph.nodes: 

691 if node.op not in ("call_function", "call_method"): 

692 continue 

693 if _node_is_comm(node) or _node_is_side_effectful(node): 

694 in_region = False 

695 continue 

696 if not in_region: 

697 region_id += 1 

698 in_region = True 

699 _tag_node(node, inductor_configs) 

700 # Capability partitioning otherwise merges non-adjacent compute 

701 # across storage frees, delaying a parameter read until after free. 

702 node.meta["custom"]["compile_with_inductor"]["inductor_region"] = region_id