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

436 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"""ACLGraph capture/replay, input guards and buffer ownership.""" 

16 

17from __future__ import annotations 

18 

19from collections.abc import Callable, Iterable 

20from datetime import timedelta 

21import importlib 

22import logging 

23import os 

24from operator import itemgetter 

25from typing import Any 

26 

27import torch 

28from torch import _debug_has_internal_overlap, _foreach_copy_ 

29from torch._C import _dispatch_keys 

30from torch._C._dynamo.guards import RootGuardManager 

31from torch._dynamo.guards import GuardManagerType 

32from torch.multiprocessing.reductions import StorageWeakRef 

33from torch.ops import _c10d_functional 

34from torch.utils._pytree import keystr, tree_flatten, tree_flatten_with_path, tree_leaves, tree_map, tree_unflatten 

35 

36logger = logging.getLogger(__name__) 

37 

38 

39def _get_torch_npu() -> Any: 

40 # Keep this optional dependency out of CPU imports and disabled pipelines. 

41 return importlib.import_module("torch_npu") 

42 

43 

44def _clone_capture_input(value): 

45 """Copy an input into independent persistent storage while preserving safe strides.""" 

46 normal = ( 

47 type(value) is torch.Tensor and value.layout == torch.strided # pylint: disable=unidiomatic-typecheck 

48 and not value.is_conj() and not value.is_neg() and not value.is_quantized 

49 and not value.is_nested and not any(name is not None for name in getattr(value, "names", ())) 

50 ) 

51 if normal: 

52 span = 1 

53 # A stride beyond all smaller-stride dimensions proves disjoint addresses, 

54 # including gapped slices where the generic overlap check is inconclusive. 

55 for stride, size in sorted((stride, size) for size, stride in zip(value.shape, value.stride(), strict=True) 

56 if size > 1): 

57 if stride < span: 

58 break 

59 span += (size - 1) * stride 

60 else: 

61 saved = torch.empty_strided(value.shape, value.stride(), dtype=value.dtype, device=value.device) 

62 saved.copy_(value.detach()) 

63 return saved 

64 saved = value.detach().clone() 

65 # clone preserves dense permutations but compacts slices with gaps. 

66 # Such intermediates still need their original layout during replay. 

67 if saved.stride() != value.stride() and _debug_has_internal_overlap(value) != 1: 

68 saved = torch.empty_strided(value.shape, value.stride(), dtype=value.dtype, device=value.device) 

69 saved.copy_(value.detach()) 

70 return saved 

71 

72 

73def prepare_aclgraph_runtime() -> None: 

74 """Select a task-queue mode supported by NPU graph recording. 

75 

76 Raises: 

77 ValueError: If task queue mode 2 cannot be switched dynamically. 

78 """ 

79 npu = _get_torch_npu().npu 

80 get_mode = getattr(npu, "get_task_queue_enable", None) 

81 mode = get_mode() if get_mode is not None else int(os.environ.get("TASK_QUEUE_ENABLE", "1")) 

82 if mode == 2: 

83 set_mode = getattr(npu, "set_task_queue_enable", None) 

84 if set_mode is None: 

85 raise ValueError("ACLGraph requires TASK_QUEUE_ENABLE=0/1 or the dynamic task-queue API") 

86 set_mode(1) 

87 logger.info("ACLGraph switched task queue mode from 2 to 1 before recording") 

88 

89 

90def _add_tensor_input_guard(manager, value, label): 

91 """Retain native layout/type guards across Dynamo binding signatures.""" 

92 layout_args = (value, list(value.shape), list(value.stride()), label, []) 

93 type_args = (type(value), _dispatch_keys(value)) 

94 try: 

95 manager.add_tensor_match_guard(*layout_args, *type_args) 

96 except TypeError: 

97 # Newer bindings require an extra guard-recording metadata argument. 

98 manager.add_tensor_match_guard(*layout_args, None, *type_args) 

99 

100 

101class _RecaptureCoordinator: 

102 """Agree across ranks before capture/replay, without capturing a collective.""" 

103 

104 def __init__(self, *, coordinate_recapture: bool = True) -> None: 

105 """Track the common capture order and recording-pool generation.""" 

