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

430 statements  

« 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"""Partition a joint FX graph into eager host work and NPU capture regions.""" 

16 

17from __future__ import annotations 

18 

19from collections import Counter, defaultdict 

20import logging 

21import operator 

22from typing import Any, Iterable 

23 

24import torch 

25from torch import fx 

26from torch._ops import OpOverload 

27from torch._subclasses.fake_tensor import FakeTensor 

28from torch.fx.experimental.symbolic_shapes import statically_known_true 

29from torch.fx.immutable_collections import immutable_dict, immutable_list 

30from torch.fx.passes.split_module import split_module 

31from torch.multiprocessing.reductions import StorageWeakRef 

32from torch.ops import _c10d_functional 

33from torch.utils._pytree import tree_leaves, tree_map 

34 

35from ..pass_config import PassConfig 

36from .base import GraphPass 

37from .graph_metadata import ( 

38 _native_overload, 

39 is_host_node as _host_boundary, 

40 mutated_input_indices as _mutated_input_indices, 

41 propagate_fake_values, 

42 tensor_storages as _storages, 

43 written_nodes, 

44) 

45from .parallel.fsdp_pass import _free_tensor_storage 

46from .aclgraph_runtime import ( 

47 ACLGraphWrapper, 

48 _RecaptureCoordinator, 

49 install_aclgraph_runtime, 

50 prepare_aclgraph_runtime, 

51) 

52 

53logger = logging.getLogger(__name__) 

54 

55_FUNCTIONAL_COLLECTIVES = frozenset(( 

56 _c10d_functional.all_gather_into_tensor.default, 

57 _c10d_functional.all_reduce.default, 

58 _c10d_functional.reduce_scatter_tensor.default, 

59 _c10d_functional.all_to_all_single.default, 

60 _c10d_functional.all_gather_into_tensor_coalesced.default, 

61 _c10d_functional.all_reduce_coalesced.default, 

62 _c10d_functional.reduce_scatter_tensor_coalesced.default, 

63 _c10d_functional.broadcast.default, 

64)) 

65# Match the exact internal ATen symbols emitted by tracing, rather than Python wrappers. 

66_COLLECTIVE_REGION_SUPPORT = frozenset(( 

67 _c10d_functional.wait_tensor.default, 

68 # pylint: disable-next=protected-access 

69 torch.ops.aten.view.default, torch.ops.aten._unsafe_view.default, torch.ops.aten.reshape.default, 

70 torch.ops.aten.transpose.int, torch.ops.aten.permute.default, torch.ops.aten.t.default, 

71 torch.ops.aten.squeeze.default, torch.ops.aten.squeeze.dim, torch.ops.aten.unsqueeze.default, 

72 torch.ops.aten.slice.Tensor, torch.ops.aten.narrow.default, torch.ops.aten.select.int, 

73 torch.ops.aten.split.Tensor, torch.ops.aten.split_with_sizes.default, 

74 torch.ops.aten.detach.default, torch.ops.aten.alias.default, 

75 # pylint: disable-next=protected-access 

76 torch.ops.aten.clone.default, torch.ops.aten.contiguous.default, torch.ops.aten._to_copy.default, 

77 torch.ops.aten.sym_size.int, torch.ops.aten.sym_stride.int, torch.ops.aten.sym_numel.default, 

78)) 

79 

80 

81def _is_npu_tensor(value: Any) -> bool: 

82 return isinstance(value, torch.Tensor) and value.device.type == "npu" 

83 

84 

85def _same_layout(value, first): 

86 if value.dtype != first.dtype or len(value.shape) != len(first.shape): 

87 return False 

88 layout = (*value.shape, *value.stride(), value.storage_offset()) 

89 other = (*first.shape, *first.stride(), first.storage_offset()) 

90 return all(statically_known_true(left == right) for left, right in zip(layout, other, strict=True)) 

91 

92 

93def _staging_aliases(placeholders, input_storages, staged_input_indices): 

94 """Group identical input layouts without borrowing externally writable storage.""" 

95 storage_inputs = defaultdict(list) 

96 for i, storages in enumerate(input_storages): 

97 for storage in storages: 

98 storage_inputs[storage].append(i) 

99 input_aliases = {} 

100 for indices in storage_inputs.values(): 

101 if len(indices) < 2: 

102 continue 

103 first = placeholders[indices[0]].meta["val"] 

104 if all(i in staged_input_indices and _same_layout(placeholders[i].meta["val"], first) for i in indices): 

105 input_aliases.update((i, indices[0]) for i in indices[1:]) 

106 else: 

107 staged_input_indices.difference_update(indices) 

108 return input_aliases 

109 

110 

111def _collect_inputs(gm, static_input_indices): 

112 """Resolve lifted state, mutable inputs, and safe top-level staging aliases.""" 

113 placeholders = [node for node in gm.graph.nodes if node.op == "placeholder"] 

