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

311 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"""Lower frozen boundary transitions into reviewable forward methods. 

16 

17The pure boundary classifier selects identity, static TP or generic 

18redistribution forms. Boundaries are keyed by FQN, while a method rewrite is 

19shared by every instance of its class. The emitter therefore groups compatible 

20contracts by class and preserves the original method as ``_forward_impl``. 

21 

22Rendered forwards expose placement transitions and native CP dispatch. Their 

23``_hp_boundary`` and ``_hp_tp`` references describe runtime dependencies; this 

24module does not install those fields or make the artifact a training backend. 

25Native Trainer continues to apply its own per-instance plan and wrappers. 

26""" 

27from __future__ import annotations 

28 

29import ast 

30import json 

31import logging 

32import textwrap 

33from typing import Any, Iterator, Optional 

34 

35from hyper_parallel.codegen.astkit.edits import ( 

36 TextEdit, 

37 apply_edits, 

38 replace_function_body, 

39) 

40from hyper_parallel.codegen.astkit.index import ( 

41 FunctionInfo, 

42 SourceIndex, 

43 build_source_index, 

44 returns_any_value, 

45 returns_single_value, 

46) 

47from hyper_parallel.codegen.plan.boundary_forms import ( 

48 FORM_GENERIC, 

49 FORM_IDENTITY, 

50 FORM_REGION, 

51 FORM_TP_COLLECTIVE, 

52 BoundaryForm, 

53 TransitionOp, 

54 classify_boundary_form, 

55 is_boundary_entry, 

56) 

57from hyper_parallel.codegen.emit.patches import local_compute_binding_name 

58 

59#: Injection keys that describe how a boundary's compute is regioned. 

60_INJECTION_KEYS = ("inner_wrapper", "inner_target", "inner_out_src", "local_compute_fn") 

61 

62 

63def lower_forward_boundaries( 

64 source_text: str, 

65 frozen_plan: Any, 

66 *, 

67 boundary_classes: Optional[dict[str, str]] = None, 

68 module_name: str = "", 

69) -> str: 

70 """Render each boundary class's observed redistribution and computation. 

71 

72 ``frozen_plan`` is the meta/param-plan dict or a ``CodegenMeta``; the 

73 plan entries are read via ``_plan_field``. ``boundary_classes`` 

74 is the FQN -> class name map (``meta.boundary_classes``); when omitted it 

75 degrades to the class name looked up from the source index itself, which is 

76 only correct if every boundary FQN's leaf class name equals the key's tail — 

77 ``_class_for_fqn``. The plan's active axes (``mesh_dim_names``) drive 

78 :func:`classify_boundary_form`; the classified form plus the source-side 

79 structural gates decide which template each class gets (see the module 

80 docstring). 

81 

82 Returns the patched source text. This function only rewrites the 

83 ``forward`` bodies; the rewritten bodies reference the ``_hp_boundary`` 

84 / ``_hp_tp`` runtime interfaces. This pass does not bind their state 

85 or emit per-boundary global constants. 

86 """ 

87 if _plan_field(frozen_plan, "status") == "not_required": 

88 raise ValueError("codegen emit: not_required snapshot has no parallel boundaries") 

89 edits: list[TextEdit] = [] 

90 index = build_source_index(source_text) 

91 for class_name, form, emitted, func, injection, deferred_bias in iter_emitted_forms( 

92 source_text, 

93 frozen_plan, 

94 boundary_classes=boundary_classes, 

95 module_name=module_name, 

96 ): 

97 if emitted == FORM_IDENTITY: 

98 # Pruned: the runtime's install path covers the exact no-op / 

99 # to-local semantics with its generic wrapper, so leaving the 

100 # original forward untouched is behavior-preserving. 

101 if deferred_bias: 

102 # D-22: an unrewritten forward never calls the exit hook, so 

103 # the suppressed bias would silently vanish — fail fast 

104 # instead (the planner defers only rowwise-bias exits that 

105 # reduce, which classify as non-identity, so this is a 

106 # mis-declared plan, not a supported shape). 

107 raise NotImplementedError( 

108 f"lower_forward_boundaries: boundary class {class_name!r} " 

109 "prunes to identity but declares deferred bias params; an " 

110 "identity forward has no exit hook to re-add them" 

111 ) 

112 continue 

113 host = index.find_class(class_name) 

114 dispatch = (_cp_dispatch_call(source_text[func.body_start:func.body_end]) 

115 if "_forward_impl" in host.methods else None) 

116 body = _build_forward_body( 

117 source_text, injection, func, form, emitted, deferred_bias, 

118 inner_compute=ast.unparse(dispatch) if dispatch is not None else None, 

119 ) 

120 # Keep the original forward as ``_forward_impl``. The 

121 # extracted method is inserted BEFORE the ``def forward`` (zero-width 

122 # edit at ``def_offset``), and the rewritten body replaces the original 

123 # body at ``body_start`` — the two spans never overlap, so the 

124 # incremental-shift validation in ``_apply_edits`` passes. The static 

125 # form additionally prefixes the class marker naming the form. 

126 marker = _TP_FORM_MARKER_LINE if emitted == FORM_TP_COLLECTIVE else None 