106 self.wrappers = [] 

107 self.group: torch.distributed.ProcessGroup | None = None 

108 self.initialized = False 

109 self.graph_pool = None 

110 self.coordinate_recapture = coordinate_recapture 

111 self.shared_input_buffers = {} 

112 

113 def _begin_step(self): 

114 """Recycle obsolete graph pools before a new recording generation begins.""" 

115 pools = {value.pool_id for value in self.wrappers if value.graph is not None} 

116 if len(pools) > 1: 

117 torch_npu = _get_torch_npu() 

118 

119 # Reclaim old generations before another step records a third 

120 # pool. Escaping gradients are independent copies by contract. 

121 torch_npu.npu.synchronize() 

122 for value in self.wrappers: 

123 value.teardown() 

124 pools.clear() 

125 logger.info("ACLGraph: recycling mixed capture generations at step boundary") 

126 for pool in tuple(self.shared_input_buffers): 

127 if pool not in pools: 

128 del self.shared_input_buffers[pool] 

129 

130 def shared_input(self, pool: Any, key: str, value: torch.Tensor) -> torch.Tensor: 

131 """Own stable producer or region-private scratch storage within one recording generation. 

132 

133 Scratch callers must re-copy every consumer and prove that no live 

134 output alias or pending asynchronous reader survives its region. 

135 """ 

136 layout = (key, tuple(value.shape), value.stride(), value.storage_offset(), value.dtype, value.device) 

137 buffers = self.shared_input_buffers.setdefault(pool, {}) 

138 saved = buffers.get(layout) 

139 if saved is None: 

140 saved = buffers[layout] = _clone_capture_input(value) 

141 else: 

142 saved.copy_(value) 

143 return saved 

144 

145 def initialize(self) -> None: 

146 """Validate the complete plan once, including ranks without captured regions.""" 

147 if self.initialized: 

148 return 

149 if torch.distributed.is_initialized() and torch.distributed.get_world_size() > 1: 

150 group = torch.distributed.new_group(backend="gloo", timeout=timedelta(seconds=600)) 

151 self.group = group 

152 names = [value.label for value in self.wrappers] 

153 gathered: list[list[str] | None] = [None] * torch.distributed.get_world_size(group) 

154 torch.distributed.all_gather_object(gathered, names, group=group) 

155 if any(value != names for value in gathered): 

156 self.teardown() 

157 raise ValueError("ACLGraph requires identical region order across ranks") 

158 self.initialized = True 

159 

160 def before_call(self, wrapper: "ACLGraphWrapper", args: list[Any]) -> None: 

161 """Agree on capture state before executing any captured collective.""" 

162 if wrapper is self.wrappers[0]: 

163 if self.coordinate_recapture: 

164 self._begin_step() 

165 # Even a retry after partial capture must use a fresh pool rather 

166 # than allocate over live buffers from graphs replayed this step. 

167 self.graph_pool = None 

168 self.initialize() 

169 # Coordinator and wrapper share this internal replay-validation protocol. 

170 # pylint: disable-next=protected-access 

171 reason = wrapper._input_change_reason(args) if wrapper.graph is not None else None 

172 if not self.coordinate_recapture: 

173 self._validate_static_inputs(wrapper, reason) 

174 return 

175 self._coordinate(wrapper, reason) 

176 

177 def _validate_static_inputs(self, wrapper, reason): 

178 """Reject every rank before any peer submits incompatible captured communication.""" 

179 changed = reason is not None 

180 if self.group is not None: 

181 flags = torch.tensor([int(changed)], device="cpu", dtype=torch.int32) 

182 with torch.profiler.record_function("ACLGraph/rank_coordination"): 

183 torch.distributed.all_reduce(flags, op=torch.distributed.ReduceOp.MAX, group=self.group) 

184 changed = bool(flags.item()) 

185 if changed: 

186 raise ValueError( 

187 f"ACLGraph static replay inputs changed at {wrapper.label}: " 

188 f"{reason or 'peer signature mismatch'}. " 

189 "Use aclgraph_mode='dynamic' for coordinated recapture." 

190 ) 

191 

192 def _coordinate(self, wrapper, reason): 

