Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / codegen / emit / modeling.py: 86%

391 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"""Assemble the generated HF-style modeling file. 

16 

17The generated file is the original modeling source, verbatim, with two 

18appended layers: 

19 

20* a header banner recording where it came from, 

21* the adapter-driven inline patch — replaced modules and the TP / CP / EP 

22 strategies lowered into the copied source at their semantic sites. 

23 

24Boundary forwards are then lowered at the boundary classes. The artifact is 

25both an auditable source export and a directly executable model training entry. 

26Training still derives its live plan from the supplied YAML through the native 

27Trainer; preflight validates syntax and the recorded generation contract. 

28""" 

29 

30from __future__ import annotations 

31 

32import ast 

33import io 

34import keyword 

35import os 

36import tokenize 

37from typing import Any 

38 

39from hyper_parallel.codegen.source.composition import compose_nested_model_sources 

40from hyper_parallel.codegen.source.compat import sanitize_source_compat 

41from hyper_parallel.codegen.emit.parallel import lower_forward_boundaries 

42from hyper_parallel.codegen.emit.recorded import materialize_recorded_forwards 

43from hyper_parallel.codegen.inline.pipeline import _imported_forward_definition, render_inline_modeling_with_plan 

44from hyper_parallel.codegen.inline.component_source import collapse_unmodified_components 

45from hyper_parallel.codegen.inline.framework_spec import strategy_spec_for 

46from hyper_parallel.codegen.inline.targets import projected_target_path 

47 

48# --------------------------------------------------------------------------- 

49# source copy 

50# --------------------------------------------------------------------------- 

51 

52 

53def copy_original_modeling(source: Any) -> str: 

54 """Read the original modeling source text from a ``ResolvedSource``-like. 

55 

56 ``source`` is ``meta.source`` — the ``ResolvedSource.to_dict()`` form with 

57 a ``file_path`` key. Accepts either a dict or a ``ResolvedSource`` (the 

58 dict form is what the manager records, but the helper tolerates the live 

59 dataclass so it stays usable outside the meta path). 

60 

61 Args: 

62 source: Resolved source metadata containing the original modeling file. 

63 """ 

64 if isinstance(source, dict): 

65 path = source.get("file_path") 

66 else: 

67 path = getattr(source, "file_path", None) 

68 if not path or not os.path.isfile(path): 

69 raise FileNotFoundError( 

70 f"codegen emit: original modeling source is not a readable file " 

71 f"({path!r}); generation must run where the model's modeling file " 

72 "exists" 

73 ) 

74 with open(path, "r", encoding="utf-8", errors="replace") as handle: 

75 return handle.read() 

76 

77 

78def rewrite_relative_imports(text: str, module_name: str) -> str: 

79 """Rewrite ``from .xxx`` / ``from ...xxx`` imports to absolute imports. 

80 

81 HF modeling files commonly import siblings with a relative spec, e.g. 

82 ``from .configuration_qwen3 import Qwen3Config`` or ``from ...activations 

83 import ACT2FN``. The generated bundle is loaded by ``spec_from_file_location`` 

84 under a synthetic package (``hyper_parallel_generated.<digest>.<stem>``), so a 

85 relative spec resolves against that synthetic package instead of the real 

86 transformers package and fails with ``attempted relative import beyond 

87 top-level package``. 

88 

89 This anchors the relative spec on ``module_name`` (the original module's 

90 real dotted path, e.g. ``transformers.models.qwen3.modeling_qwen3``): N 

91 leading dots climb N-1 package levels above the module's parent package, then 

92 append the rest. ``from ...activations`` → ``from transformers.activations`` 

93 and ``from .configuration_qwen3`` → 

94 ``from transformers.models.qwen3.configuration_qwen3``. 

95 

96 ``module_name`` is ``"<remote>"`` for trusted remote code, which has no real 

97 package to anchor on — the rewrite is a no-op there (import handling for 

98 remote code keeps its relative imports). A non-dotted or unanchorable ``module_name`` 

99 is likewise left untouched. 

100 

101 Only the module-spec part of each relative import is rewritten; the symbol 

102 list, comments, and whitespace are preserved. It uses ``tokenize`` rather 

103 than a regex so relative-looking text inside string literals or comments is 

104 never touched. 

105 

106 Args: 

107 text: Original modeling source text. 

108 module_name: Fully qualified module name used to resolve relative imports. 

109 """ 

110 unless_anchor = _relative_anchor(module_name) 

111 if unless_anchor is None: 

112 return text 

113 text = _rewrite_dynamic_relative_imports(text, unless_anchor) 

114 

115 try: 