127 impl = None if dispatch is not None else _build_forward_impl_edit(source_text, func, prefix=marker) 

128 if impl is not None: 

129 edits.append(impl) 

130 edits.extend(replace_function_body(source_text, func, body, indent="")) 

131 if not edits: 

132 return source_text 

133 

134 nested = _validate_no_circular(edits) 

135 if nested: 

136 raise ValueError( 

137 "lower_forward_boundaries: edits overlap (circular class nesting); " 

138 "cannot safely rewrite: " + ", ".join(nested) 

139 ) 

140 return apply_edits(source_text, edits) 

141 

142 

143#: Class attribute a ``tp_collective`` forward carries, naming its form so the 

144#: runtime install path and preflight can recognize the static template. 

145TP_FORM_ATTRIBUTE = "_hp_boundary_form" 

146#: The marker value naming the statically lowered TP-collective form. 

147TP_FORM_MARKER = "tp_collective" 

148#: The emitted marker statement (method indent, followed by a blank line). 

149_TP_FORM_MARKER_LINE = f' {TP_FORM_ATTRIBUTE} = "{TP_FORM_MARKER}"\n\n' 

150 

151 

152def iter_emitted_forms( 

153 source_text: str, 

154 frozen_plan: Any, 

155 *, 

156 boundary_classes: Optional[dict[str, str]] = None, 

157 module_name: str = "", 

158) -> Iterator[tuple[str, BoundaryForm, str, FunctionInfo, Any, bool]]: 

159 """Yield every boundary class's emit decision over ``source_text``. 

160 

161 Single decision path shared by the emitter 

162 (:func:`lower_forward_boundaries`) and the train-time preflight 

163 (``check/preflight.verify_boundary_forms``): classification 

164 (:func:`classify_boundary_form`) plus the structural gates 

165 (:func:`resolve_emitted_form`), per boundary class. Yields 

166 ``(class_name, form, emitted, func, injection, deferred_bias)`` — 

167 ``form`` the classifier's verdict, ``emitted`` the form actually 

168 rendered after the gates, ``func`` the class's ``forward`` 

169 :class:`FunctionInfo`, ``injection`` the class's frozen injection rule 

170 (``None`` when absent), and ``deferred_bias`` whether the class's 

171 canonical entry carries D-22 deferred bias params (the emitted exit 

172 then calls ``self._hp_deferred_bias(outputs)`` after the output 

173 redistribution). 

174 

175 Boundary classes are iterated in sorted ``class_name`` order. The 

176 grouping walks ``param_plan``, whose insertion order is NOT stable 

177 across the write/reload cycle: ``meta.param_plan`` is persisted with 

178 ``json.dump(..., sort_keys=True)``, which reorders the keys 

179 alphabetically, so reload-ing the meta yields a different class order 

180 than the in-memory freeze did. Sorting here makes the emitted byte 

181 stream a pure function of which classes are boundaries, independent of 

182 how ``param_plan`` reached us. 

183 """ 

184 index = build_source_index(source_text) 

185 param_plan = _plan_field(frozen_plan, "param_plan") or {} 

186 injections = _plan_field(frozen_plan, "injections") or [] 

187 injection_by_class = _index_injections_by_class( 

188 injections, boundary_classes, index, param_plan 

189 ) 

190 mesh_dim_names = tuple(_plan_field(frozen_plan, "mesh_dim_names") or ()) 

191 

192 groups = _group_boundaries_by_class( 

193 param_plan, boundary_classes, index, module_name=module_name 

194 ) 

195 for class_name in sorted(groups): 

196 group = groups[class_name] 

197 # Fail fast when one class's FQNs disagree on the contract: one shared 

198 # ``forward`` cannot carry two boundary plans. The canonical entry is 

199 # the per-class contract every FQN agreed on. 

200 canonical_entry = _verify_class_contract(group, class_name) 

201 func = _require_forward(index, class_name) 

202 injection = injection_by_class.get(class_name) 

203 form = classify_boundary_form(canonical_entry, mesh_dim_names, injection) 

204 emitted = resolve_emitted_form(source_text, func, form) 

205 deferred_bias = bool(canonical_entry.get("deferred_bias_params")) 

206 yield class_name, form, emitted, func, injection, deferred_bias 

207 

208 

209def resolve_emitted_form( 

210 source_text: str, 

211 func: FunctionInfo, 

212 form: BoundaryForm, 

213) -> str: 

214 """The form the emitter actually renders for one classified boundary. 

215 

216 The classifier's ``tp_collective`` is an *optimistic* verdict: the static 

217 template additionally requires the source-side structural gates (no 

218 ``*args``, value returns, declared inputs binding to forward parameters, 

219 output ops targeting the first output). A boundary that fails a gate 

220 renders as ``generic`` instead. This resolver is the single decision 

221 shared by the emitter and preflight, so the emitted file and the train-time 

222 check can never disagree about which template a class got. 

223 """ 

224 if form.form in (FORM_IDENTITY, FORM_REGION, FORM_GENERIC): 

225 return form.form 

226 if _static_gates_pass(source_text, func, form): 

227 return FORM_TP_COLLECTIVE 

228 return FORM_GENERIC 

229 

230 