193 """Agree on recording transitions before any rank executes captured communication.""" 

194 flags = torch.tensor( 

195 [int(reason is not None), int(wrapper.graph is None), int(wrapper.graph is not None)], 

196 device="cpu", 

197 dtype=torch.int32, 

198 ) 

199 if self.group is not None: 

200 with torch.profiler.record_function("ACLGraph/rank_coordination"): 

201 torch.distributed.all_reduce(flags, op=torch.distributed.ReduceOp.MAX, group=self.group) 

202 if flags[0].item() or (flags[1].item() and flags[2].item()): 

203 torch_npu = _get_torch_npu() 

204 

205 torch_npu.npu.synchronize() 

206 # New captures use this step's fresh pool, never an older replay's 

207 # allocator state. There is no checkpoint rollback across HCCL. 

208 wrapper.teardown() 

209 logger.info( 

210 "ACLGraph %s: input signature changed; recapturing region; reason=%s", 

211 wrapper.label, 

212 reason or "another rank changed its inputs or capture state", 

213 ) 

214 

215 def teardown(self) -> None: 

216 """Release captured buffers or the coordination process group.""" 

217 if self.group is not None: 

218 torch.distributed.destroy_process_group(self.group) 

219 self.group = None 

220 self.graph_pool = None 

221 self.shared_input_buffers.clear() 

222 self.initialized = False 

223 

224 

225class ACLGraphWrapper: 

226 """Warm up once, then capture/replay using stable input buffers. 

227 

228 Lifted state and mutated inputs retain their addresses. Escaping gradients 

229 are copied: GraphTrainer may assign a returned gradient to ``param.grad``. 

230 Intermediates use non-owning replay handles; owning capture-time results 

231 follow normal FX liveness. New recordings never allocate in an older pool. 

232 """ 

233 

234 def __init__( 

235 self, 

236 runnable: Callable[..., Any], 

237 *, 

238 static_input_indices: Iterable[int], 

239 capture_runnable: Callable[..., Any] | None = None, 

240 label: str = "joint step", 

241 output_clone_indices: Iterable[int] | None = None, 

242 recapture_coordinator: _RecaptureCoordinator | None = None, 

243 borrowed_input_indices: Iterable[int] = (), 

244 capture_boxed: bool = False, 

245 shared_input_keys: dict[int, str] | None = None, 

246 ) -> None: 

247 """Bind a region and optionally share proven-safe dynamic input storage. 

248 

249 ``shared_input_keys`` maps dynamic input indices to read-only producer 

250 names or region-private scratch slots. Scratch inputs must not mutate, 

251 escape through aliases, or retain asynchronous readers past the region. 

252 Clone all outputs for None, none for an empty iterable. 

253 """ 

254 self.runnable = runnable 

255 self.capture_runnable = capture_runnable or runnable 

256 self.label = label 

257 self.static_input_indices = set(static_input_indices) 

258 self.output_clone_indices = None if output_clone_indices is None else frozenset(output_clone_indices) 

259 self.recapture_coordinator = recapture_coordinator 

260 self.borrowed_input_indices = set(borrowed_input_indices) 

261 self.capture_boxed = capture_boxed 

262 self.shared_input_keys = dict(shared_input_keys or {}) 

263 self.warmed_up = False 

264 self.graph = None 

265 self.pool_id = None 

266 self.args = None 

267 self.input_specs = None 

268 self.output = None 

269 self._flat_outputs = None 

270 self._output_spec = None 

271 self._clone_output_indices: tuple[int, ...] = () 

272 self._input_guard = None 

273 self._static_pointers = () 

274 self._scalar_inputs = () 

275 self._container_inputs = {} 

276 

277 def _prepare_input_guard(self, args): 

278 """Record layout, scalar, container, and explicitly static address contracts.""" 

279 guard = RootGuardManager() 

280 try: 

281 guard.add_length_check_guard(len(args), []) 

282 except TypeError: 

283 # Keep the native length check with newer guard-recording bindings. 

284 guard.add_length_check_guard(len(args), [], None) 

285 pointers, scalars = [], [] 

286 self._container_inputs = {} 

287 for i, arg in enumerate(args): 

