Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / codegen / inline / forward_edits.py: 88%
91 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
« 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"""Apply source-visible forward extraction patches."""
17from __future__ import annotations
19import ast
20import textwrap
21from collections.abc import Iterable
23from hyper_parallel.codegen.astkit.edits import TextEdit, replace_function_body
24from hyper_parallel.codegen.astkit.index import ClassInfo, FunctionInfo, build_source_index
25from hyper_parallel.codegen.emit.parallel import _build_forward_impl_edit
26from hyper_parallel.codegen.inline.ir import ForwardExtractPatch
28_HIDDEN_ARG_TOKEN = "__hp_hidden_arg__"
31def forward_extract_edits(
32 source_text: str,
33 patches: Iterable[ForwardExtractPatch],
34) -> list[TextEdit]:
35 """Build edits that preserve original forwards and install dispatch bodies."""
36 patch_list = tuple(patches)
37 if not patch_list:
38 return []
39 index = build_source_index(source_text)
40 edits: list[TextEdit] = []
41 for patch in patch_list:
42 cls = index.find_class(patch.class_name)
43 if cls is None:
44 continue
45 if patch.initializers:
46 initializer = cls.methods.get("__init__")
47 if initializer is None or initializer.body_end is None:
48 raise RuntimeError(f"codegen cannot initialize observed state for {patch.class_name!r}")
49 statements = textwrap.indent("\n".join(patch.initializers), " ") + "\n"
50 line_end = source_text.find("\n", initializer.body_end - 1)
51 offset = line_end + 1 if line_end >= 0 else len(source_text)
52 prefix = "" if source_text[:offset].endswith("\n") else "\n"
53 edits.append(TextEdit(offset, offset, prefix + statements))
54 if patch.definition is not None:
55 edits.append(_definition_edit(source_text, cls, patch))
56 continue
57 func = cls.methods.get(patch.method_name)
58 if func is None:
59 continue
60 body = _bind_forward_args(_bind_hidden_arg(patch.body, func), func)
61 prefix = _parallel_state_prefix(body)
62 impl = _build_forward_impl_edit(source_text, func, prefix=prefix)
63 if impl is not None:
64 edits.append(impl)
65 edits.extend(replace_function_body(source_text, func, body, indent=" "))
66 return edits
69def _definition_edit(source_text: str, cls: ClassInfo, patch: ForwardExtractPatch) -> TextEdit:
70 """Install actual native methods, preserving the old method only when called."""
71 names = {node.name for node in ast.parse(patch.definition).body if isinstance(node, ast.FunctionDef)}
72 collisions = (names - {patch.method_name}) & cls.methods.keys()
73 if collisions:
74 raise RuntimeError(f"codegen observed methods collide with source methods {sorted(collisions)}")
75 definition = textwrap.indent(patch.definition.strip(), " ") + "\n"
76 func = cls.methods.get(patch.method_name)
77 if func is None:
78 return TextEdit(cls.end_offset, cls.end_offset, "\n" + definition)
79 if any(isinstance(node, ast.Attribute) and isinstance(node.value, ast.Name)
80 and node.value.id == "self" and node.attr == "_forward_impl"
81 for node in ast.walk(ast.parse(patch.definition))):
82 impl = _build_forward_impl_edit(source_text, func)
83 if impl is None or "_forward_impl" in cls.methods:
84 raise RuntimeError("codegen cannot preserve the original method for the observed wrapper")
85 original = ast.parse(textwrap.dedent(source_text[func.def_offset:func.body_end])).body[0]
86 decorators = "".join(f" @{ast.unparse(item)}\n" for item in original.decorator_list)
87 definition = decorators + impl.replacement + "\n" + definition
88 return TextEdit(func.def_offset, func.body_end, definition)
91def _parallel_state_prefix(body: str) -> str:
92 """Render static enable flags read by a generated dispatch body."""
93 lines = [
94 f" {axis}_enable = False"
95 for axis in ("tp", "cp", "ep")
96 if f"self.{axis}_enable" in body
97 ]
98 return "\n".join(lines) + "\n\n" if lines else ""
101def _bind_hidden_arg(body: str, func: FunctionInfo) -> str:
102 """Bind a strategy shell's hidden-input placeholder to its host signature."""
103 if _HIDDEN_ARG_TOKEN not in body:
104 return body
105 if not func.param_names:
106 raise RuntimeError(
107 f"codegen: inline strategy body references {_HIDDEN_ARG_TOKEN!r} "
108 "but the target method has no positional parameter to bind it to"
109 )
110 return body.replace(_HIDDEN_ARG_TOKEN, func.param_names[0])
113def _bind_forward_args(body: str, func: FunctionInfo) -> str:
114 """Bind a dispatch shell's argument token to the original signature."""
115 token = "__hp_forward_args__"
116 args = list(func.param_names)
117 if func.vararg_name:
118 args.append(f"*{func.vararg_name}")
119 args.extend(f"{name}={name}" for name in func.kwonly_names)
120 if func.kwarg_name:
121 args.append(f"**{func.kwarg_name}")
122 positional = list(func.param_names)
123 if func.vararg_name:
124 positional.append(f"*{func.vararg_name}")
125 keywords = [f"{name!r}: {name}" for name in func.kwonly_names]
126 if func.kwarg_name:
127 keywords.append(f"**{func.kwarg_name}")
128 positional_text = ", ".join(positional) + ("," if positional else "")
129 bindings = []
130 if "__hp_forward_positional__" in body:
131 bindings.append(f"forward_args = ({positional_text})")
132 body = body.replace("__hp_forward_positional__", "forward_args")
133 if "__hp_forward_keywords__" in body:
134 bindings.append("forward_kwargs = {" + ", ".join(keywords) + "}")
135 body = body.replace("__hp_forward_keywords__", "forward_kwargs")
136 return "\n".join([*bindings, body.replace(token, ", ".join(args))])
139__all__ = ["forward_extract_edits"]