231def _static_gates_pass(source_text: str, func: FunctionInfo, form: BoundaryForm) -> bool: 

232 """Whether the static bare-operator template is admissible for ``func``. 

233 

234 Gates (each mirrors a concrete way the generic engine is more general 

235 than a static rewrite): 

236 

237 1. No ``*args`` — a positional variable tail cannot be enumerated 

238 statically. ``**kwargs`` is allowed and is re-passed by name. 

239 2. Every ``return`` carries a value. Single-value returns receive output 

240 ops directly; tuple returns receive index-0 output ops and are 

241 rebuilt, matching the compiled plan's output-index behavior. 

242 3. Every declared input name binds to a forward parameter — the generic 

243 engine skips an ``in_src`` name the caller never passed (``_get_arg`` 

244 default ``None``); the static template would reference an unbound 

245 variable instead, so a declared name outside the signature disqualifies 

246 the static form. 

247 4. Every non-identity output op targets the first declared output — with a 

248 single-value return the compiled plan applies index-0 ops only; an op 

249 mapped to a later output position cannot be expressed statically. 

250 """ 

251 if func.vararg_name is not None: 

252 return False 

253 if not returns_any_value(source_text, func): 

254 return False 

255 signature_names = set(func.param_names) | set(func.kwonly_names) 

256 if not set(form.in_declared) <= signature_names: 

257 return False 

258 out_names = form.out_names 

259 for name in form.out_ops: 

260 # An op name missing from the declared order compiles to index 0 

261 # (``_compile_output_plan``'s ``name_to_idx.get(name, 0)``), which the 

262 # single-value template covers; a later position does not. 

263 if name in out_names and out_names.index(name) != 0: 

264 return False 

265 return True 

266 

267 

268# --------------------------------------------------------------------------- 

269# grouping / consistency 

270# --------------------------------------------------------------------------- 

271 

272def _group_boundaries_by_class( 

273 param_plan: dict[str, Any], 

274 boundary_classes: Optional[dict[str, str]], 

275 index: SourceIndex, 

276 *, 

277 module_name: str, 

278) -> dict[str, list[tuple[str, dict[str, Any]]]]: 

279 """Group boundary FQNs by the class that owns their ``forward``. 

280 

281 Returns ``{class_name: [(fqn, entry), ...]}`` in a stable order (FQN sorted 

282 for determinism). 

283 

284 Imported classes and inherited forwards have no method span in this 

285 source unit. Keep their boundary facts for native per-instance application 

286 without copying or rewriting an unrelated class. The same restriction 

287 applies to ``skip_source_lowering`` entries shared with non-boundaries. 

288 

289 A boundary whose class cannot be resolved fails fast rather than silently 

290 losing its source coverage. 

291 """ 

292 logger = logging.getLogger(__name__) 

293 groups: dict[str, list[tuple[str, dict[str, Any]]]] = {} 

294 for fqn, entry in param_plan.items(): 

295 if not is_boundary_entry(entry): 

296 continue 

297 if entry.get("skip_source_lowering"): 

298 logger.info( 

299 "lower_forward_boundaries: boundary %s is marked " 

300 "skip_source_lowering (class shared with a non-boundary " 

301 "instance); native per-instance application remains Trainer-owned", 

302 fqn, 

303 ) 

304 continue 

305 class_name = _class_for_fqn(fqn, boundary_classes, index, module_name) 

306 if class_name is None: 

307 raise ValueError( 

308 f"lower_forward_boundaries: cannot resolve the class for boundary " 

309 f"{fqn!r} — the frozen plan has no class mapping and the source " 

310 "index does not contain a class whose name matches; a boundary " 

311 "whose forward is not rewritten would silently drop its " 

312 "redistribution" 

313 ) 

314 if index.find_class(class_name) is None: 

315 # Imported methods have no source span in this unit; do not 

316 # copy an entire native class solely to render its boundary. 

317 continue 

318 if index.find_forward(class_name) is None: 

319 # An inherited forward has the same source-span restriction 

320 # as an imported class. 

321 logger.info( 

322 "lower_forward_boundaries: boundary %s is a %s instance whose " 

323 "forward is inherited (no class-body ``def forward``); the " 

324 "native per-instance application remains Trainer-owned", 

325 fqn, 

326 class_name, 

327 ) 

328 continue 

329 groups.setdefault(class_name, []).append((fqn, entry)) 

330 for class_name, items in groups.items(): 

331 items.sort(key=lambda item: item[0]) 

332 return groups 

333 

334 

335def _class_for_fqn( 

336 fqn: str, 

337 boundary_classes: Optional[dict[str, str]], 

338 index: SourceIndex, 

339 module_name: str, 

340) -> Optional[str]: 

341 """Resolve a boundary FQN to a top-level class name. 

342 

343 Resolution order: 

344 1. the explicit ``boundary_classes`` map (freeze-time truth); 

345 2. a source-index class whose name matches the FQN's leaf segment; 

346 3. a source-index class whose name matches after stripping a known module 

347 prefix (``module_name``) — remote-code modeling files carry the bare 

348 class name, and the FQN leaf is usually it; 

349 4. ``None`` (caller fails fast). 

350 """ 

351 if boundary_classes: 

352 cls = boundary_classes.get(fqn) 