288 if not isinstance(arg, torch.Tensor): 

289 leaves, structure = tree_flatten_with_path(arg) 

290 if structure.is_leaf(): 

291 scalars.append((i, arg)) 

292 else: 

293 # Tensor leaves need layout guards, never Python equality; 

294 # only explicitly static containers retain their addresses. 

295 self._container_inputs[i] = ( 

296 structure, 

297 [ 

298 ( 

299 keystr(path), 

300 None if isinstance(value, torch.Tensor) else value, 

301 (value.shape, value.stride(), value.dtype, value.device, value.data_ptr()) 

302 if isinstance(value, torch.Tensor) 

303 else None, 

304 ) 

305 for path, value in leaves 

306 ], 

307 ) 

308 continue 

309 manager = guard.list_getitem_manager(i, f"input[{i}]", arg, GuardManagerType.GUARD_MANAGER) 

310 _add_tensor_input_guard(manager, arg, f"input[{i}]") 

311 if i in self.static_input_indices: 

312 pointers.append((i, arg.data_ptr())) 

313 self._input_guard = guard 

314 self._static_pointers = tuple(pointers) 

315 self._scalar_inputs = tuple(scalars) 

316 

317 @staticmethod 

318 def _tensor_change_reason(arg, spec, *, static): 

319 """Describe the first incompatible tensor layout or static address change.""" 

320 if not isinstance(arg, torch.Tensor): 

321 return f"Tensor -> {type(arg).__name__}" 

322 for field, old, new in zip( 

323 ("shape", "stride", "dtype", "device"), 

324 spec[:4], 

325 (arg.shape, arg.stride(), arg.dtype, arg.device), 

326 strict=True, 

327 ): 

328 if old != new: 

329 return f"{field} {old} -> {new}" 

330 if static and arg.data_ptr() != spec[4]: 

331 return f"static address {spec[4]:#x} -> {arg.data_ptr():#x}" 

332 return None 

333 

334 def _container_change_reason(self, args): 

335 """Validate nested input structure, tensor leaves, and Python constants.""" 

336 for i, (structure, saved_leaves) in self._container_inputs.items(): 

337 leaves, current_structure = tree_flatten_with_path(args[i]) 

338 if current_structure != structure: 

339 return f"input[{i}] container structure changed" 

340 for (_, value), (path, saved, spec) in zip(leaves, saved_leaves, strict=True): 

341 if spec is not None: 

342 reason = self._tensor_change_reason(value, spec, static=i in self.static_input_indices) 

343 if reason is not None: 

344 return f"input[{i}]{path} {reason}" 

345 elif value is not saved and (type(value) is not type(saved) or value != saved): 

346 return f"input[{i}]{path} scalar {saved!r} -> {value!r}" 

347 return None 

348 

349 def _fast_change_reason(self, args): 

350 for i, address in self._static_pointers: 

351 if args[i].data_ptr() != address: 

352 return f"input[{i}] static address {address:#x} -> {args[i].data_ptr():#x}" 

353 for i, saved in self._scalar_inputs: 

354 arg = args[i] 

355 if arg is not saved and (type(arg) is not type(saved) or arg != saved): 

356 return f"input[{i}] scalar {saved!r} -> {arg!r}" 

357 return None 

358 

359 def _input_change_reason(self, args): 

360 """Check current arguments against the captured input contracts.""" 

361 assert self.args is not None and self.input_specs is not None 

362 if len(args) != len(self.args): 

363 return f"argument count {len(self.args)} -> {len(args)}" 

364 reason = self._container_change_reason(args) 

365 if reason is not None: 

366 return reason 

367 # C++ guards check all tensor layouts without a Python loop per input. 

368 # Address checks remain explicit: tensor identity does not guard .data. 

369 if self._input_guard is not None and self._input_guard.check(args): 

370 return self._fast_change_reason(args) 

371 for i, (arg, saved, spec) in enumerate(zip(args, self.args, self.input_specs, strict=True)): 

372 if isinstance(saved, torch.Tensor): 

373 assert spec is not None 

374 reason = self._tensor_change_reason(arg, spec, static=i in self.static_input_indices) 