114 input_storages = [_storages(node) for node in placeholders] 

115 static_storages = set().union(*(input_storages[i] for i in static_input_indices)) 

116 mutated_storages = set().union(*(input_storages[i] for i in _mutated_input_indices(gm))) 

117 staged_input_indices = { 

118 i 

119 for i, node in enumerate(placeholders) 

120 if i not in static_input_indices 

121 and isinstance(value := node.meta.get("val"), torch.Tensor) 

122 and _is_npu_tensor(value) 

123 and value.is_contiguous() 

124 and len(input_storages[i]) == 1 

125 and not input_storages[i] & (mutated_storages | static_storages) 

126 } 

127 input_aliases = _staging_aliases(placeholders, input_storages, staged_input_indices) 

128 static_storages.update(set().union(*(input_storages[i] for i in staged_input_indices))) 

129 return placeholders, static_storages, staged_input_indices, input_aliases 

130 

131 

132def _partition_hosts(node_hosts): 

133 """Assign contiguous partitions across eager and capturable execution boundaries.""" 

134 partitions, host_partitions = {}, set() 

135 partition_id, previous_host = -1, None 

136 for node, host in node_hosts.items(): 

137 if host != previous_host: 

138 partition_id += 1 

139 previous_host = host 

140 partitions[node] = partition_id 

141 if host: 

142 host_partitions.add(partition_id) 

143 return partitions, host_partitions 

144 

145 

146def _storage_free_node(node): 

147 return ( 

148 node.op == "call_function" and node.target is _free_tensor_storage 

149 and node.meta.get("comm_type") in ("fsdp_reshard_free", "fsdp_reshard_free_backward") 

150 ) 

151 

152 

153def _known_free_metadata(value): 

154 """Exclude subclass/container contexts that could hide storage aliases.""" 

155 if type(value) in (torch.Tensor, FakeTensor) or isinstance(value, (torch.SymInt, torch.SymFloat, torch.SymBool)): 

156 return True 

157 if type(value) in (type(None), bool, int, float, complex, str, bytes): 

158 return True 

159 if type(value) in (tuple, list, immutable_list): 

160 return all(_known_free_metadata(item) for item in value) 

161 if type(value) in (dict, immutable_dict): 

162 return all(type(key) in (str, int) and _known_free_metadata(item) for key, item in value.items()) 

163 return False 

164 

165 

166def _known_free_node_metadata(node): 

167 # FakeTensorProp omits val for None; this exact helper never returns storage. 

168 if _storage_free_node(node): 

169 return node.meta.get("val") is None 

170 return "val" in node.meta and _known_free_metadata(node.meta["val"]) 

171 

172 

173# Native schemas are the only source of alias and mutation contracts for these FX operators. 

174def _storage_alias_forwarder(node): 

175 overload = _native_overload(node.target) 

176 return ( 

177 node.target is operator.getitem 

178 # pylint: disable-next=protected-access 

179 or overload in (_c10d_functional.wait_tensor.default, torch.ops.aten._unsafe_view.default) 

180 # pylint: disable-next=protected-access 

181 or (overload is not None and any(result.alias_info is not None for result in overload._schema.returns)) 

182 ) 

183 

184 

185def _free_storage_aliases(nodes, storages): 

186 """Include logical wait/view aliases even when their FakeTensor storages differ.""" 

187 parents = {node: node for node in nodes} 

188 

189 def _find(node): 

190 while parents[node] is not node: 

191 parents[node] = parents[parents[node]] 

192 node = parents[node] 

193 return node 

194 

195 def _join(left, right): 

196 parents[_find(left)] = _find(right) 

197 

198 producers = {} 

199 for node in nodes: 

200 for storage in storages[node]: 

201 _join(node, producers.setdefault(storage, node)) 

202 if _storage_alias_forwarder(node): 

203 for source in node.all_input_nodes: 

204 if storages[source] or "val" not in source.meta: 

205 _join(node, source) 

206 groups = defaultdict(set) 

207 for node in nodes: 

208 groups[_find(node)].add(node) 

209 return {node: groups[_find(node)] for node in nodes} 

210 

211 

212def _private_region_values(nodes, storages): 

213 """Prove allocation ownership from exact roots, never from Fake storage differences.""" 

214 owned = set() 

215 roots = (torch.ops.aten.clone.default, _c10d_functional.all_gather_into_tensor.default) 

216 for node in nodes: 

217 overload = _native_overload(node.target) 

218 if overload in roots: 

219 owned.add(node) 

220 # pylint: disable-next=protected-access 

221 elif _storage_alias_forwarder(node) and (overload is None or not overload._schema.is_mutable): 

222 inputs = [source for source in node.all_input_nodes if storages[source]] 

223 if inputs and all(source in owned for source in inputs): 

224 owned.add(node) 

225 return owned 

226 

227 