353 if cls: 

354 return cls 

355 leaf = fqn.rsplit(".", 1)[-1] 

356 if leaf in index.classes: 

357 return leaf 

358 # A remote-code file may name the class without the module-name prefix on 

359 # the FQN leaf; only accept it when the leaf matches a class AND the leaf 

360 # is a plausible modeling class (no lambdas / generics). 

361 if module_name: 

362 candidate = module_name.rsplit(".", 1)[-1] 

363 if candidate in index.classes and _name_matches(candidate, leaf): 

364 return candidate 

365 return None 

366 

367 

368def _name_matches(class_name: str, leaf: str) -> bool: 

369 """Loose match between a module-name class and an FQN leaf. 

370 

371 The FQN leaf is the module attribute (``self_attn`` / ``mlp``); the class 

372 is its type (``Qwen3MoeAttention``). They usually differ, so this only 

373 accepts the trivial identity. The strong mapping is ``boundary_classes``; 

374 this fallback is deliberately conservative. 

375 """ 

376 return class_name == leaf 

377 

378 

379def _verify_class_contract( 

380 group: list[tuple[str, dict[str, Any]]], class_name: str 

381) -> dict[str, Any]: 

382 """Fail fast unless every FQN of ``class_name`` carries the same contract. 

383 

384 One ``class.forward`` is shared by every instance of the class, so all the 

385 class's boundaries must be describable by the SAME frozen entry (modulo the 

386 ``params`` tree, which is instance-specific and drives the native Phase A 

387 parameter sharding, not the forward rewrite). Returns the canonical entry. 

388 """ 

389 canonical: Optional[str] = None 

390 canonical_entry: dict[str, Any] = {} 

391 for fqn, entry in group: 

392 entry = _without_params(entry) 

393 blob = json.dumps(entry, sort_keys=True) 

394 if canonical is None: 

395 canonical = blob 

396 canonical_entry = entry 

397 elif blob != canonical: 

398 raise ValueError( 

399 f"lower_forward_boundaries: class {class_name!r} has FQNs with " 

400 f"differing boundary contracts ({fqn!r}); a shared forward " 

401 "cannot carry two contracts — split the plan or align the " 

402 "per-rule contracts" 

403 ) 

404 return canonical_entry 

405 

406 

407def _without_params(entry: dict[str, Any]) -> dict[str, Any]: 

408 """Drop the instance-specific ``params`` tree from a contract comparison.""" 

409 if "params" not in entry: 

410 return entry 

411 return {k: v for k, v in entry.items() if k != "params"} 

412 

413 

414def _index_injections_by_class( 

415 injections: list[dict[str, Any]], 

416 boundary_classes: Optional[dict[str, str]], 

417 index: SourceIndex, 

418 param_plan: Optional[dict[str, Any]] = None, 

419) -> dict[str, dict[str, Any]]: 

420 """Fold a class's injection declarations (inner wrapper / local compute). 

421 

422 Returns ``{class_name: {key: value}}`` — the union of every injection rule 

423 whose ``match`` lands on a FQN of that class. A class with conflicting 

424 values for one key (two FQNs declared different local compute fns) fails 

425 fast, for the same reason as ``_verify_class_contract``. 

426 """ 

427 by_class: dict[str, dict[str, Any]] = {} 

428 for rule in injections: 

429 match = rule.get("match") 

430 if not isinstance(match, str) or not match: 

431 continue 

432 entry = (param_plan or {}).get(match) or {} 

433 if entry.get("skip_source_lowering"): 

434 continue 

435 class_name = _class_for_fqn(match, boundary_classes, index, "") 

436 if class_name is None: 

437 continue 

438 payload = {k: rule[k] for k in _INJECTION_KEYS if k in rule} 

439 if not payload: 

440 continue 

441 existing = by_class.setdefault(class_name, {}) 

442 for key, value in payload.items(): 

443 if key in existing and _json_stable(existing[key]) != _json_stable(value): 

444 raise ValueError( 

445 f"lower_forward_boundaries: class {class_name!r} has " 

446 f"conflicting injection values for {key!r}" 

447 ) 

448 existing[key] = value 

449 return by_class 

450 

451 

452def _json_stable(value: Any) -> str: 

453 return json.dumps(value, sort_keys=True, default=str) 

454 

455 

456# --------------------------------------------------------------------------- 

457# forward body construction 

458# --------------------------------------------------------------------------- 

459 

460def _require_forward(index: SourceIndex, class_name: str) -> FunctionInfo: 

461 """Return the ``forward`` ``FunctionInfo`` for a boundary class or raise.""" 

462 func = index.find_forward(class_name) 

463 if func is None: 

464 raise ValueError( 

465 f"lower_forward_boundaries: class {class_name!r} has no forward " 

466 "method; a boundary forward must exist to be rewritten" 

467 ) 

468 if func.body_start is None or func.body_end is None: 

469 raise ValueError( 

470 f"lower_forward_boundaries: class {class_name!r}.forward has no " 

471 "replaceable body (single-line/pass); cannot sink a boundary" 

472 ) 

473 return func 

474 

475 

476def _build_forward_impl_edit( 

477 source_text: str, 

478 func: FunctionInfo, 

479 prefix: Optional[str] = None, 

480) -> Optional[TextEdit]: 