375 if reason is not None: 

376 return f"input[{i}] {reason}" 

377 elif ( 

378 i not in self._container_inputs and arg is not saved and (type(arg) is not type(saved) or arg != saved) 

379 ): 

380 return f"input[{i}] scalar {saved!r} -> {arg!r}" 

381 return None 

382 

383 def __call__(self, *args: Any) -> Any: 

384 """Execute a region using positional graph inputs.""" 

385 return self.call_boxed(list(args)) 

386 

387 def _capture_input(self, i, arg, pool): 

388 """Borrow stable state or stage a dynamic input using its proven ownership.""" 

389 if i in self.static_input_indices: 

390 return arg 

391 key = self.shared_input_keys.get(i) 

392 coordinator = self.recapture_coordinator 

393 # Tensor subclasses may override dispatch and aliasing semantics. 

394 if ( 

395 key is not None 

396 and coordinator is not None 

397 and i not in self.borrowed_input_indices 

398 and type(arg) is torch.Tensor # pylint: disable=unidiomatic-typecheck 

399 and arg.layout == torch.strided 

400 and not arg.is_conj() 

401 and not arg.is_neg() 

402 and _debug_has_internal_overlap(arg) == 0 

403 ): 

404 return coordinator.shared_input(pool, key, arg) 

405 return tree_map(lambda value: _clone_capture_input(value) if isinstance(value, torch.Tensor) else value, arg) 

406 

407 def _prepare_capture_inputs(self, args, pool=None): 

408 """Create persistent inputs and verify that staging preserves their layouts.""" 

409 self.args = tuple( 

410 self._capture_input(i, arg, pool) 

411 for i, arg in enumerate(args) 

412 ) 

413 self.input_specs = [ 

414 (arg.shape, arg.stride(), arg.dtype, arg.device, arg.data_ptr()) 

415 if isinstance(arg, torch.Tensor) 

416 else None 

417 for arg in args 

418 ] 

419 self._prepare_input_guard(args) 

420 for i, (arg, saved) in enumerate(zip(args, self.args, strict=True)): 

421 for source, destination in zip(tree_leaves(arg), tree_leaves(saved), strict=True): 

422 if isinstance(source, torch.Tensor) and source.stride() != destination.stride(): 

423 raise ValueError( 

424 f"ACLGraph {self.label}: dynamic input[{i}] copy must preserve strides; " 

425 f"shape={tuple(source.shape)}, source={source.stride()}, copied={destination.stride()}" 

426 ) 

427 

428 def _replay_handle_factory(self, torch_npu): 

429 """Create non-owning handles only for capture-pool storage owned by recorded work.""" 

430 protected_storages = { 

431 StorageWeakRef(value.untyped_storage()) 

432 for i, arg in enumerate(self.args) 

433 if i not in self.borrowed_input_indices 

434 for value in tree_leaves(arg) 

435 if isinstance(value, torch.Tensor) 

436 } 

437 

438 def _replay_handle(value): 

439 if ( 

440 self.recapture_coordinator is not None 

441 and isinstance(value, torch.Tensor) 

442 and value.device.type == "npu" 

443 and StorageWeakRef(value.untyped_storage()) not in protected_storages 

444 ): 

445 # The NPU backend exposes non-owning graph-pool handles only through this binding. 

446 handle = torch_npu._C._weak_ref_tensor(value) # pylint: disable=protected-access 

447 # The FSDP release helper recognizes this library-owned handle marker. 

448 handle._aclgraph_non_owning = True # pylint: disable=protected-access 

449 return handle 

450 return value 

451 

452 return _replay_handle 

453 

454 def _capture(self, args, torch_npu): 

455 """Prepare a fresh recording pool and discard staging after failed capture.""" 

456 coordinator = self.recapture_coordinator 

457 if coordinator is not None: 

458 if coordinator.graph_pool is None: 

459 coordinator.graph_pool = torch_npu.npu.graph_pool_handle() 

460 pool = coordinator.graph_pool 

461 else: 

462 pool = torch_npu.npu.graph_pool_handle() 

463 try: 

464 self._prepare_capture_inputs(args, pool) 

465 return self._capture_graph(args, torch_npu, pool) 