228def _internal_free_reason(node, region, owned, aliases, order): 

229 """Explain why a release cannot preserve the region-private storage lifetime.""" 

230 if len(node.args) != 1 or node.kwargs or not isinstance(node.args[0], fx.Node): 

231 return "unknown_free_signature" 

232 target = node.args[0] 

233 if not isinstance(target.meta.get("val"), torch.Tensor) or target not in owned: 

234 return "allocation_not_internal" 

235 storage_aliases = aliases[target] 

236 if not storage_aliases <= region: 

237 return "external_storage_alias" 

238 for alias in storage_aliases: 

239 for reader in alias.users: 

240 if reader not in region: 

241 return "escaping_storage_alias" 

242 if order[reader] > order[node]: 

243 return "alias_read_after_free" 

244 if reader is not node and not _storage_free_node(reader) and written_nodes(reader): 

245 return "storage_alias_mutation" 

246 overload = _native_overload(reader.target) 

247 # pylint: disable-next=protected-access 

248 if overload is not None and not overload._schema.name.startswith(("aten::", "_c10d_functional::")): 

249 return "unknown_alias_consumer" 

250 return None 

251 

252 

253def _region_free_failures(members, frees, metadata_known, storages, aliases, order, metadata_failures): 

254 """Check one tentative region without weakening release ownership proofs.""" 

255 region = set(members) 

256 inputs = {source for node in members for source in node.all_input_nodes if source not in region} 

257 known = all(metadata_known[node] for node in region | inputs) 

258 if not known: 

259 metadata_failures.update(node for node in region | inputs if not metadata_known[node]) 

260 inline_tensor = any(isinstance(value, torch.Tensor) for node in members 

261 for value in tree_leaves((node.args, node.kwargs))) 

262 boundary_write = _has_boundary_write(members, region, aliases) 

263 owned = _private_region_values(members, storages) 

264 failures = {} 

265 for node in frees: 

266 reason = ("missing_or_unknown_metadata" if not known else "inline_tensor_argument" if inline_tensor 

267 else "boundary_input_mutation" if boundary_write 

268 else _internal_free_reason(node, region, owned, aliases, order)) 

269 if reason is not None: 

270 failures[node] = reason 

271 return failures 

272 

273 

274def _has_boundary_write(members, region, aliases): 

275 """Reject writes that can rebind or mutate storage outside the region.""" 

276 value_only_writes = ( 

277 torch.ops.aten.copy_.default, torch.ops.aten.add_.Tensor, torch.ops.aten.logical_and_.default, 

278 ) 

279 return any( 

280 not aliases[written] <= region 

281 for node in members 

282 if not _storage_free_node(node) and node.target not in value_only_writes 

283 for written in written_nodes(node) 

284 ) 

285 

286 

287def _admit_internal_storage_frees(gm, node_hosts): 

288 """Repartition until every admitted release has a stable region-private lifetime.""" 

289 helpers = [node for node in node_hosts if _storage_free_node(node)] 

290 if not helpers: 

291 return node_hosts, {}, 0, {} 

292 nodes = list(gm.graph.nodes) 

293 order = {node: index for index, node in enumerate(nodes)} 

294 metadata_known = {node: _known_free_node_metadata(node) for node in nodes} 

295 storages = {node: _storages(node) if metadata_known[node] else set() for node in nodes} 

296 aliases = _free_storage_aliases(nodes, storages) 

297 active, rejected, iterations = set(helpers), {}, 0 

298 metadata_failures = set() 

299 node_hosts = {node: False if node in active else host for node, host in node_hosts.items()} 

300 while active: 

301 iterations += 1 

302 partitions, _ = _partition_hosts(node_hosts) 

303 groups = defaultdict(list) 

304 for node, partition in partitions.items(): 

305 groups[partition].append(node) 

306 failures = {} 

307 for members in groups.values(): 

308 frees = active.intersection(members) 

309 if frees: 

310 failures.update(_region_free_failures( 

311 members, frees, metadata_known, storages, aliases, order, metadata_failures, 

312 )) 

313 if not failures: 

314 break 

315 for node, reason in failures.items(): 

316 active.remove(node) 

317 rejected[node.name] = reason 

318 node_hosts[node] = True 

319 return node_hosts, rejected, iterations, _free_metadata_diagnostics(nodes, metadata_failures) 

320 

321 

322def _free_metadata_diagnostics(nodes, metadata_failures): 

323 """Summarize unknown metadata without changing release-admission decisions.""" 

324 missing = [node for node in nodes if node in metadata_failures] 

325 diagnostics = { 

326 "missing_metadata_node_count": len(missing), 

327 "missing_metadata_target_counts": dict(Counter(str(node.target) for node in missing).most_common(16)), 

328 "missing_metadata_examples": [ 

329 {"name": node.name, "op": node.op, "target": str(node.target), 

330 "kind": "missing_val" if "val" not in node.meta else "unknown_value_type", 

331 "value_type": type(node.meta.get("val")).__name__} 

332 for node in missing[:16] 

333 ], 

334 } 