116 tokens = list(tokenize.generate_tokens(io.StringIO(text).readline)) 

117 except tokenize.TokenError: 

118 return text 

119 if not tokens: 

120 return text 

121 

122 edits: list[tuple[int, int, str]] = [] 

123 i = 0 

124 while i < len(tokens): 

125 edit, i = _relative_import_edit(tokens, i, unless_anchor) 

126 if edit is not None: 

127 edits.append(edit) 

128 

129 if not edits: 

130 return text 

131 return _splice(text, edits) 

132 

133 

134def _relative_import_edit( 

135 tokens: list[tokenize.TokenInfo], index: int, anchor: list[str] 

136) -> tuple[tuple[tuple[int, int], tuple[int, int], str] | None, int]: 

137 """Parse one token position into an absolute relative-import edit.""" 

138 token = tokens[index] 

139 if token.type != tokenize.NAME or token.string != "from": 

140 return None, index + 1 

141 cursor = _skip_import_trivia(tokens, index + 1) 

142 if cursor >= len(tokens) or not _is_dot_token(tokens[cursor]): 

143 return None, index + 1 

144 dots_token = tokens[cursor] 

145 dots = 0 

146 while cursor < len(tokens) and _is_dot_token(tokens[cursor]): 

147 dots += len(tokens[cursor].string) 

148 cursor += 1 

149 path, last_token, cursor = _relative_module_path(tokens, cursor) 

150 import_index = _skip_import_trivia(tokens, cursor) 

151 if import_index >= len(tokens) or tokens[import_index].string != "import": 

152 return None, index + 1 

153 absolute = _absolute_spec(anchor, dots, path) 

154 if absolute is None: 

155 return None, index + 1 

156 end = last_token.end if last_token is not None else dots_token.end 

157 return (dots_token.start, end, absolute), cursor + 1 

158 

159 

160def _skip_import_trivia(tokens: list[tokenize.TokenInfo], index: int) -> int: 

161 """Skip comments and physical/logical newlines between import tokens.""" 

162 trivia = {tokenize.NL, tokenize.NEWLINE, tokenize.COMMENT} 

163 while index < len(tokens) and tokens[index].type in trivia: 

164 index += 1 

165 return index 

166 

167 

168def _is_dot_token(token: tokenize.TokenInfo) -> bool: 

169 """Return whether a token contains only relative-import dots.""" 

170 return token.type == tokenize.OP and bool(token.string) and set(token.string) == {"."} 

171 

172 

173def _relative_module_path( 

174 tokens: list[tokenize.TokenInfo], index: int 

175) -> tuple[list[str], tokenize.TokenInfo | None, int]: 

176 """Collect the NAME (dot NAME)* portion of a relative import.""" 

177 path: list[str] = [] 

178 last_token = None 

179 while index < len(tokens): 

180 token = tokens[index] 

181 if token.type != tokenize.NAME or token.string == "import": 

182 break 

183 path.append(token.string) 

184 last_token = token 

185 index += 1 

186 if index >= len(tokens) or tokens[index].string != ".": 

187 break 

188 index += 1 

189 return path, last_token, index 

190 

191 

192def _rewrite_dynamic_relative_imports(text: str, anchor: list[str]) -> str: 

193 """Rewrite imports whose resolved package is not valid Python syntax.""" 

194 try: 

195 tree = ast.parse(text) 

196 except SyntaxError: 

197 return text 

198 edits = [] 

199 for node in ast.walk(tree): 

200 if not isinstance(node, ast.ImportFrom) or node.level == 0: 

201 continue 

202 absolute = _absolute_spec(anchor, node.level, (node.module or "").split(".")) 

203 if absolute is None or _is_import_syntax_safe(absolute): 

204 continue 

205 assignments = [] 

206 for alias in node.names: 

207 if alias.name == "*": 

208 raise ValueError( 

209 f"codegen cannot rewrite a wildcard import from dynamic module {absolute!r}" 

210 ) 

211 target = alias.asname or alias.name 

212 assignments.append( 

213 f"{target} = __import__({absolute!r}, fromlist=[{alias.name!r}]).{alias.name}" 

214 ) 

215 indent = " " * node.col_offset 

216 replacement = ("\n" + indent).join(assignments) 

217 edits.append( 

218 ( 

219 (node.lineno, node.col_offset), 

220 (node.end_lineno, node.end_col_offset), 

221 replacement, 

222 ) 

223 ) 

224 return _splice(text, edits) if edits else text 

225 

226 

227def _is_import_syntax_safe(module: str) -> bool: 

228 """Return whether every dotted component can appear in an import statement.""" 

229 return all( 

230 part.isidentifier() and not keyword.iskeyword(part) 

231 for part in module.split(".") 

232 ) 