466 except BaseException: 

467 if coordinator is not None: 

468 coordinator.shared_input_buffers.pop(pool, None) 

469 raise 

470 

471 def _capture_graph(self, args, torch_npu, pool): 

472 """Record a region and preserve first-call output ownership for downstream work.""" 

473 graph = torch_npu.npu.NPUGraph() 

474 coordinator = self.recapture_coordinator 

475 capture_inputs = list(self.args) 

476 replay_handle = self._replay_handle_factory(torch_npu) 

477 self.args = tuple( 

478 tree_map(replay_handle, arg) if i in self.borrowed_input_indices else arg 

479 for i, arg in enumerate(self.args) 

480 ) 

481 args.clear() 

482 # All regions use the same default capture stream and execute once, 

483 # in joint-FX order. Capture-time outputs follow the caller's normal 

484 # liveness; replay only needs non-owning handles to their addresses. 

485 with torch_npu.npu.graph(graph, pool=pool): 

486 self.output = ( 

487 self.capture_runnable(capture_inputs) 

488 if self.capture_boxed 

489 else self.capture_runnable(*capture_inputs) 

490 ) 

491 # Join pending HCCL streams before ending this region's capture. 

492 for value in tree_leaves(self.output): 

493 if isinstance(value, torch.Tensor) and value.device.type == "npu": 

494 _c10d_functional.wait_tensor.default(value) 

495 self.graph = graph 

496 self.pool_id = pool 

497 captured_output = self.output 

498 if coordinator is not None: 

499 self.output = tree_map(replay_handle, captured_output) 

500 owner = getattr(self.capture_runnable, "__self__", None) 

501 if isinstance(owner, torch.fx.Interpreter): 

502 owner.env.clear() 

503 if self.output_clone_indices is None or self.output_clone_indices: 

504 self._prepare_output_clones() 

505 logger.info("ACLGraph %s: capture SUCCEEDED", self.label) 

506 return captured_output 

507 

508 def _prepare_output_clones(self): 

509 static_storages = { 

510 StorageWeakRef(value.untyped_storage()) 

511 for i, arg in enumerate(self.args) 

512 if i in self.static_input_indices and i not in self.borrowed_input_indices 

513 for value in tree_leaves(arg) 

514 if isinstance(value, torch.Tensor) 

515 } 

516 self._flat_outputs, self._output_spec = tree_flatten(self.output) 

517 self._clone_output_indices = tuple( 

518 i 

519 for i, value in enumerate(self._flat_outputs) 

520 if isinstance(value, torch.Tensor) 

521 and (self.output_clone_indices is None or i in self.output_clone_indices) 

522 and StorageWeakRef(value.untyped_storage()) not in static_storages 

523 ) 

524 

525 def _replay_outputs(self, captured_output): 

526 """Return live state and independent copies of outputs that escape the graph.""" 

527 if self.output_clone_indices is not None and not self.output_clone_indices: 

528 # During recording, owning tensors keep inputs live for subsequent 

529 # captures until their last FX consumer. Replay allocates no tensors 

530 # in this pool, so non-owning handles suffice on subsequent steps. 

531 return captured_output if captured_output is not None else self.output 

532 assert self._flat_outputs is not None and self._output_spec is not None 

533 # Downstream recordings must still own the un-cloned intermediates. 

534 # Replay handles become safe only after every region has been recorded. 

535 outputs = tree_leaves(captured_output) if captured_output is not None else list(self._flat_outputs) 

536 for i in self._clone_output_indices: 

537 outputs[i] = outputs[i].clone() 

538 return tree_unflatten(outputs, self._output_spec) 

539 

540 @torch.no_grad() 

541 def call_boxed(self, args: list[Any]) -> Any: 

542 """Warm up, record, or replay a region, consuming its argument list.""" 

543 torch_npu = _get_torch_npu() 

544 if self.recapture_coordinator is not None: 

545 self.recapture_coordinator.before_call(self, args) 

546 elif self.graph is not None and self._input_change_reason(args) is not None: 

547 raise ValueError("ACLGraph inputs changed without a recapture coordinator") 

548 if not self.warmed_up: 