335 return diagnostics 

336 

337 

338def _is_collective_only_region(nodes, mutated_aliases): 

339 # A downstream capture must keep the stable address of a mutated input; 

340 # eager collective allocations would change that address every step. 

341 if any(node in mutated_aliases for node in nodes): 

342 return False 

343 overloads = [_native_overload(node.target) for node in nodes] 

344 return any(overload in _FUNCTIONAL_COLLECTIVES for overload in overloads) and all( 

345 node.op == "call_function" and ( 

346 node.target is operator.getitem 

347 or overload in _FUNCTIONAL_COLLECTIVES 

348 or overload in _COLLECTIVE_REGION_SUPPORT 

349 ) for node, overload in zip(nodes, overloads, strict=True) 

350 ) 

351 

352 

353def _view_alias_last_writes(nodes, aliases): 

354 """Track the last writer through native view and structured-result aliases.""" 

355 order = {node: index for index, node in enumerate(nodes)} 

356 last_writes = {} 

357 for node in nodes: 

358 unknown = (node.op in ("call_function", "call_method", "call_module") 

359 and _native_overload(node.target) is None and node.target is not operator.getitem) 

360 written = written_nodes(node) 

361 if unknown: 

362 written = [node, *written] 

363 for value in written: 

364 for alias in aliases[value]: 

365 last_writes[alias] = max(last_writes.get(alias, -1), float("inf") if unknown else order[node]) 

366 return order, last_writes 

367 

368 

369def _is_view_only_region(nodes, order, last_writes): 

370 overloads = [_native_overload(node.target) for node in nodes] 

371 return ( 

372 any(overload == torch.ops.aten.view.default for overload in overloads) 

373 and all(node.op == "call_function" and ( 

374 node.target is operator.getitem or overload == torch.ops.aten.view.default 

375 ) for node, overload in zip(nodes, overloads, strict=True)) 

376 and all(last_writes.get(node, -1) < order[nodes[0]] for node in nodes) 

377 ) 

378 

379 

380def _is_trivial_region(nodes, mutated_aliases, order, last_writes): 

381 return (_is_collective_only_region(nodes, mutated_aliases) 

382 or _is_view_only_region(nodes, order, last_writes)) 

383 

384 

385def _keep_collective_only_regions_eager( 

386 node_hosts: dict[fx.Node, bool], 

387) -> tuple[dict[fx.Node, bool], list[list[fx.Node]]]: 

388 """Avoid separate graph launches for isolated communication or metadata views.""" 

389 partitions, hosts = _partition_hosts(node_hosts) 

390 regions = defaultdict(list) 

391 for node, partition in partitions.items(): 

392 regions[partition].append(node) 

393 graph_nodes = list(next(iter(node_hosts)).graph.nodes) if node_hosts else [] 

394 storages = {node: _storages(node) for node in graph_nodes} 

395 aliases = _free_storage_aliases(graph_nodes, storages) 

396 mutated_aliases = { 

397 alias for node in graph_nodes if not _storage_free_node(node) 

398 for written in written_nodes(node) for alias in aliases[written] 

399 } 

400 order, last_writes = _view_alias_last_writes(graph_nodes, aliases) 

401 skipped = [] 

402 for partition, nodes in regions.items(): 

403 if partition in hosts or partition - 1 not in hosts or partition + 1 not in hosts: 

404 continue 

405 if _is_trivial_region(nodes, mutated_aliases, order, last_writes): 

406 skipped.append(nodes) 

407 # Keep proven storage releases and their owners together. An unrecognized 

408 # node (including a release or mutable op) retains the entire capture region. 

409 updated = dict(node_hosts) 

410 for nodes in skipped: 

411 updated.update((node, True) for node in nodes) 

412 return updated, skipped 

413 

414 

415def _collective_region_stats(regions): 

416 view_regions = [nodes for nodes in regions 

417 if not any(_native_overload(node.target) in _FUNCTIONAL_COLLECTIVES for node in nodes)] 

418 regions = [nodes for nodes in regions if nodes not in view_regions] 

419 if regions: 

420 logger.info("ACLGraph kept %d isolated collective-only regions eager", len(regions)) 

421 return { 

422 "view_only_eager_regions": len(view_regions), 

423 "view_only_eager_nodes": sum(len(nodes) for nodes in view_regions), 

424 "view_only_eager_region_examples": [ 

425 {"first_node": nodes[0].name, "last_node": nodes[-1].name, "node_count": len(nodes)} 

426 for nodes in view_regions[:16] 

427 ], 

428 "collective_only_eager_regions": len(regions), 

429 "collective_only_eager_nodes": sum(len(nodes) for nodes in regions), 

430 "collective_only_eager_target_counts": dict(Counter( 

431 str(node.target) for nodes in regions for node in nodes 

432 if _native_overload(node.target) in _FUNCTIONAL_COLLECTIVES 

433 )), 

434 "collective_only_eager_region_examples": [ 

435 {"first_node": nodes[0].name, "last_node": nodes[-1].name, "node_count": len(nodes)} 

436 for nodes in regions[:16] 

437 ], 

438 } 