233 

234 

235def _relative_anchor(module_name: str) -> list[str] | None: 

236 """Return the dotted package segments a relative spec anchors on, or None. 

237 

238 A real installed-module path (``transformers.models.qwen3.modeling_qwen3``) 

239 anchors. The ``"<remote>"`` sentinel (trusted remote code) and any 

240 non-dotted / placeholder-laden name cannot anchor — the caller leaves such 

241 imports untouched. 

242 """ 

243 if not isinstance(module_name, str) or not module_name: 

244 return None 

245 if "<" in module_name or ">" in module_name: 

246 return None 

247 segs = module_name.split(".") 

248 if len(segs) < 2 or any(not seg for seg in segs): 

249 return None 

250 return segs 

251 

252 

253def _absolute_spec(anchor: list[str], dots: int, path: list[str]) -> str | None: 

254 """Compute the absolute import spec for one relative import, or None. 

255 

256 ``anchor`` is the module's package segments (its path minus the final 

257 module segment). ``dots`` leading dots climb ``dots - 1`` package levels 

258 above the module's parent package, then append ``path``. Returns None when 

259 the relative import climbs above the package root (invalid source — leave 

260 it untouched rather than corrupt it). 

261 """ 

262 parent = anchor[:-1] 

263 climb = dots - 1 

264 if climb > len(parent): 

265 return None 

266 base_parts = parent if climb <= 0 else parent[: len(parent) - climb] 

267 parts = base_parts + path 

268 return ".".join(part for part in parts if part) 

269 

270 

271def _splice( 

272 text: str, edits: list[tuple[tuple[int, int], tuple[int, int], str]] 

273) -> str: 

274 """Splice absolute specs back into ``text`` by token (row, col) positions. 

275 

276 Edits are applied last-first so the earlier offsets stay valid. A single 

277 contiguous span is replaced in every case: the relative spec starts at the 

278 dots token and ends at the last module-path token (or the dots token when 

279 there is no path, i.e. ``from . import``). 

280 """ 

281 lines = text.splitlines(keepends=True) 

282 if not lines: 

283 return text 

284 line_offsets = [] 

285 acc = 0 

286 for line in lines: 

287 line_offsets.append(acc) 

288 acc += len(line) 

289 

290 def offset(row: int, col: int) -> int: 

291 """Map a source row and column to an absolute character offset. 

292 

293 Args: 

294 row: One-based source row. 

295 col: Zero-based column within that row. 

296 """ 

297 if 1 <= row <= len(line_offsets): 

298 return line_offsets[row - 1] + col 

299 return acc 

300 

301 positioned = sorted( 

302 ((offset(*start), offset(*end), new) for start, end, new in edits), 

303 key=lambda item: item[0], 

304 reverse=True, 

305 ) 

306 out = text 

307 for start, end, new in positioned: 

308 if start < end <= len(out): 

309 out = out[:start] + new + out[end:] 

310 return out 

311 

312 

313# --------------------------------------------------------------------------- 

314# file assembly 

315# --------------------------------------------------------------------------- 

316 

317 

318def emit_modeling_file(meta: Any, *, patch_plan: Any = None) -> str: 

319 """Assemble the full generated modeling file text. 

320 

321 Returns the text (not written to disk) so the caller can compute a diff 

322 first. The header banner carries the generation provenance; the source is 

323 copied verbatim, rewritten by the adapter-driven inline pipeline, and then 

324 lowered at the boundary classes. 

325 

326 Args: 

327 meta: Resolved model metadata and observed replacements. 

328 patch_plan: Optional precomputed structural patch plan. 

329 """ 

330 text = copy_original_modeling(meta.source) 

331 # Stale-source sanitize: a trust-remote-code modeling file ships with the 

332 # checkpoint and reflects the author's transformers, not the installed one. 

333 # Removing ``is_torch_fx_available`` (a transformers>=5.0 casualty) here 

334 # keeps the artifact importable without touching the source file. No-op 

335 # when the source does not import the symbol. 

336 text = sanitize_source_compat(text) 

337 module_name = ( 

338 meta.source.get("module_name") 

339 if isinstance(meta.source, dict) 

340 else getattr(meta.source, "module_name", "") 

341 ) 

342 text = rewrite_relative_imports(text, module_name) 

343 text = compose_nested_model_sources(text, meta) 

344 text, emission_meta = _apply_inline_modeling(text, meta, patch_plan=patch_plan) 

345 source_path = ( 

346 meta.source.get("file_path") 

347 if isinstance(meta.source, dict) 

348 else getattr(meta.source, "file_path", None) 

349 ) 