481 """Build an edit that extracts a method as ``_forward_impl``. 

482 

483 The original method (signature + body) is copied out of the source and 

484 inserted as the private ``_forward_impl`` right before the rewritten 

485 ``def forward``. The copy keeps the original signature and body byte-for- 

486 byte, re-indented to the method's own indent, with the ``def forward`` 

487 renamed to ``def _forward_impl``. ``prefix`` (the static form's class 

488 marker) is prepended to the same insertion — one zero-width edit at 

489 ``def_offset``, so the edit set never carries two edits at one offset. 

490 

491 Returns ``None`` when the forward has no replaceable body (single-line/ 

492 pass) — there is nothing meaningful to extract, and ``forward`` itself was 

493 already rejected by ``_require_forward`` for the same reason, so this is a 

494 defensive fallback. 

495 """ 

496 if func.body_start is None or func.body_end is None: 

497 return None 

498 # The extracted method owns the signature + body; DECORATORS stay attached to 

499 # the original ``forward`` (which is being rewritten) — copying them onto 

500 # ``_forward_impl`` too would duplicate a side effect (e.g. 

501 # ``@torch.no_grad()``) on a method that must be pure. ``func.def_offset`` 

502 # anchors the FIRST line of the method (a decorator when one is present), so 

503 # scan forward from it past decorator lines and blanks to the ``def`` keyword 

504 # — this finds the signature line for both the plain and the decorated case 

505 # without offset arithmetic (a naive backward scan from ``body_start`` finds 

506 # the newline that *ends* the ``def`` line, landing on the first body line). 

507 def_line_start = func.def_offset 

508 for line in source_text[def_line_start:func.body_start].splitlines(keepends=True): 

509 stripped = line.lstrip() 

510 if stripped.startswith("def "): 

511 break 

512 def_line_start += len(line) 

513 span = source_text[def_line_start:func.body_end] 

514 lines = span.splitlines(keepends=True) 

515 if not lines: 

516 return None 

517 # ``_forward_impl`` is a VERBATIM copy of the original method (signature + 

518 # body, byte-for-byte, keeping the method indent on the ``def`` and the body 

519 # nesting) with only the name changed -- so nothing here needs dedenting or 

520 # re-indenting, and the copy can never drift from the original source. 

521 for i, line in enumerate(lines): 

522 stripped = line.lstrip() 

523 if stripped.startswith(f"def {func.name}("): 

524 lines[i] = line.replace(f"def {func.name}(", "def _forward_impl(", 1) 

525 break 

526 impl = "".join(lines) 

527 # The copy ends at ``body_end``, which is clamped to EOF for a final 

528 # statement with no trailing newline — so the extracted method can lose its 

529 # terminating newline and land joined onto the ``def forward`` that follows. 

530 # A method must be separated from the next one by a newline, so pad. 

531 if not impl.endswith("\n"): 

532 impl += "\n" 

533 if prefix: 

534 impl = prefix + impl 

535 return TextEdit(func.def_offset, func.def_offset, impl) 

536 

537 

538def _cp_dispatch_pair(source_body: str) -> Optional[tuple[ast.Call, ast.Call]]: 

539 """Recognize the CP branch and local fallback with Python 3.9-compatible AST checks.""" 

540 body = ast.parse(textwrap.dedent(source_body)).body 

541 if len(body) != 2 or not isinstance(body[0], ast.If) or not isinstance(body[1], ast.Return): 

542 return None 

543 branch, fallback = body 

544 if branch.orelse or len(branch.body) != 1 or not isinstance(branch.body[0], ast.Return): 

545 return None 

546 if ast.dump(branch.test) != ast.dump(ast.parse("self.cp_enable", mode="eval").body): 

547 return None 

548 call, original = branch.body[0].value, fallback.value 

549 if not isinstance(call, ast.Call) or not isinstance(original, ast.Call) or not call.args: 

550 return None 

551 if (ast.dump(call.args[0]) != ast.dump(ast.Name(id="self", ctx=ast.Load())) 

552 or ast.dump(original.func) != ast.dump(ast.parse("self._forward_impl", mode="eval").body)): 

553 return None 

554 return call, original 

555 

556 

557def _cp_dispatch_call(source_body: str) -> Optional[ast.Call]: 

558 """Recognize our passthrough CP shell and bind it to redistributed arguments.""" 

559 pair = _cp_dispatch_pair(source_body) 

560 if pair is None: 

561 return None 

562 call, original = pair 

563 if [ast.dump(arg) for arg in call.args[1:]] != [ast.dump(arg) for arg in original.args]: 

564 return None 

565 originals = {ast.dump(keyword) for keyword in original.keywords} 

566 if not originals <= {ast.dump(keyword) for keyword in call.keywords}: 

567 return None 

568 call.args = [ast.Name(id="self", ctx=ast.Load()), 

569 ast.Starred(value=ast.Name(id="args", ctx=ast.Load()), ctx=ast.Load())] 

570 call.keywords = [keyword for keyword in call.keywords if ast.dump(keyword) not in originals] 

571 call.keywords.append(ast.keyword(arg=None, value=ast.Name(id="kwargs", ctx=ast.Load()))) 