439 

440 

441def _select_capture_regions(sizes, min_capture_nodes, max_capture_regions): 

442 """Apply the node minimum before budgeting complete device regions.""" 

443 eligible = {partition: size for partition, size in sizes.items() if size >= min_capture_nodes} 

444 selected = set(eligible) 

445 if max_capture_regions and len(eligible) > max_capture_regions: 

446 selected = set(sorted(eligible, key=lambda partition: (-eligible[partition], partition))[:max_capture_regions]) 

447 logger.info("ACLGraph capture budget kept %d of %d device regions", len(selected), len(eligible)) 

448 return selected, len(sizes) - len(eligible), len(eligible) - len(selected) 

449 

450 

451def _partitions(gm, max_capture_regions=0, min_capture_nodes=0): 

452 """Select complete safe capture regions and record ownership and budget decisions.""" 

453 node_hosts = {node: _host_boundary(node) for node in gm.graph.nodes 

454 if node.op not in ("placeholder", "get_attr", "output")} 

455 partitions, host_partitions = _partition_hosts(node_hosts) 

456 strict_regions = len(set(partitions.values()) - host_partitions) 

457 helpers = [node for node in node_hosts if _storage_free_node(node)] 

458 node_hosts, rejected, iterations, diagnostics = _admit_internal_storage_frees(gm, node_hosts) 

459 partitions, host_partitions = _partition_hosts(node_hosts) 

460 regions_after_free_admission = len(set(partitions.values()) - host_partitions) 

461 admitted = [node for node in helpers if not node_hosts[node]] 

462 node_hosts, collective_only_regions = _keep_collective_only_regions_eager(node_hosts) 

463 partitions, host_partitions = _partition_hosts(node_hosts) 

464 sizes = Counter(partition for partition in partitions.values() if partition not in host_partitions) 

465 collective_stats = _collective_region_stats(collective_only_regions) 

466 selected, below_minimum, over_budget = _select_capture_regions(sizes, min_capture_nodes, max_capture_regions) 

467 if len(selected) < len(sizes): 

468 partitions, host_partitions = _partition_hosts( 

469 {node: partition not in selected for node, partition in partitions.items()} 

470 ) 

471 captured = len(set(partitions.values()) - host_partitions) 

472 gm.meta["aclgraph_partition_stats"] = { 

473 "strict_device_regions": strict_regions, "device_regions_after_free_admission": regions_after_free_admission, 

474 "device_regions_after_collective_filter": len(sizes), 

475 **collective_stats, 

476 "max_capture_regions": max_capture_regions, "capture_regions": captured, "eager_regions": len(host_partitions), 

477 "min_capture_nodes": min_capture_nodes, "min_nodes_dropped_device_regions": below_minimum, 

478 "budget_dropped_device_regions": over_budget, "storage_free_candidates": len(helpers), 

479 "storage_free_admitted": len(admitted), "storage_free_rejected": len(rejected), 

480 "admitted_helper_names": [node.name for node in admitted], "rejected_helper_reasons": rejected, 

481 "rejected_helper_names": [node.name for node in helpers if node.name in rejected], 

482 "captured_helper_names": [node.name for node in admitted if partitions[node] not in host_partitions], 

483 "fixed_point_iterations": iterations, **diagnostics, 

484 } 

485 return partitions, host_partitions 

486 

487 

488def _output_clone_indices(output, escaping_storages, unknown_returns): 

489 nodes = [node for node in tree_leaves(output.args[0]) if isinstance(node, fx.Node)] 

490 if unknown_returns or any("val" not in node.meta for node in nodes): 

491 return None 

492 values = tree_map(lambda value: value.meta["val"] if isinstance(value, fx.Node) else value, output.args[0]) 

493 return tuple( 

494 i for i, value in enumerate(tree_leaves(values)) 

495 if isinstance(value, torch.Tensor) and StorageWeakRef(value.untyped_storage()) in escaping_storages 

496 ) 

497 

498 

499def _capture_ownership(result, host_partitions, escaping_storages, unknown_returns, placeholders): 

500 """Resolve captured storage owners and outputs requiring independent copies.""" 

501 captured_storages = set() 

502 output_clones, cloned_nodes = {}, set() 

503 for name, region in result.named_children(): 

504 if not isinstance(region, torch.fx.GraphModule): 

505 continue 

506 if int(name.rsplit("_", 1)[1]) not in host_partitions: 

507 output = next(node for node in region.graph.nodes if node.op == "output") 