549 output = self.runnable(*args) 

550 self.warmed_up = True 

551 logger.info("ACLGraph %s: warmup completed", self.label) 

552 return output 

553 captured_output = None 

554 if self.graph is None: 

555 captured_output = self._capture(args, torch_npu) 

556 else: 

557 for i, (arg, saved) in enumerate(zip(args, self.args, strict=True)): 

558 if isinstance(saved, torch.Tensor) and i not in self.static_input_indices: 

559 saved.copy_(arg) 

560 elif i in self._container_inputs and i not in self.static_input_indices: 

561 for source, destination in zip(tree_leaves(arg), tree_leaves(saved), strict=True): 

562 if isinstance(destination, torch.Tensor): 

563 destination.copy_(source) 

564 self.graph.replay() 

565 return self._replay_outputs(captured_output) 

566 

567 def teardown(self) -> None: 

568 """Release captured buffers or the coordination process group.""" 

569 self.graph = None 

570 self.pool_id = None 

571 self.args = None 

572 self.input_specs = None 

573 self.output = None 

574 self._flat_outputs = None 

575 self._output_spec = None 

576 self._clone_output_indices = () 

577 self._input_guard = None 

578 self._static_pointers = () 

579 self._scalar_inputs = () 

580 self._container_inputs = {} 

581 owner = getattr(self.capture_runnable, "__self__", None) 

582 if isinstance(owner, torch.fx.Interpreter): 

583 owner.env.clear() 

584 

585 

586class _PartitionInterpreter(torch.fx.Interpreter): 

587 """Release the caller's last references before entering a boxed region.""" 

588 

589 def __init__( 

590 self, module: torch.fx.GraphModule, *, staged_input_indices: Iterable[int] = (), 

591 input_aliases: dict[int, int] | None = None, 

592 ) -> None: 

593 """Keep normal FX liveness while staging changing user input storage.""" 

594 super().__init__(module) 

595 self._staged_input_indices = tuple(sorted(staged_input_indices)) 

596 self._input_buffers = {} 

597 self._input_aliases = input_aliases or {} 

598 self._coordinator = getattr(module, "_aclgraph_recapture_coordinator", None) 

599 self._eager_forward = ( 

600 module.forward if self._coordinator is not None and not self._coordinator.wrappers else None 

601 ) 

602 # Keep the last-use map, but perform collection before boxed calls. 

603 self.garbage_collect_values = False 

604 self._inputs = [node for node in self.graph.nodes if node.op == "placeholder"] 

605 self._body = [node for node in self.graph.nodes if node.op != "placeholder"] 

606 self._boxed_args = { 

607 node: itemgetter(*node.args) 

608 for node in self._body 

609 if node.op == "call_module" 

610 and node.args 

611 and not node.kwargs 

612 and all(isinstance(arg, torch.fx.Node) for arg in node.args) 

613 } 

614 

615 def run( 

616 self, *args: Any, initial_env: dict[torch.fx.Node, Any] | None = None, 

617 enable_io_processing: bool = True, 

618 ) -> Any: 

619 """Execute partitions and release values before entering captured regions.""" 

620 try: 

621 if self._coordinator is not None: 

622 self._coordinator.initialize() 

623 if self._eager_forward is not None and initial_env is None and enable_io_processing: 

624 return self._eager_forward(*args) 

625 if initial_env is not None or len(args) != len(self._inputs): 

626 return super().run(*args, initial_env=initial_env, enable_io_processing=enable_io_processing) 

627 if enable_io_processing: 

628 args = self.graph.process_inputs(*args) 

629 if self._staged_input_indices: 

630 args = self._stage_inputs(args) 

631 # Lifted parameters need bindings, not a Python interpreter call each. 

632 self.env = dict(zip(self._inputs, args, strict=True)) 

633 for node in self._body: 

634 result = self.env[node] = self.run_node(node) 

635 if node.op == "output": 

636 return self.graph.process_outputs(result) if enable_io_processing else result 

637 

638 raise RuntimeError("ACLGraph partition graph has no output node") 

639 finally: 

640 # Returned gradients outlive this call through the caller alone; 

641 # detaching also preserves an externally supplied initial_env. 