572 return ast.fix_missing_locations(call) 

573 

574 

575def _build_forward_body( 

576 source_text: str, 

577 injection: Optional[dict[str, Any]], 

578 func: FunctionInfo, 

579 form: BoundaryForm, 

580 emitted: str, 

581 deferred_bias: bool = False, 

582 inner_compute: Optional[str] = None, 

583) -> str: 

584 """Render the rewritten forward body for one boundary class. 

585 

586 ``emitted`` is :func:`resolve_emitted_form`'s verdict (the classifier's 

587 form after the static gates). The redistribute calls go through the 

588 ``self._hp_boundary`` runtime interface; the static ``tp_collective`` 

589 form calls operators on ``self._hp_tp`` instead. Source emission only 

590 renders these references; actual state binding remains runtime-owned. 

591 

592 ``deferred_bias`` (D-22) appends the exit hook call 

593 ``self._hp_deferred_bias(outputs)`` after the output redistribution — 

594 the runtime binds that hook when it installs the native 

595 suppression/restore pair. 

596 """ 

597 if emitted == FORM_TP_COLLECTIVE: 

598 return _render_tp_collective_forward(source_text, func, form, deferred_bias) 

599 

600 input_redist = _render_input_redistribute(func) 

601 out_redist = _render_output_redistribute(deferred_bias) 

602 

603 local = injection.get("local_compute_fn") if injection else None 

604 if local is not None: 

605 raise RuntimeError( 

606 "codegen: local_compute_fn reached source boundary lowering; " 

607 "builder recording must mark it skip_source_lowering so runtime " 

608 "can install the trainer's native Phase C wrapper" 

609 ) 

610 # Keep source-visible CP dispatch inside the boundary and outside the 

611 # preserved local implementation that its helper may call back into. 

612 return _render_plain_redistribute(input_redist, out_redist, form, inner_compute) 

613 

614 

615def _render_input_redistribute(func: FunctionInfo) -> str: 

616 """Render the input-side redistribute call on the compiled boundary plan. 

617 

618 The generated forward re-binds args/kwargs against its own signature, so a 

619 positional ``(args, kwargs)`` pair reaches the compiled plan as the 

620 boundary's input side. The pair is built from the signature's own 

621 parameter names rather than relying on runtime index binding — for a 

622 ``def forward(self, hidden_states)`` that is ``((hidden_states,), {})``. 

623 

624 The full parameter profile is preserved on the re-pass: positional names go 

625 in the args tuple (a trailing ``*args`` expands into it), keyword-only 

626 parameters and a fixed ``**kwargs`` go into the kwargs dict. The boundary 

627 plan rewrites only the args/kwargs it owns and forwards the rest through 

628 unchanged, so ``self._forward_impl(*args, **kwargs)`` receives every 

629 argument class the original call site used — a keyword-only ``required`` 

630 or an HF ``**kwargs`` pass-through no longer drops out. 

631 """ 

632 args = list(func.param_names) 

633 if func.vararg_name: 

634 args.append(f"*{func.vararg_name}") 

635 kwargs_parts = [f'"{name}": {name}' for name in func.kwonly_names] 

636 if func.kwarg_name: 

637 kwargs_parts.append(f"**{func.kwarg_name}") 

638 kwargs_literal = "{" + ", ".join(kwargs_parts) + "}" if kwargs_parts else "{}" 

639 # The args body is spliced into a tuple literal; a single element needs a 

640 # trailing comma (also for a lone ``*vararg``) so it stays a tuple rather 

641 # than parenthesized scalars / a generator expression. 

642 args_body = ", ".join(args) + ("," if len(args) == 1 else "") 

643 return ( 

644 " args, kwargs = self._hp_boundary.redistribute_inputs(\n" 

645 f" (({args_body}), {kwargs_literal}),\n" 

646 " )" 

647 ) 

648 

649 

650def _render_output_redistribute(deferred_bias: bool = False) -> str: 

651 """Render the output-side boundary exit (no signature to bind). 

652 

653 Mirrors the native production path: the compute output remains local and 

654 ``PrecompiledBoundary`` executes a lowered collective directly when 

655 possible. An unlowerable transition performs any required temporary 

656 DTensor wrapping internally and still returns a local tensor. 

657 

658 ``deferred_bias`` (D-22) appends the exit hook after redistribution: the 

659 rowwise bias was suppressed inside the region so the exit reduction sees 

660 a pure matmul contribution, and the hook re-adds it exactly once on the 

661 reduced local output — Megatron RowParallelLinear semantics. The hook is 

662 bound at install time (``module._hp_deferred_bias``); the emitted call 

663 is conditional on the plan declaring deferred params, so the two sides 

664 cannot disagree about whether a boundary defers. 

665 """ 

666 lines = [ 

667 " outputs = self._hp_boundary.redistribute_outputs(outputs)", 

668 ] 

669 if deferred_bias: 

670 lines.append(" outputs = self._hp_deferred_bias(outputs)") 

671 return "\n".join(lines) 

672 

673 

674def _ordered_notes(notes: dict[str, str]) -> list[str]: 

675 """Declarative annotation lines for one side, in deterministic name order.""" 

