Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / codegen / inline / component_source.py: 91%
216 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"""Project native rewrites and replacement components into the existing source pipeline."""
17from __future__ import annotations
19import ast
20import importlib
21import inspect
22import textwrap
23from typing import Any, Callable
25from hyper_parallel.codegen.astkit.edits import TextEdit, apply_edits
26from hyper_parallel.codegen.inline.attention import (
27 _component_dependencies,
28 _referenced_global_names,
29 _strip_annotations,
30 render_attention_class,
31)
32from hyper_parallel.codegen.inline.expansion import ExpandedSource
33from hyper_parallel.codegen.inline.recognition import (
34 _assigned_once,
35 _closure_source_bindings,
36 _companion_attr_bindings,
37 _function_source_qualname,
38 _nested_forward_body,
39 _wrapper_definition,
40)
41from hyper_parallel.distributed.recipe_spec import WRAPPER_CONTEXT
44def render_component_source(
45 component: type, *, interface: Callable[..., Any] | None = None,
46) -> ExpandedSource:
47 """Expose a native forward signature for the existing boundary lowering pass.
49 Args:
50 component: Concrete implementation already selected by native preparation.
51 interface: Optional kernel interface used by the existing attention renderer.
52 """
53 if interface is not None:
54 return render_attention_class(component, interface=interface)
55 forward = ast.parse(textwrap.dedent(inspect.getsource(component.forward))).body[0]
56 _strip_annotations(forward)
57 forward.decorator_list = []
58 tuple_output = any(isinstance(node, ast.Return) and isinstance(node.value, ast.Tuple)
59 for node in ast.walk(forward))
60 forward.body = ast.parse(_native_forward_call(forward, tuple_output=tuple_output)).body
61 owner = next(base for base in component.__mro__ if "forward" in base.__dict__)
62 _, imports = _component_dependencies(owner, ast.unparse(forward), provided={component.__name__},
63 inline_definitions=False)
64 source = (f"class {component.__name__}({component.__module__}.{component.__name__}):\n"
65 + textwrap.indent(ast.unparse(forward), " ") + "\n")
66 return ExpandedSource((f"import {component.__module__}", *imports), source)
69def _native_forward_call(forward: ast.FunctionDef, *, tuple_output: bool = False) -> str:
70 """Delegate all arguments without rebinding the native defining-class closure."""
71 args = forward.args
72 arguments = [arg.arg for arg in (*args.posonlyargs, *args.args)][1:]
73 if args.vararg:
74 arguments.append(f"*{args.vararg.arg}")
75 arguments.extend(f"{arg.arg}={arg.arg}" for arg in args.kwonlyargs)
76 if args.kwarg:
77 arguments.append(f"**{args.kwarg.arg}")
78 call = f"super().forward({', '.join(arguments)})"
79 return f"return (*{call},)" if tuple_output else f"return {call}"
82def collapse_unmodified_components(source: str) -> str:
83 """Replace untouched native forwarding shells with their original class imports.
85 Boundary lowering needs a signature to select its existing templates. Only
86 shells that lowering left untouched can collapse; rewritten forwards remain
87 visible and continue inheriting native constructors and parallel stages.
88 """
89 lines = source.splitlines(keepends=True)
90 offsets = [0]
91 for line in lines:
92 offsets.append(offsets[-1] + len(line))
93 tree = ast.parse(source)
94 edits = []
95 collapsed = {}
96 for node in tree.body:
97 module = _unchanged_component_base(node)
98 if module is None:
99 continue
100 collapsed[node] = (module, node.name)
101 edits.append(TextEdit(offsets[node.lineno - 1], offsets[node.end_lineno], ""))
102 for node in tree.body:
103 if not isinstance(node, ast.Import) or len(node.names) != 1:
104 continue
105 module = node.names[0].name
106 names = sorted(name for owner, name in collapsed.values() if owner == module)
107 if not names:
108 continue
109 still_used = _component_module_used(tree, module, collapsed)
110 imports = (f"import {module}\n" if still_used else "") + f"from {module} import {', '.join(names)}\n"
111 edits.append(TextEdit(offsets[node.lineno - 1], offsets[node.end_lineno], imports))
112 return apply_edits(source, edits) if edits else source
115def _component_module_used(tree: ast.Module, module: str, collapsed: dict) -> bool:
116 """Keep namespace imports still used by rewritten subclasses or other source."""
117 return any(
118 isinstance(child, ast.Attribute) and ast.unparse(child).startswith(module + ".")
119 for other in tree.body if other not in collapsed
120 for child in ast.walk(other)
121 )
124def _unchanged_component_base(node: ast.AST) -> str | None:
125 """Recognize only a same-name native subclass forwarding all arguments unchanged."""
126 if not isinstance(node, ast.ClassDef) or len(node.bases) != 1:
127 return None
128 base = node.bases[0]
129 if not isinstance(base, ast.Attribute) or base.attr != node.name:
130 return None
131 module = ast.unparse(base.value)
132 if not module.startswith("hyper_parallel.components.modules."):
133 return None
134 component = getattr(importlib.import_module(module), node.name)
135 expected = ast.parse(render_component_source(component).source).body[0]
136 return module if ast.dump(node) == ast.dump(expected) else None
139__all__ = ["render_component_source", "observe_wrapper_source"]
142def observe_wrapper_source(
143 target: Any, forward: Callable[..., Any], companions: dict[str, Any], *, original_forward: Any,
144) -> dict[str, Any]:
145 """Lower a native rewrite while its closure is alive; retain source strings only.
147 ``original_forward`` identifies the method saved by the native patch.
148 Models and closures stay scoped; runtime mesh and communication state are
149 never queried or synthesized by this source reader.
150 """
151 if getattr(forward, "__func__", forward) is getattr(original_forward, "__func__", original_forward):
152 return {"body": None, "imports": []}
153 function = getattr(forward, "__func__", forward)
154 node, captures = _wrapper_capture(function)
155 source_bindings = _installed_closure_bindings(function, node.name)
156 target_names, original_names = _bound_capture_names(captures, target, original_forward)
157 bindings, literals = _closure_bindings(function, captures, companions)
158 initializers, state_imports = _companion_initializers(
159 function, captures, bindings, target_names, original_names, literals,
160 )
161 cp_scalars = _native_cp_scalars(function, captures, bindings)
162 if cp_scalars:
163 offset = 1 if ast.get_docstring(node) is not None else 0
164 node.body[offset:offset] = ast.parse("\n".join(
165 f"{name} = cp_mesh.{method}()" for name, method in sorted(cp_scalars.items())
166 )).body
167 original = original_names[0] if original_names else "original_forward"
168 target_name = target_names[0] if target_names else "target_module"
169 parameters = ", ".join(sorted(set(captures) | {target_name} | ({"cp_mesh"} if cp_scalars else set())))
170 attrs = ", ".join(f"{attr!r}: {name}" for name, attr in bindings.items() if attr is not None)
171 source = (f"def observed({parameters}):\n {original} = {target_name}.forward\n"
172 + textwrap.indent(ast.unparse(node), " ")
173 + f"\n return _ForwardRewriteRequest({target_name}, {node.name}, companion_attrs={{{attrs}}})\n")
174 tree = ast.parse(source).body[0]
175 body = _nested_forward_body(tree, node.name, target_name=target_name, literals=literals,
176 bound_globals=set(source_bindings))
177 if body is None:
178 raise RuntimeError(f"codegen cannot lower observed forward {forward.__qualname__}")
179 globals_used = _referenced_global_names("\n".join((*source_bindings.values(), ast.unparse(node)))) - set(captures)
180 owner = function.__globals__["__name__"]
181 imports = [(owner, name) for name in sorted(globals_used & function.__globals__.keys())]
182 imports.extend(state_imports)
183 if "_get_cp_submesh" in body:
184 imports.append(("hyper_parallel.distributed._builder.applier", "_get_cp_submesh"))
185 return {"body": body, "imports": imports, "bindings": tuple(source_bindings.values()),
186 "initializers": initializers,
187 "definition": _wrapper_definition(node, body, getattr(forward, "__self__", None) is target)}
190def _wrapper_capture(function: Any) -> tuple:
191 """Read an already-installed closure without executing its owner or runtime resources."""
192 node = ast.parse(textwrap.dedent(inspect.getsource(function.__code__))).body[0]
193 node.decorator_list = []
194 _strip_annotations(node)
195 return node, dict(inspect.getclosurevars(function).nonlocals)
198def _installed_closure_bindings(function: Any, name: str) -> dict[str, str]:
199 """Resolve the native owner's aliases without inspecting arbitrary global runtime objects."""
200 qualname = _function_source_qualname(function)
201 owner = function.__globals__.get(qualname.partition(".<locals>.")[0])
202 node = ast.parse(textwrap.dedent(inspect.getsource(owner.__code__))).body[0] if inspect.isfunction(owner) else None
203 imported = {symbol: value.__name__ for symbol, value in function.__globals__.items()
204 if inspect.ismodule(value) or inspect.isfunction(value) or inspect.isbuiltin(value)}
205 return _closure_source_bindings(node, name, imported)
208def _closure_bindings(function: Any, captures: dict[str, Any], companions: dict[str, Any]) -> tuple[dict, dict]:
209 """Project configuration and native-published state without retaining objects."""
210 bindings = {name: next((attr for attr, value in companions.items() if value is captured), None)
211 for name, captured in captures.items() if not isinstance(captured, (str, int, float, bool, type(None)))}
212 declared, parameters = _native_companion_bindings(function)
213 bindings.update({name: attr for name, attr in declared.items() if name in captures
214 and attr in companions and companions[attr] is captures[name]})
215 literals = {name: value for name, value in captures.items()
216 if isinstance(value, (str, int, float, bool, type(None)))
217 and name not in {"cp_rank", "cp_size"} and name not in WRAPPER_CONTEXT
218 and (not bindings.get(name) or name in parameters)}
219 return bindings, literals
222def _bound_capture_names(captures: dict[str, Any], target: Any, original: Any) -> tuple[list[str], list[str]]:
223 """Identify the native target and the specific saved forward, not arbitrary methods."""
224 targets = [name for name, value in captures.items() if value is target]
225 forwards = [name for name, value in captures.items()
226 if getattr(value, "__self__", None) is target
227 and getattr(value, "__func__", None) is getattr(original, "__func__", None)]
228 return targets, forwards
231def _companion_initializers(
232 function: Any, captures: dict[str, Any], bindings: dict[str, str],
233 target_names: list[str], original_names: list[str], literals: dict[str, Any],
234) -> tuple[tuple[str, ...], list[tuple[str, str]]]:
235 """Rebuild explicitly published state from its native constructor, never from the live object."""
236 qualname = _function_source_qualname(function)
237 owner = function.__globals__.get(qualname.partition(".<locals>.")[0])
238 if not inspect.isfunction(owner):
239 return (), []
240 tree = ast.parse(textwrap.dedent(inspect.getsource(owner.__code__))).body[0]
241 assignments = {node.targets[0].id: node.value for node in tree.body if isinstance(node, ast.Assign)
242 and len(node.targets) == 1 and isinstance(node.targets[0], ast.Name)}
243 target_names = _companion_target_names(tree, assignments, target_names, original_names)
244 initializers, imports = [], []
245 for name, attr in bindings.items():
246 value = assignments.get(name)
247 if attr is None or not isinstance(value, ast.Call) or not isinstance(value.func, ast.Name):
248 continue
249 constructor = function.__globals__.get(value.func.id)
250 if constructor is not type(captures[name]) or not _assigned_once(tree, name):
251 continue
252 arguments = _companion_call_arguments(value, target_names, literals, name)
253 module, symbol = constructor.__module__, constructor.__name__
254 if getattr(importlib.import_module(module), symbol, None) is not constructor:
255 raise RuntimeError(f"codegen companion constructor {constructor!r} is not importable")
256 initializers.append(f"self.{attr} = {symbol}({', '.join(arguments)})")
257 imports.append((module, symbol))
258 return tuple(dict.fromkeys(initializers)), imports
261def _companion_target_names(
262 tree: ast.FunctionDef, assignments: dict[str, ast.expr], target_names: list[str], original_names: list[str],
263) -> list[str]:
264 """Resolve unchanged native owners of the specific saved forward."""
265 target_names = list(target_names)
266 for name in original_names:
267 value = assignments.get(name)
268 if isinstance(value, ast.Attribute) and value.attr == "forward" and isinstance(value.value, ast.Name):
269 if not any(isinstance(node, ast.Name) and node.id == value.value.id and isinstance(node.ctx, ast.Store)
270 for node in ast.walk(tree)):
271 target_names.append(value.value.id)
272 return target_names
275def _companion_call_arguments(
276 call: ast.Call, target_names: list[str], literals: dict[str, Any], name: str,
277) -> list[str]:
278 """Render proven constructor arguments while preserving positional and keyword order."""
279 arguments = []
280 for argument in (*call.args, *(keyword.value for keyword in call.keywords)):
281 if isinstance(argument, ast.Name) and argument.id in target_names:
282 arguments.append("self")
283 elif isinstance(argument, ast.Name) and argument.id in literals:
284 arguments.append(repr(literals[argument.id]))
285 else:
286 try:
287 arguments.append(repr(ast.literal_eval(argument)))
288 except (ValueError, TypeError) as exc:
289 raise RuntimeError(f"codegen cannot rebuild companion {name!r} from a dynamic argument") from exc
290 positional = arguments[:len(call.args)]
291 keywords = [f"{keyword.arg}={text}" if keyword.arg else f"**{text}"
292 for keyword, text in zip(call.keywords, arguments[len(call.args):])]
293 return [*positional, *keywords]
296def _native_companion_bindings(function: Any) -> tuple[dict[str, str], set[str]]:
297 """Preserve the native request's named state, including optional None contexts."""
298 qualname = _function_source_qualname(function)
299 owner = function.__globals__.get(qualname.partition(".<locals>.")[0])
300 if not inspect.isfunction(owner):
301 return {}, set()
302 tree = ast.parse(textwrap.dedent(inspect.getsource(owner.__code__)))
303 return _companion_attr_bindings(tree), set(inspect.signature(owner, follow_wrapped=False).parameters)
306def _native_cp_scalars(function: Any, captures: dict[str, Any], bindings: dict[str, str]) -> dict[str, str]:
307 """Prove captured CP scalars originate in native context fields without reading a mesh."""
308 qualname = _function_source_qualname(function)
309 owner = function.__globals__.get(qualname.partition(".<locals>.")[0])
310 if not inspect.isfunction(owner):
311 return {}
312 tree = ast.parse(textwrap.dedent(inspect.getsource(owner.__code__)))
313 parameters = set(inspect.signature(owner, follow_wrapped=False).parameters)
314 cp_scalars = {}
315 for node in tree.body[0].body:
316 if not isinstance(node, ast.Assign) or len(node.targets) != 1 or not isinstance(node.targets[0], ast.Name):
317 continue
318 name = node.targets[0].id
319 if bindings.get(name) or _cp_context_field(node.value, parameters, captures.get(name)) != name:
320 continue
321 if not _assigned_once(tree, name):
322 continue
323 cp_scalars[name] = "get_local_rank" if name == "cp_rank" else "size"
324 return cp_scalars
327def _cp_context_field(value: ast.expr, parameters: set[str], captured: Any) -> str | None:
328 """Recognize one integer CP field read from an unchanged native context parameter."""
329 if not isinstance(captured, int) or isinstance(captured, bool):
330 return None
331 arguments = _context_getattr_arguments(value)
332 if not arguments:
333 return None
334 context, field = arguments[:2]
335 if not isinstance(context, ast.Name) or context.id not in parameters:
336 return None
337 if not isinstance(field, ast.Constant) or field.value not in {"cp_rank", "cp_size"}:
338 return None
339 expected = ast.Constant(value=0 if field.value == "cp_rank" else 1)
340 if len(arguments) == 3 and ast.dump(arguments[2]) != ast.dump(expected):
341 return None
342 return field.value
345def _context_getattr_arguments(value: ast.expr) -> list[ast.expr]:
346 """Read a native getattr or int(getattr(...)) using syntax accepted by the lint runtime."""
347 if isinstance(value, ast.Call) and isinstance(value.func, ast.Name) and value.func.id == "int":
348 if len(value.args) != 1 or value.keywords:
349 return []
350 value = value.args[0]
351 if (isinstance(value, ast.Call) and isinstance(value.func, ast.Name) and value.func.id == "getattr"
352 and len(value.args) in (2, 3) and not value.keywords):
353 return value.args
354 return []