350 text = materialize_recorded_forwards( 

351 text, 

352 emission_meta, 

353 patch_plan=patch_plan, 

354 source_path=( 

355 None if getattr(emission_meta, "nested_components", None) else source_path 

356 ), 

357 ) 

358 text = _lower_forward_boundaries(text, emission_meta, module_name) 

359 text = collapse_unmodified_components(text) 

360 _verify_recorded_patch_materialization( 

361 text, emission_meta, patch_plan=patch_plan 

362 ) 

363 return _banner(meta) + text 

364 

365 

366def _verify_recorded_patch_materialization( 

367 text: str, 

368 meta: Any, 

369 *, 

370 patch_plan: Any = None, 

371) -> None: 

372 """Require every trainer-installed source-visible patch to be materialized.""" 

373 patches = patch_plan 

374 local_records = ( 

375 getattr(patches, "local_computes", ()) if patches is not None else () 

376 ) 

377 replacement_records = ( 

378 getattr(patches, "module_replacements", ()) if patches is not None else () 

379 ) 

380 wrapper_records = ( 

381 getattr(patches, "inner_wrappers", ()) if patches is not None else () 

382 ) 

383 if not local_records and not replacement_records and not wrapper_records: 

384 return 

385 tree = ast.parse(text) 

386 classes = _class_index(tree) 

387 materialized = getattr(meta, "materialized_patches", None) 

388 if isinstance(materialized, list): 

389 materialized.clear() 

390 missing = _verify_local_records(tree, classes, local_records, materialized) 

391 missing += _verify_replacement_records( 

392 tree, classes, replacement_records, materialized 

393 ) 

394 missing += _verify_wrapper_records( 

395 classes, wrapper_records, replacement_records, materialized 

396 ) 

397 if missing: 

398 raise RuntimeError( 

399 "codegen: trainer-installed source-visible patches were not " 

400 "materialized in the generated model source: " + ", ".join(missing) 

401 ) 

402 

403 

404def _class_index(tree: ast.AST) -> dict[str, ast.ClassDef]: 

405 """Index top-level classes by name.""" 

406 return { 

407 node.name: node 

408 for node in getattr(tree, "body", ()) 

409 if isinstance(node, ast.ClassDef) 

410 } 

411 

412 

413def _class_methods(host: ast.ClassDef) -> set[str]: 

414 """Return method names declared directly by a class.""" 

415 return { 

416 node.name 

417 for node in host.body 

418 if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) 

419 } 

420 

421 

422def _class_state_names(host: ast.ClassDef) -> set[str]: 

423 """Return simple class attributes declared by assignment.""" 

424 names = set() 

425 for child in host.body: 

426 targets = ( 

427 child.targets 

428 if isinstance(child, ast.Assign) 

429 else (child.target,) 

430 if isinstance(child, ast.AnnAssign) 

431 else () 

432 ) 

433 names.update(target.id for target in targets if isinstance(target, ast.Name)) 

434 return names 

435 

436 

437def _record_materialized( 

438 materialized: Any, fqn: str, host: str, kind: str, source_form: str 

439) -> None: 

440 """Append one materialization record when metadata is mutable.""" 

441 if isinstance(materialized, list): 

442 materialized.append( 

443 {"fqn": fqn, "host_class": host, "kind": kind, "source_form": source_form} 

444 ) 

445 

446 

447def _verify_local_records( 

448 tree: ast.AST, classes: dict[str, ast.ClassDef], records: Any, materialized: Any 

449) -> list[str]: 

450 """Verify local-compute records in one source unit.""" 

451 missing = [] 

452 for record in records: 

453 class_name = record.module_type.__name__ 

454 if _bound_function_patch_materialized(tree, record): 

455 _record_materialized( 

456 materialized, 

457 record.module_fqn, 

458 class_name, 

459 "local_compute", 

460 "bound_method_toggle_forward", 

461 ) 

462 continue 

463 host = classes.get(class_name) 

464 if host is None: 

465 continue 

466 valid = {"_forward_impl", "forward"} <= _class_methods( 

467 host 

468 ) and "ep_enable" in _class_state_names(host) 

469 if valid: 

470 _record_materialized( 

471 materialized, 

472 record.module_fqn, 

473 class_name, 

474 "local_compute", 

475 "same_class_toggle_forward", 

476 ) 

477 else: 

478 missing.append(f"{record.module_fqn} ({class_name})") 

479 return missing 

480 

481 

482def _verify_replacement_records( 

483 tree: ast.AST, classes: dict[str, ast.ClassDef], records: Any, materialized: Any 

484) -> list[str]: 

485 """Verify replacement constructors in one source unit.""" 