508 output_nodes = [node for node in tree_leaves(output.args) if isinstance(node, torch.fx.Node)] 

509 indices = output_clones[name] = _output_clone_indices(output, escaping_storages, unknown_returns) 

510 cloned_nodes.update(node.name for node in output_nodes 

511 if indices is None or _storages(node) & escaping_storages) 

512 region_input_storages = set().union( 

513 *(_storages(node) for node in region.graph.nodes if node.op == "placeholder") 

514 ) 

515 for node in tree_leaves(output.args): 

516 if isinstance(node, torch.fx.Node): 

517 # Views of eager inputs inherit their producer's changing 

518 # addresses; only allocations made here are capture-owned. 

519 captured_storages.update(_storages(node) - region_input_storages) 

520 for node in placeholders: 

521 captured_storages.difference_update(_storages(node)) 

522 return captured_storages, output_clones, cloned_nodes 

523 

524 

525def _region_inputs(region, producers, eager_producers, cloned_nodes, static_storages, captured_storages): 

526 """Classify region inputs as borrowed, static, or privately staged.""" 

527 region_inputs = [node for node in region.graph.nodes if node.op == "placeholder"] 

528 # SAR can reuse forward FakeTensor storage metadata on eager 

529 # recomputations. Trust the actual FX producer, not storage alone. 

530 captured_inputs = { 

531 i 

532 for i, node in enumerate(region_inputs) 

533 if (producer := producers.get(node.name)) is not None and producer not in eager_producers 

534 and node.name not in cloned_nodes 

535 } 

536 mutated = _mutated_input_indices(region) 

537 written_storages = set().union(*(_storages(region_inputs[i]) for i in mutated)) 

538 static_indices = ( 

539 mutated 

540 | captured_inputs 

541 | {i for i, node in enumerate(region_inputs) if _storages(node) & (static_storages | written_storages)} 

542 ) 

543 # A mixed container may also own eager/state buffers. Borrow it only 

544 # when every tensor storage comes from a captured producer. 

545 borrowed_indices = { 

546 i 

547 for i, node in enumerate(region_inputs) 

548 if i in captured_inputs and (storages := _storages(node)) and storages <= captured_storages 

549 } 

550 return static_indices, borrowed_indices 

551 

552 

553def _read_only_producers(gm, escaping_storages, unknown_returns): 

554 """Prove producer storage is read-only across the complete scheduled graph.""" 

555 if unknown_returns: 

556 return set() 

557 written_storages = set() 

558 for node in gm.graph.nodes: 

559 for written in written_nodes(node): 

560 if "val" not in written.meta: 

561 return set() 

562 written_storages.update(_storages(written)) 

563 excluded = written_storages | escaping_storages 

564 native_producers, shareable = set(), set() 

565 for node in gm.graph.nodes: 

566 native = node.op == "call_function" and isinstance(node.target, OpOverload) 

567 getitem = (node.op == "call_function" and node.target is operator.getitem 

568 and node.args and isinstance(node.args[0], fx.Node) and node.args[0] in native_producers) 

569 if not (native or getitem): 

570 continue 

571 native_producers.add(node) 

572 storages = _storages(node) 

573 if isinstance(node.meta.get("val"), torch.Tensor) and storages and not storages & excluded: 

574 shareable.add(node.name) 

575 return shareable 

576 

577 

578def _scratch_input_aliases(region): 

579 """Find private input lifetimes, retaining unknown and storage-rebinding barriers.""" 

580 nodes = list(region.graph.nodes) 

581 if any(node.op != "output" and not _known_free_node_metadata(node) 

582 # pylint: disable-next=protected-access 

583 and not ((overload := _native_overload(node.target)) is not None and not overload._schema.returns) 

584 for node in nodes): 

585 return None 

586 for node in nodes: 

587 overload = _native_overload(node.target) 

588 if overload is not None and overload._schema.name in ( # pylint: disable=protected-access 

589 "aten::set_", "aten::resize_", "aten::resize_as_", "aten::as_strided_", 

590 ): 

591 return None 

592 aliases = _free_storage_aliases(nodes, {node: _storages(node) for node in nodes}) 

593 output = next(node for node in nodes if node.op == "output") 

594 returned = {node for node in tree_leaves(output.args) if isinstance(node, fx.Node)} 

595 excluded = set().union(*(aliases[node] for node in returned)) 

596 excluded.update(alias for node in nodes for written in written_nodes(node) for alias in aliases[written]) 

597 excluded.update(_scratch_unjoined_readers(nodes, aliases, returned)) 

598 return excluded 

599 

600 

601def _scratch_unjoined_readers(nodes, aliases, returned): 

602 """Exclude direct slot reads with no proven current-stream completion contract.""" 

603 wait = _c10d_functional.wait_tensor.default 