676 return [f" # {notes[name]}" for name in sorted(notes)] 

677 

678 

679def _render_plain_redistribute( 

680 input_redist: str, out_redist: str, form: BoundaryForm, inner_compute: Optional[str] = None, 

681) -> str: 

682 """Generic boundary: annotated redistribute around the original forward. 

683 

684 The comment blocks are the plan's own declaration: one line per 

685 non-identity transition (``name: axis S(1) -> R ==> all_gather(dim=1)`` or 

686 ``==> dtensor redistribute`` for transitions the compiled plan's DTensor 

687 fallback owns), so a reader sees what the boundary communicates without 

688 re-deriving the plan. 

689 """ 

690 compute = " outputs = self._forward_impl(*args, **kwargs)" 

691 if inner_compute is not None: 

692 compute = (f" if self.cp_enable:\n outputs = {inner_compute}\n" 

693 " else:\n outputs = self._forward_impl(*args, **kwargs)") 

694 return "\n".join([ 

695 " # [HYPER BOUNDARY] input redistribution", 

696 *_ordered_notes(form.in_notes), 

697 input_redist, 

698 "", 

699 " # [HYPER BOUNDARY] original forward body (now ``_forward_impl``)", 

700 compute, 

701 "", 

702 " # [HYPER BOUNDARY] output redistribution", 

703 *_ordered_notes(form.out_notes), 

704 out_redist, 

705 "", 

706 " return outputs", 

707 ]) 

708 

709 

710# --------------------------------------------------------------------------- 

711# static tp_collective template 

712# --------------------------------------------------------------------------- 

713 

714def _render_tp_collective_forward( 

715 source_text: str, 

716 func: FunctionInfo, 

717 form: BoundaryForm, 

718 deferred_bias: bool = False, 

719) -> str: 

720 """Static boundary: bare TP operators, semantics of ``RedistOp.execute``. 

721 

722 The rendered body is instruction-equivalent to the generic engine with the 

723 TP lowerer attached: 

724 

725 - identity inputs — ``self._hp_tp.to_local(name)`` (a DTensor unwraps to 

726 its local shard, anything else passes through); 

727 - TP-lowerable inputs/outputs — ``self._hp_tp.<kind>(...)`` (the bound 

728 operator unwraps a DTensor input and runs the collective on the tp 

729 group; ``None`` passes through, like the compiled plan's ``None`` skip); 

730 - ``_forward_impl`` is called with every declared parameter in signature 

731 order (the static forward re-binds names, so no ``*args`` re-pass). 

732 

733 The rendered ``self._hp_tp`` calls expose the selected transitions for 

734 review. This source pass neither binds a mesh nor installs runtime state. 

735 

736 ``deferred_bias`` (D-22) appends ``self._hp_deferred_bias(outputs)`` 

737 after the output ops — the Partial(sum) -> R all_reduce above is exactly 

738 the exit reduction the deferral waits for, so the bias re-add lands once, 

739 on the reduced output. 

740 """ 

741 lines = [ 

742 " # [HYPER TP-COLLECTIVE] statically lowered boundary — the runtime", 

743 " # re-validates this form at install time and replaces the forward", 

744 " # with the generic engine on any mismatch.", 

745 ] 

746 for name in form.in_declared: 

747 op = form.in_ops.get(name) 

748 if op is None: 

749 note = form.in_notes.get(name) or f"{name}: identity ==> to_local" 

750 lines.append(f" # {note}") 

751 lines.append(f" {name} = self._hp_tp.to_local({name})") 

752 else: 

753 lines.append(f" # {form.in_notes[name]}") 

754 lines.append(_render_tp_call(name, op)) 

755 lines.append("") 

756 lines.append( 

757 " # [HYPER TP-COLLECTIVE] original forward body (now ``_forward_impl``)" 

758 ) 

759 lines.append(_render_forward_call(func)) 

760 tuple_output = not returns_single_value(source_text, func) 

761 for name, op in form.out_ops.items(): 

762 lines.append(f" # {form.out_notes[name]}") 

763 lines.extend(_render_output_tp_call(name, op, form, tuple_output)) 

764 if deferred_bias: 

765 lines.append("") 

766 lines.append( 

767 " # [HYPER D-22] deferred bias re-added once, after the exit reduction" 

768 ) 

769 lines.append(" outputs = self._hp_deferred_bias(outputs)") 

770 lines.append("") 

771 lines.append(" return outputs") 

772 return "\n".join(lines) 

773 

774 

775def _render_tp_call_expr(target: str, op: TransitionOp) -> str: 

776 """One bare-operator call expression (``self._hp_tp.<kind>(...)``).""" 

777 if op.kind == "all_reduce": 

778 return f"self._hp_tp.all_reduce({target})" 

779 return f"self._hp_tp.{op.kind}({target}, dim={op.tensor_dim})" 

780 

781 

782def _render_tp_call(name: str, op: TransitionOp) -> str: 

783 """One input-side bare-operator statement (rebinding the named input).""" 

784 return f" {name} = {_render_tp_call_expr(name, op)}" 

785 

786 

787def _render_output_tp_call( 

788 name: str, op: TransitionOp, form: BoundaryForm, tuple_output: bool 

789) -> list[str]: 