486 bound_names = { 

487 node.id for node in ast.walk(tree) if isinstance(node, ast.Name) 

488 } | set(classes) 

489 missing = [] 

490 for record in records: 

491 constructor = getattr(record, "factory", None) or record.replacement_type 

492 name = constructor.__name__ 

493 if name not in bound_names: 

494 name = record.replacement_type.__name__ 

495 calls = [node for node in ast.walk(tree) 

496 if isinstance(node, ast.Call) and _call_name(node.func) == name] 

497 visible = name in bound_names and bool(calls) and _replacement_calls_cover_fqn(calls, record.module_fqn) 

498 if visible: 

499 _record_materialized( 

500 materialized, 

501 record.module_fqn, 

502 name, 

503 "module_replacement", 

504 "constructor", 

505 ) 

506 else: 

507 missing.append(f"{record.module_fqn} (replacement {name})") 

508 return missing 

509 

510 

511def _replacement_calls_cover_fqn(calls: list[ast.Call], fqn: str) -> bool: 

512 """Require exact coverage when emitted constructors name their observed paths.""" 

513 explicit = {keyword.value.value for call in calls for keyword in call.keywords 

514 if keyword.arg == "module_fqn" and isinstance(keyword.value, ast.Constant) 

515 and isinstance(keyword.value.value, str) and keyword.value.value} 

516 return not explicit or fqn in explicit 

517 

518 

519def _wrapper_identity(record: Any) -> tuple[Any, str, str]: 

520 """Return target type, host name, and target FQN for a wrapper record.""" 

521 target_type = getattr(record, "target_type", None) 

522 host_name = ( 

523 target_type.__name__ 

524 if target_type is not None 

525 else type(record.request.target).__name__ 

526 ) 

527 target_fqn = ( 

528 record.module_fqn 

529 if record.target_fqn == "self" 

530 else f"{record.module_fqn}.{record.target_fqn}" 

531 ) 

532 return target_type, host_name, target_fqn 

533 

534 

535def _wrapper_source_form( 

536 classes: dict[str, ast.ClassDef], host: ast.ClassDef, record: Any, replacements: Any 

537) -> str | None: 

538 """Return the concrete source form that materializes a wrapper.""" 

539 definition = getattr(record, "observed_definition", None) 

540 if definition is not None: 

541 return _observed_method_form(host, definition, getattr(record, "target_type", None)) 

542 source_form = _declared_wrapper_form(host, record) 

543 if source_form is None or source_form == "observed_native_methods": 

544 return source_form 

545 return _wrapper_class_form(classes, host, record, replacements) 

546 

547 

548def _wrapper_class_form( 

549 classes: dict[str, ast.ClassDef], host: ast.ClassDef, record: Any, replacements: Any 

550) -> str | None: 

551 """Identify the class form after verifying the selected wrapper computation.""" 

552 if ( 

553 "forward" in _class_methods(host) 

554 and "cp_enable" in _class_state_names(host) 

555 and _class_dispatch_reads_state(host, "cp_enable") 

556 ): 

557 return "same_class_toggle_forward" 

558 subclass = next( 

559 ( 

560 node 

561 for node in classes.values() 

562 if any( 

563 isinstance(base, ast.Name) and base.id == host.name 

564 for base in node.bases 

565 ) 

566 and "forward" in _class_methods(node) 

567 ), 

568 None, 

569 ) 

570 if subclass is not None: 

571 return "subclass_forward" 

572 target_type = getattr(record, "target_type", None) 

573 replacement_backed = any( 

574 item.module_fqn == record.module_fqn and item.replacement_type is target_type 

575 for item in replacements 

576 ) 

577 if replacement_backed and {"_forward_impl", "forward"} <= _class_methods(host): 

578 return "replacement_forward_runtime_binding" 

579 return None 

580 

581 

582def _declared_wrapper_form(host: ast.ClassDef, record: Any) -> str | None: 

583 """Require computation from the selected wrapper, not an unrelated CP flag.""" 

584 wrapper = getattr(record, "wrapper", None) 

585 if wrapper is None: 

586 return "structural" 

587 arguments = getattr(record, "factory_kwargs", {}) 

588 try: 

589 spec = strategy_spec_for( 

590 projected_target_path(wrapper), inner_wrapper=True, 

591 construction_kwargs=tuple(f"{name}={value!r}" for name, value in sorted(arguments.items())), 

592 ) 

593 except RuntimeError: 

594 return None 

595 if spec is None or spec.subclass_shell is None: 

596 return None 

597 if spec.definition is not None: 

598 return _observed_method_form(host, spec.definition, getattr(record, "target_type", None)) 