604 joined = returned | {node.args[0] for node in nodes if _native_overload(node.target) == wait 

605 and node.args and isinstance(node.args[0], fx.Node)} 

606 excluded = set() 

607 for node in nodes: 

608 if node.op not in ("call_function", "call_method", "call_module") or _storage_free_node(node): 

609 continue 

610 overload = _native_overload(node.target) 

611 if node.target is operator.getitem or overload == wait: 

612 continue 

613 schema = overload._schema.name if overload is not None else "" # pylint: disable=protected-access 

614 safe = schema.startswith("aten::") or (schema.startswith("_c10d_functional::") and node in joined) 

615 if not safe: 

616 excluded.update(alias for source in node.all_input_nodes for alias in aliases[source]) 

617 return excluded 

618 

619 

620def _scratch_input_keys(region, static_indices, borrowed_indices): 

621 """Reuse only region-private dynamic copies; original producer liveness is independent.""" 

622 excluded = _scratch_input_aliases(region) 

623 if excluded is None: 

624 return {} 

625 keys = {} 

626 for index, node in enumerate(region.graph.find_nodes(op="placeholder")): 

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

628 if (index in static_indices or index in borrowed_indices or node in excluded 

629 or type(value) not in (torch.Tensor, FakeTensor) or not _is_npu_tensor(value) 

630 or value.layout != torch.strided or value.is_conj() or value.is_neg() 

631 or value.is_quantized or value.is_nested 

632 # FakeTensor rejects named tensors; its names property may itself raise. 

633 or (not isinstance(value, FakeTensor) 

634 and any(name is not None for name in getattr(value, "names", ())))): 

635 continue 

636 # Fake layouts can converge after an escaping clone compacts a view. 

637 # Distinct input indices stay distinct even when actual layouts match. 

638 keys[index] = f"scratch:{index}" 

639 return keys 

640 

641 

642def _wrap_regions(result, partitions, host_partitions, ownership, static_storages, coordinator, read_only_producers): 

643 """Install replay wrappers with proven input and output ownership.""" 

644 captured_storages, output_clones, cloned_nodes = ownership 

645 producers = {node.name: partition for node, partition in partitions.items()} 

646 summaries, input_plans = [], {} 

647 shared_producers = Counter() 

648 for name, region in result.named_children(): 

649 if not isinstance(region, torch.fx.GraphModule) or int(name.rsplit("_", 1)[1]) in host_partitions: 

650 continue 

651 static_indices, borrowed_indices = _region_inputs( 

652 region, producers, host_partitions, cloned_nodes, static_storages, captured_storages 

653 ) 

654 shared_keys = { 

655 index: node.name 

656 for index, node in enumerate(region.graph.find_nodes(op="placeholder")) 

657 if index not in static_indices and index not in borrowed_indices and node.name in read_only_producers 

658 } 

659 shared_keys.update(_scratch_input_keys(region, static_indices, borrowed_indices)) 

660 shared_producers.update(shared_keys.values()) 

661 input_plans[name] = static_indices, borrowed_indices, shared_keys 

662 for name, region in result.named_children(): 

663 if not isinstance(region, torch.fx.GraphModule): 

664 continue 

665 host = int(name.rsplit("_", 1)[1]) in host_partitions 

666 summaries.append( 

667 { 

668 "name": name, 

669 "host": host, 

670 "capture": not host, 

671 } 

672 ) 

673 if host: 

674 continue 

675 clone_indices = output_clones[name] 

676 static_indices, borrowed_indices, shared_keys = input_plans[name] 

677 wrapper = ACLGraphWrapper( 

678 region.forward, 

679 static_input_indices=static_indices, 

680 capture_runnable=torch.fx.Interpreter(region).boxed_run, 

681 label=name, 

682 output_clone_indices=clone_indices, 

683 recapture_coordinator=coordinator, 

684 borrowed_input_indices=borrowed_indices, 

685 capture_boxed=True, 

686 shared_input_keys={index: key for index, key in shared_keys.items() if shared_producers[key] > 1}, 

687 ) 

688 object.__setattr__(region, "_aclgraph_wrapper", wrapper) 

689 region.forward = wrapper 

690 coordinator.wrappers.append(wrapper) 

691 return summaries 

692 

693 

694def _partition_graph(gm, *, static_input_indices, coordinate_recapture, max_capture_regions=0, min_capture_nodes=0): 

695 """Capture contiguous device work, retaining host boundaries in eager.""" 

696 placeholders, static_storages, staged, aliases = _collect_inputs(gm, static_input_indices) 

697 returned = next(node for node in gm.graph.nodes if node.op == "output") 

698 returned_nodes = [node for node in tree_leaves(returned.args) if isinstance(node, fx.Node)] 

699 escaping_storages = set().union(*(_storages(node) for node in returned_nodes)) 

700 unknown_returns = any("val" not in node.meta for node in returned_nodes) 