642 self.env = {} 

643 

644 def teardown(self) -> None: 

645 """Release interpreter-owned staging buffers after captured graphs close.""" 

646 self.env.clear() 

647 self._input_buffers.clear() 

648 

649 def _stage_inputs(self, args): 

650 """Update shared top-level input buffers while preserving declared aliases.""" 

651 # Share one persistent buffer across every consumer, including aliases 

652 # returned by captured regions. Update it once before this step's work. 

653 values = list(args) 

654 destinations, sources = [], [] 

655 for i in self._staged_input_indices: 

656 arg = args[i] 

657 if i in self._input_aliases: 

658 source = self._input_aliases[i] 

659 other = args[source] 

660 if arg.data_ptr() != other.data_ptr() or (arg.shape, arg.stride(), arg.dtype) != ( 

661 other.shape, 

662 other.stride(), 

663 other.dtype, 

664 ): 

665 raise ValueError(f"ACLGraph shared input alias changed: input[{i}] and input[{source}]") 

666 values[i] = values[source] 

667 continue 

668 saved = self._input_buffers.get(i) 

669 if saved is None or (saved.shape, saved.stride(), saved.dtype, saved.device) != ( 

670 arg.shape, 

671 arg.stride(), 

672 arg.dtype, 

673 arg.device, 

674 ): 

675 saved = self._input_buffers[i] = arg.detach().clone() 

676 else: 

677 destinations.append(saved) 

678 sources.append(arg) 

679 values[i] = saved 

680 if sources: 

681 _foreach_copy_(destinations, sources) 

682 return values 

683 

684 def run_node(self, n: torch.fx.Node) -> Any: 

685 """Drop last-use arguments before the wrapper records their consumer.""" 

686 region = self.fetch_attr(n.target) if n.op == "call_module" else None 

687 wrapper = getattr(region, "_aclgraph_wrapper", None) 

688 if wrapper is not None: 

689 fetch = self._boxed_args.get(n) 

690 if fetch is not None: 

691 values = fetch(self.env) 

692 boxed = [values] if len(n.args) == 1 else list(values) 

693 del values 

694 else: 

695 args, kwargs = self.fetch_args_kwargs_from_env(n) 

696 if kwargs: 

697 raise ValueError("ACLGraph partition calls must use positional inputs") 

698 boxed = list(args) 

699 del args 

700 for value in self.user_to_last_uses.get(n, []): 

701 del self.env[value] 

702 return wrapper.call_boxed(boxed) 

703 result = super().run_node(n) 

704 for value in self.user_to_last_uses.get(n, []): 

705 del self.env[value] 

706 return result 

707 

708 

709def install_aclgraph_runtime( 

710 graph_module: torch.fx.GraphModule, coordinator: _RecaptureCoordinator, *, 

711 staged_input_indices: Iterable[int] = (), input_aliases: dict[int, int] | None = None, 

712) -> torch.fx.GraphModule: 

713 """Validate every rank's capture plan at graph entry before any eager or captured work.""" 

714 object.__setattr__(graph_module, "_aclgraph_wrappers", coordinator.wrappers) 

715 object.__setattr__(graph_module, "_aclgraph_recapture_coordinator", coordinator) 

716 graph_module.forward = _PartitionInterpreter( 

717 graph_module, staged_input_indices=staged_input_indices, input_aliases=input_aliases, 

718 ).run 

719 return graph_module 

720 

721 

722def teardown_aclgraph(graph_module: torch.fx.GraphModule) -> None: 

723 """Release graphs before the caller destroys HCCL process groups.""" 

724 wrappers = getattr(graph_module, "_aclgraph_wrappers", ()) 

725 if any(wrapper.graph is not None for wrapper in wrappers): 

726 _get_torch_npu().npu.synchronize() 

727 for wrapper in wrappers: 

728 wrapper.teardown() 

729 coordinator = getattr(graph_module, "_aclgraph_recapture_coordinator", None) 

730 if coordinator is not None: 

731 coordinator.teardown() 

732 interpreter = getattr(graph_module.forward, "__self__", None) 

733 if isinstance(interpreter, _PartitionInterpreter): 

734 interpreter.teardown()