599 expected = _wrapper_helper_calls(spec) 

600 actual = _forward_calls(host) 

601 visible = bool(expected) and all( 

602 any(_native_call_visible(call, candidate) for candidate in actual) for call in expected 

603 ) 

604 return "native_helper_calls" if visible else None 

605 

606 

607def _wrapper_helper_calls(spec: Any) -> list[ast.Call]: 

608 """Read imported computation calls from the selected native wrapper body.""" 

609 imports = {name for item in spec.imports for name in item.names} 

610 return [node for node in ast.walk(ast.parse(spec.subclass_shell)) if isinstance(node, ast.Call) 

611 and isinstance(node.func, ast.Name) and node.func.id in imports] 

612 

613 

614def _forward_calls(host: ast.ClassDef) -> list[ast.Call]: 

615 """Collect calls from the emitted dispatch and preserved local computation.""" 

616 methods = [node for node in host.body if isinstance(node, ast.FunctionDef) 

617 and node.name in {"forward", "_forward_impl"}] 

618 return [node for method in methods for node in ast.walk(method) if isinstance(node, ast.Call)] 

619 

620 

621def _native_call_visible(expected: ast.Call, actual: ast.Call) -> bool: 

622 """Match a native helper and its explicit literal configuration arguments.""" 

623 if ast.dump(expected.func) != ast.dump(actual.func): 

624 return False 

625 for index, argument in enumerate(expected.args): 

626 if isinstance(argument, ast.Constant) or isinstance(argument, ast.Name) and argument.id == "self": 

627 if index >= len(actual.args) or ast.dump(argument) != ast.dump(actual.args[index]): 

628 return False 

629 keywords = {item.arg: item.value for item in actual.keywords} 

630 return all(item.arg in keywords and ast.dump(item.value) == ast.dump(keywords[item.arg]) 

631 for item in expected.keywords if isinstance(item.value, ast.Constant)) 

632 

633 

634def _observed_method_form(host: ast.ClassDef, definition: str, native_type: type | None) -> str | None: 

635 """Verify each observed computation, allowing only the existing boundary extraction.""" 

636 native_base = f"{native_type.__module__}.{native_type.__name__}" if native_type is not None else "" 

637 if any(ast.unparse(base) == native_base for base in host.bases): 

638 definition = _imported_forward_definition(definition) 

639 methods = {node.name: node for node in host.body if isinstance(node, ast.FunctionDef)} 

640 for expected in ast.parse(definition).body: 

641 if not isinstance(expected, ast.FunctionDef): 

642 return None 

643 if ast.get_docstring(expected) is not None: 

644 expected.body[0].value.value = ast.get_docstring(expected) 

645 candidates = [methods.get(expected.name)] 

646 if expected.name == "forward": 

647 candidates.append(methods.get("_forward_impl")) 

648 matched = False 

649 for candidate in candidates: 

650 if candidate is None: 

651 continue 

652 candidate = ast.parse(ast.unparse(candidate)).body[0] 

653 candidate.name = expected.name 

654 if ast.get_docstring(candidate) is not None: 

655 candidate.body[0].value.value = ast.get_docstring(candidate) 

656 if ast.dump(candidate) == ast.dump(expected): 

657 matched = True 

658 if not matched: 

659 return None 

660 return "observed_native_methods" 

661 

662 

663def _verify_wrapper_records( 

664 classes: dict[str, ast.ClassDef], records: Any, replacements: Any, materialized: Any 

665) -> list[str]: 

666 """Verify inner-wrapper records in one source unit.""" 

667 missing = [] 

668 for record in records: 

669 _, host_name, target_fqn = _wrapper_identity(record) 

670 host = classes.get(host_name) 

671 if host is None: 

672 continue 

673 source_form = _wrapper_source_form(classes, host, record, replacements) 

674 if source_form: 

675 _record_materialized( 

676 materialized, target_fqn, host_name, "inner_wrapper", source_form 

677 ) 

678 else: 

679 missing.append(f"{target_fqn} (inner wrapper for {host_name})") 

680 return missing 

681 

682 

683def _call_name(node: ast.AST) -> str | None: 

684 """Return the terminal name of a constructor call expression.""" 

685 if isinstance(node, ast.Name): 

686 return node.id 

687 if isinstance(node, ast.Attribute): 

688 return node.attr 

689 return None 

690 

691 

692def verify_recorded_patch_bundle( 

693 files: dict[str, str], 

694 *, 

695 patch_plan: Any = None, 

696) -> None: 

697 """Verify recorded local-compute patches across all generated source units. 

698 

699 Args: 

700 files: Generated file names mapped to their source text. 

701 patch_plan: Recorded patches whose generated bindings must remain visible. 

702 """ 