701 read_only_producers = _read_only_producers(gm, escaping_storages, unknown_returns) 

702 partitions, host_partitions = _partitions(gm, max_capture_regions, min_capture_nodes) 

703 result = split_module(gm, gm, partitions.__getitem__, keep_original_order=True, keep_original_node_name=True) 

704 ownership = _capture_ownership( 

705 result, host_partitions, escaping_storages, unknown_returns, placeholders 

706 ) 

707 coordinator = _RecaptureCoordinator(coordinate_recapture=coordinate_recapture) 

708 summaries = _wrap_regions( 

709 result, partitions, host_partitions, ownership, static_storages, coordinator, read_only_producers 

710 ) 

711 result.meta.update(gm.meta) 

712 result.meta["aclgraph_partitions"] = summaries 

713 install_aclgraph_runtime(result, coordinator, staged_input_indices=staged, input_aliases=aliases) 

714 logger.info("Applied ACLGraph pass: %d capture regions, %d eager regions", len(coordinator.wrappers), 

715 len(host_partitions)) 

716 return result 

717 

718 

719def _has_npu_work(graph_module): 

720 return any(_is_npu_tensor(value) for node in graph_module.graph.nodes 

721 for value in tree_leaves(node.meta.get("val")) if isinstance(value, torch.Tensor)) 

722 

723 

724def _validate_static_indices(indices, count): 

725 if any(isinstance(index, bool) or not isinstance(index, int) or index < 0 or index >= count for index in indices): 

726 raise ValueError("ACLGraph static_input_indices must index graph placeholders") 

727 

728 

729class ACLGraphPass(GraphPass): 

730 """Capture device regions after FSDP, bucketing and communication scheduling. 

731 

732 Parameters, buffers and mutated inputs retain their original storage. 

733 Host reads stay eager. Static mode rejects changed replay signatures; 

734 dynamic mode coordinates recapture across ranks using a CPU process group. 

735 """ 

736 

737 name = "aclgraph" 

738 

739 def run( 

740 self, 

741 graph_module: fx.GraphModule, 

742 pass_config: PassConfig, 

743 example_inputs: tuple[Any, ...] | None = None, 

744 static_input_indices: Iterable[int] | None = None, 

745 model: torch.nn.Module | None = None, 

746 **kwargs: Any, 

747 ) -> fx.GraphModule: 

748 """Install NPU capture wrappers, returning the partitioned graph. 

749 

750 Args: 

751 graph_module: Traced joint forward/backward graph. 

752 pass_config: Selects off, static, or dynamic ACLGraph replay. 

753 example_inputs: Fake inputs used to fill metadata on inserted nodes. 

754 static_input_indices: Lifted state indices. Defaults to the tracer's 

755 ``num_state_inputs`` leading placeholders. 

756 model: Live model, whose parameters may already have been sharded. 

757 **kwargs: Additional pipeline context, unused here. 

758 

759 Returns: 

760 A graph whose device regions warm up once before capture and replay. 

761 CPU-only graphs stay eager without loading the NPU backend. Disabled passes are unchanged. 

762 """ 

763 if pass_config.aclgraph_mode == "off": 

764 return graph_module 

765 pass_config.validate() 

766 if graph_module.meta.get("inductor_compiled") in ("regional", "full"): 

767 raise ValueError("ACLGraphPass cannot capture a graph already compiled with Inductor") 

768 placeholders = list(graph_module.graph.find_nodes(op="placeholder")) 

769 if example_inputs is not None or model is not None: 

770 propagate_fake_values(graph_module, example_inputs, model) 

771 if not _has_npu_work(graph_module): 

772 return install_aclgraph_runtime( 

773 graph_module, _RecaptureCoordinator(coordinate_recapture=pass_config.aclgraph_mode == "dynamic"), 

774 ) 

775 if static_input_indices is None: 

776 static_input_indices = range(getattr(graph_module, "num_state_inputs", 0)) 

777 static_input_indices = set(static_input_indices) 

778 _validate_static_indices(static_input_indices, len(placeholders)) 

779 prepare_aclgraph_runtime() 

780 result = _partition_graph( 

781 graph_module, 

782 static_input_indices=static_input_indices, 

783 coordinate_recapture=pass_config.aclgraph_mode == "dynamic", 

784 max_capture_regions=pass_config.aclgraph_max_capture_regions, 

785 min_capture_nodes=pass_config.aclgraph_min_capture_nodes, 

786 ) 

787 # Tracing and physical FSDP layout contracts live outside ``meta``. 

788 # Gradient clipping and checkpoint restore both need the physical layout. 

789 for name in ("state_fqns", "state_is_param", "num_state_inputs", "user_inputs_spec", "loss_dict_keys", 

790 "fsdp_sharded_param_names", "fsdp_padded_params"): 

791 if hasattr(graph_module, name): 

792 setattr(result, name, getattr(graph_module, name)) 

793 return result