790 """Output-side bare-operator statements. 

791 

792 The common single-tensor case rewrites ``outputs`` directly. For tuple 

793 outputs, the frozen plan names the first declared output as index 0; 

794 rebuild the original container after applying the collective to that item. 

795 """ 

796 out_names = form.out_names 

797 if tuple_output and (name not in out_names or out_names.index(name) == 0): 

798 return [ 

799 f" _hp_output_0 = {_render_tp_call_expr('outputs[0]', op)}", 

800 " outputs = (_hp_output_0, *outputs[1:])", 

801 ] 

802 return [f" outputs = {_render_tp_call_expr('outputs', op)}"] 

803 

804 

805def _render_forward_call(func: FunctionInfo) -> str: 

806 """The ``self._forward_impl(...)`` call, every parameter re-passed by name. 

807 

808 Positional parameters go positionally, keyword-only ones by keyword — the 

809 call is a pure re-pass of the static forward's own signature, so defaults 

810 and call-site keyword usage both survive the rewrite. 

811 """ 

812 args = list(func.param_names) + [f"{name}={name}" for name in func.kwonly_names] 

813 if func.kwarg_name: 

814 args.append(f"**{func.kwarg_name}") 

815 if not args: 

816 return " outputs = self._forward_impl()" 

817 single = f" outputs = self._forward_impl({', '.join(args)})" 

818 if len(single) <= 100: 

819 return single 

820 lines = [" outputs = self._forward_impl("] 

821 lines.extend(f" {arg}," for arg in args) 

822 lines.append(" )") 

823 return "\n".join(lines) 

824 

825 

826def _render_local_compute( 

827 local: Any, input_redist: str, out_redist: str, form: BoundaryForm 

828) -> str: 

829 """Local-region boundary (shape 2, EP MoE): compute fn on local tensors, then exit. 

830 

831 The factory-named attribute is ``functools.partial(compute_fn, module)`` 

832 bound by the emitted constructor patch. The applier calls it as ``compute_fn(*args, 

833 **kwargs)`` (``_wrap_local_region_forward``), so the generated forward 

834 forwards its own re-distributed ``*args, **kwargs`` through. The local 

835 Production keeps the compute output local so the lowered boundary 

836 operations can run on plain tensors. If a transition cannot be lowered, the 

837 installed boundary owns the necessary fallback wrapping. 

838 

839 The per-transition declarative notes (``form.in_notes`` / ``out_notes``) 

840 annotate the redistribution steps exactly like the generic and 

841 tp-collective templates; identity transitions carry no note, so an 

842 identity in/out region emits no noise. 

843 """ 

844 compute_name = _callable_name(local) 

845 binding_name = local_compute_binding_name(local) 

846 return "\n".join([ 

847 " # [HYPER LOCAL REGION] boundary entry", 

848 *_ordered_notes(form.in_notes), 

849 input_redist, 

850 " # [HYPER LOCAL REGION] run the region compute fn on local tensors", 

851 f" # {compute_name} is bound to self by generated source.", 

852 f" outputs = self.{binding_name}(*args, **kwargs)", 

853 "", 

854 " # [HYPER LOCAL REGION] boundary exit", 

855 *_ordered_notes(form.out_notes), 

856 out_redist, 

857 "", 

858 " return outputs", 

859 ]) 

860 

861 

862def _callable_name(value: Any) -> str: 

863 """Human name for an injection's callable (dict target / string / fn).""" 

864 if isinstance(value, dict): 

865 return ( 

866 value.get("_target_") 

867 or value.get("name") 

868 or value.get("target") 

869 or repr(value) 

870 ) 

871 if isinstance(value, str): 

872 return value 

873 return getattr(value, "__name__", repr(value)) 

874 

875 

876# --------------------------------------------------------------------------- 

877# field reads / validation 

878# --------------------------------------------------------------------------- 

879 

880def _plan_field(plan: Any, name: str) -> Any: 

881 """Read a frozen-plan field from a dict or a ``CodegenMeta``.""" 

882 if isinstance(plan, dict): 

883 return plan.get(name) 

884 return getattr(plan, name, None) 

885 

886 

887def _validate_no_circular(edits: list[TextEdit]) -> list[str]: 

888 """Detect edits authored against different texts (a soft sanity check). 

889 

890 The lowerer computes all edits against one ``source_text``; the index is 

891 built once, so a second-pass author (an inner wrapper that itself carries a 

892 body rewrite) would need to re-index. We fail fast rather than splice 

893 stale offsets. 

894 """ 

895 problems: list[str] = [] 

896 seen: dict[tuple[int, int], str] = {} 

897 for edit in edits: 

898 key = (edit.start, edit.end) 

899 if key in seen: 

900 problems.append( 

901 f"[{edit.start},{edit.end}) (was {seen[key]}, now {edit.replacement[:30]!r})" 

902 ) 

903 else: 

904 seen[key] = edit.replacement[:30] 

905 return problems 

906 

907 

908__all__ = [ 

909 "TP_FORM_ATTRIBUTE", 

910 "TP_FORM_MARKER", 

911 "iter_emitted_forms", 

912 "lower_forward_boundaries", 

913 "resolve_emitted_form", 

914]