703 records = ( 

704 getattr(patch_plan, "local_computes", ()) if patch_plan is not None else () 

705 ) 

706 wrappers = ( 

707 getattr(patch_plan, "inner_wrappers", ()) if patch_plan is not None else () 

708 ) 

709 trees = { 

710 name: ast.parse(text) for name, text in files.items() if name.endswith(".py") 

711 } 

712 missing = [ 

713 f"{record.module_fqn} ({record.module_type.__name__})" 

714 for record in records 

715 if not any(_tree_has_local_record(tree, record) for tree in trees.values()) 

716 ] 

717 if missing: 

718 raise RuntimeError( 

719 "codegen: recorded local-compute patches were not materialized " 

720 "in their owning source units: " + ", ".join(missing) 

721 ) 

722 replacements = getattr(patch_plan, "module_replacements", ()) 

723 missing_wrappers = [ 

724 f"{record.module_fqn} ({_wrapper_identity(record)[1]})" 

725 for record in wrappers 

726 if not any( 

727 _tree_has_wrapper_record(tree, record, replacements) 

728 for tree in trees.values() 

729 ) 

730 ] 

731 if missing_wrappers: 

732 raise RuntimeError( 

733 "codegen: recorded inner-wrapper patches were not materialized " 

734 "in their owning source units: " + ", ".join(missing_wrappers) 

735 ) 

736 if any("HPCodegen" in text for text in files.values()): 

737 raise RuntimeError( 

738 "codegen: generated bundle contains forbidden HPCodegen class names" 

739 ) 

740 

741 

742def _tree_has_local_record(tree: ast.AST, record: Any) -> bool: 

743 """Return whether one source tree materializes a local-compute record.""" 

744 if _bound_function_patch_materialized(tree, record): 

745 return True 

746 host = _class_index(tree).get(record.module_type.__name__) 

747 return ( 

748 host is not None 

749 and {"_forward_impl", "forward"} <= _class_methods(host) 

750 and "ep_enable" in _class_state_names(host) 

751 ) 

752 

753 

754def _tree_has_wrapper_record(tree: ast.AST, record: Any, replacements: Any) -> bool: 

755 """Return whether one source tree materializes an inner-wrapper record.""" 

756 _, class_name, _ = _wrapper_identity(record) 

757 classes = _class_index(tree) 

758 host = classes.get(class_name) 

759 return host is not None and _wrapper_source_form(classes, host, record, replacements) is not None 

760 

761 

762def _class_dispatch_reads_state(host: ast.ClassDef, state_name: str) -> bool: 

763 """Return whether a class dispatches on one state flag in either layer.""" 

764 methods = ( 

765 child 

766 for child in host.body 

767 if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)) 

768 and child.name in {"forward", "_forward_impl"} 

769 ) 

770 return any( 

771 isinstance(node, ast.Attribute) 

772 and isinstance(node.value, ast.Name) 

773 and node.value.id == "self" 

774 and node.attr == state_name 

775 for method in methods 

776 for node in ast.walk(method) 

777 ) 

778 

779 

780def _bound_function_patch_materialized(tree: ast.AST, record: Any) -> bool: 

781 """Return whether a ``MethodType`` forward has an explicit EP toggle.""" 

782 function_name = getattr(record.original_forward, "__name__", "") 

783 if not function_name: 

784 return False 

785 impl_name = f"{function_name}_hp_impl" 

786 functions = { 

787 node.name: node 

788 for node in getattr(tree, "body", ()) 

789 if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) 

790 } 

791 wrapper = functions.get(function_name) 

792 if wrapper is None or impl_name not in functions: 

793 return False 

794 return _function_reads_ep_toggle(wrapper) and _tree_binds_method_impl( 

795 tree, impl_name 

796 ) 

797 

798 

799def _function_reads_ep_toggle(wrapper: ast.AST) -> bool: 

800 """Return whether a function reads the instance EP enable flag.""" 

801 return any( 

802 isinstance(node, ast.Attribute) 

803 and isinstance(node.value, ast.Name) 

804 and node.value.id == "self" 

805 and node.attr == "ep_enable" 

806 for node in ast.walk(wrapper) 

807 ) 

808 

809 

810def _tree_binds_method_impl(tree: ast.AST, impl_name: str) -> bool: 

811 """Return whether a tree binds an implementation through MethodType.""" 

812 return any( 

813 isinstance(node, ast.Assign) 

814 and any( 

815 isinstance(target, ast.Attribute) and target.attr == "_forward_impl" 

816 for target in node.targets 

817 ) 

818 and isinstance(node.value, ast.Call) 

819 and _call_name(node.value.func) == "MethodType" 

820 and node.value.args 

821 and isinstance(node.value.args[0], ast.Name) 

822 and node.value.args[0].id == impl_name 

823 for node in ast.walk(tree) 

824 ) 

825 

826 

827def _apply_inline_modeling( 

828 text: str, 

829 meta: Any, 

830 *, 

831 patch_plan: Any = None, 

832) -> tuple[str, Any]: 

833 """Render the artifact through the adapter-driven inline source pipeline.""" 

834 

835 source = getattr(meta, "source", None) 

836 architecture = ( 

837 source.get("architecture") 

838 if isinstance(source, dict) 

839 else getattr(source, "architecture", None) 

840 ) 

841 return render_inline_modeling_with_plan( 

842 text, 

843 meta, 

844 model_type=architecture, 

845 patch_plan=patch_plan, 

846 ) 

847 

848 

849def _lower_forward_boundaries(text: str, meta: Any, module_name: str) -> str: 

850 """Sink boundary wrappers into the model's ``forward`` bodies. 

851 

852 Each boundary class's ``forward`` is rewritten to redistribute through 

853 the instance-bound compiled plan and run the region's compute 

854 explicitly. A boundary whose class cannot be resolved or 

855 whose per-class contract differs across FQNs fails fast — a silently 

856 dropped redistribution would change the model's numeric behavior. 

857 

858 Fresh on the unmodified source text, so offsets stay valid for the whole 

859 call. The ``local_compute_fn`` / ``inner_wrapper`` members the rewritten 

860 forward references are bound by the runtime parallelize step, so the 

861 generated file stays runtime-importable without a mesh. 

862 

863 ``boundary_classes`` is the observed FQN -> class-name map. When it is 

864 empty there are no source-level boundaries to lower, so the source remains 

865 untouched. 

866 """ 

867 boundary_classes = getattr(meta, "boundary_classes", None) or {} 

868 if not boundary_classes: 

869 return text 

870 return lower_forward_boundaries( 

871 text, 

872 meta, 

873 boundary_classes=boundary_classes, 

874 module_name=module_name, 

875 ) 

876 

877 

878def _banner(meta: Any) -> str: 

879 """Render the provenance banner comment.""" 

880 source = meta.source if isinstance(meta.source, dict) else _source_dict(meta.source) 

881 pd = meta.parallel_dims or {} 

882 lines = [ 

883 "# Generated by codegen. DO NOT EDIT MANUALLY.", 

884 "#", 

885 f"# source : {source.get('module_name', '')}", 

886 f"# architecture : {source.get('architecture', '')}", 

887 f"# parallel_dims: tp={pd.get('tp_size', 1)} cp={pd.get('cp_size', 1)} " 

888 f"ep={pd.get('ep_size', 1)} pp={pd.get('pp_size', 1)} " 

889 f"sp={pd.get('sequence_parallel', False)} " 

890 f"loss_parallel={pd.get('loss_parallel', False)}", 

891 f"# injections : {len(getattr(meta, 'injections', []) or [])} rule(s)", 

892 "# runtime : mesh / FSDP2 / PP / AC / compile still handled by runtime", 

893 "#", 

894 "# [HYPER PLAN] training derives a live plan from its YAML and this model;", 

895 "# Regenerate this file from the training YAML after strategy changes.", 

896 "#", 

897 "", 

898 ] 

899 for record in getattr(meta, "module_overrides", None) or (): 

900 source_type = (record.get("module_type") or "unknown").rsplit(".", 1)[-1] 

901 implementation = (record.get("construction") or {}).get("implementation") 

902 target = (implementation or record.get("factory") or record.get("replacement_target") or "unknown") 

903 target = target.replace(":", ".", 1).rsplit(".", 1)[-1] 

904 for fqn in record.get("fqns") or (record.get("fqn"),): 

905 if fqn is not None: 

906 lines.insert(-1, f"# {fqn}: {source_type} -> {target}") 

907 if getattr(meta, "module_overrides", None): 

908 lines.insert(-1, "#") 

909 return "\n".join(lines) 

910 

911 

912def _source_dict(source: Any) -> dict[str, Any]: 

913 if source is None: 

914 return {} 

915 if isinstance(source, dict): 

916 return source 

917 return { 

918 "module_name": getattr(source, "module_name", ""), 

919 "file_path": getattr(source, "file_path", ""), 

920 "architecture": getattr(source, "architecture", ""), 

921 } 

922 

923 

924__all__ = [ 

925 "copy_original_modeling", 

926 "emit_modeling_file", 

927 "rewrite_relative_imports", 

928]