Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / codegen / inline / recognition.py: 87%
452 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"""Framework structural recognition for inline component selection.
17Which generic component replaces a matched source module is decided by the
18*structure of the family's own replacement factory* -- the generic component it
19constructs, the module that class comes from, the constructor arguments it
20passes and the kernel entry it hands over -- never by the model's name and
21never by a component-name table. The factory is not codegen-specific: the YAML
22already names it for the native path, so reading it adds no family codegen
23declaration.
25This is what makes "native HF model + one YAML" sufficient: a family whose
26attention is fused-QKV, whose experts are batched, or whose norm is an RMSNorm
27is covered the moment its runtime factory exists.
28"""
30from __future__ import annotations
32import ast
33import inspect
34import os
35import symtable
36import sys
37import textwrap
38from collections.abc import Collection
39from copy import deepcopy
40from dataclasses import dataclass
41from functools import lru_cache
42from typing import Any
44from hyper_parallel.codegen.inline.attention import _strip_annotations
45from hyper_parallel.distributed.recipe_spec import WRAPPER_CONTEXT
48def _function_source_qualname(function: Any) -> str:
49 """Locate a function's lexical definition even when decorators changed its public name."""
50 code = function.__code__
51 qualname = getattr(code, "co_qualname", None)
52 if qualname is not None:
53 return qualname
54 lines, _ = inspect.findsource(code)
55 qualname = _source_qualname(ast.parse("".join(lines)), code)
56 if qualname is None:
57 raise RuntimeError(f"codegen: cannot locate source definition {code.co_name!r} "
58 f"at {code.co_filename}:{code.co_firstlineno}")
59 return qualname
62def _source_qualname(tree: ast.AST, code: Any, prefix: str = "") -> str | None:
63 """Match the code's definition line and reconstruct Python's lexical scope path."""
64 for node in ast.iter_child_nodes(tree):
65 nested_prefix = prefix
66 if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
67 name = prefix + node.name
68 is_function = not isinstance(node, ast.ClassDef)
69 start = min([node.lineno, *(decorator.lineno for decorator in node.decorator_list)])
70 if is_function and node.name == code.co_name and start == code.co_firstlineno:
71 return name
72 nested_prefix = name + (".<locals>." if is_function else ".")
73 found = _source_qualname(node, code, nested_prefix)
74 if found is not None:
75 return found
76 return None
79@dataclass(frozen=True)
80class ReplacementArgument:
81 """One constructor keyword a replacement factory passes.
83 ``value`` is the argument's source text; ``None`` marks an argument bound to
84 the factory's own parameter (a runtime value such as ``module_fqn``), whose
85 generated value is the component's constructor default.
86 """
88 name: str
89 value: str | None = None
92@dataclass(frozen=True)
93class ReplacementTarget:
94 """The component a replacement factory constructs, read from its source.
96 Every fact the generated replacement needs is here: ``component`` (the class
97 the factory builds) and ``module`` (where that class is imported from) give
98 the emitted import; ``wraps_source`` says whether the matched module is
99 handed over as the component's ``module`` argument (a wrap) or whether the
100 component drops in for the source class; ``arguments`` carries the remaining
101 constructor keywords; ``interface`` names the family symbol the factory
102 hands over -- a component that receives one is rendered rather than merely
103 imported, so its class and that interface stay visible in the artifact.
104 """
106 component: str
107 module: str
108 wraps_source: bool
109 arguments: tuple[ReplacementArgument, ...]
110 interface: str | None = None
113@dataclass(frozen=True)
114class InnerWrapperTarget:
115 """Source-visible helper and companion mesh attribute of an inner wrapper."""
117 helper_module: str | None = None
118 helper_name: str | None = None
119 inline_body: str | None = None
120 extra_imports: tuple[tuple[str, str], ...] = ()
121 definition: str | None = None
122 bindings: tuple[str, ...] = ()
125def class_name_of(qualified_type: str | None) -> str | None:
126 """Return the bare class name of a dotted ``module_type`` path."""
127 if not qualified_type:
128 return None
129 return qualified_type.rsplit(".", 1)[-1] or None
132def family_from_target(target: str | None) -> str | None:
133 """Infer the adapter family directory from a framework adapter path.
135 ``hyper_parallel.models.<family>.adapter...`` -> ``<family>``. Returns
136 ``None`` for targets that are not model-adapter paths (for example a
137 framework recipe), which callers treat as "no family provider".
138 """
139 parts = (target or "").split(".")
140 if len(parts) >= 3 and parts[:2] == ["hyper_parallel", "models"]:
141 return parts[2]
142 return None
145def adapter_path_parts(target: str | None) -> bool:
146 """Whether a target lives under the ``models/<family>/adapter`` convention."""
147 parts = (target or "").split(".")
148 return len(parts) >= 4 and parts[:2] == ["hyper_parallel", "models"] and parts[3] == "adapter"
151def replacement_target(factory: Any) -> ReplacementTarget | None:
152 """Read the component one ``@module_replacement`` factory constructs.
154 Only a factory that constructs an imported class directly (``Ctor(...)``)
155 yields a target: that is the call codegen can sink into the generated
156 ``__init__``. A factory that builds through a class method
157 (``SomeExperts.from_module(...)``) has no constructor call to sink, so the
158 rule is left untouched -- the same conservative behaviour a component-name
159 table gave, without the table.
160 """
161 try:
162 source = textwrap.dedent(inspect.getsource(factory))
163 tree = ast.parse(source)
164 except (OSError, TypeError, SyntaxError):
165 return None
166 imported = _factory_imported_modules(tree)
167 parameters = _parameter_names(factory)
168 for node in ast.walk(tree):
169 if not isinstance(node, ast.Call) or not isinstance(node.func, ast.Name):
170 continue
171 component = node.func.id
172 module = imported.get(component) or _global_class_module(factory, component)
173 if module is None:
174 continue
175 return ReplacementTarget(
176 component=component,
177 module=module,
178 wraps_source=any(
179 keyword.arg == "module"
180 and isinstance(keyword.value, ast.Name)
181 and keyword.value.id in parameters
182 for keyword in node.keywords
183 ),
184 arguments=_factory_arguments(node, parameters),
185 interface=next(
186 (
187 keyword.value.id
188 for keyword in node.keywords
189 if isinstance(keyword.value, ast.Name)
190 and keyword.value.id in getattr(factory, "__globals__", {})
191 and callable(factory.__globals__[keyword.value.id])
192 ),
193 None,
194 ),
195 )
196 return None
199def _factory_imported_modules(tree: ast.AST) -> dict[str, str]:
200 """Module path per name the factory source imports (``from X import Y``)."""
201 imported: dict[str, str] = {}
202 for node in ast.walk(tree):
203 if isinstance(node, ast.ImportFrom) and node.module:
204 for alias in node.names:
205 imported.setdefault(alias.asname or alias.name, node.module)
206 elif isinstance(node, ast.Import):
207 for alias in node.names:
208 imported.setdefault(alias.asname or alias.name.split(".")[0], alias.name)
209 return imported
212def _global_class_module(factory: Any, name: str) -> str | None:
213 """Module path of a class the factory's own module imported at module level."""
214 value = getattr(factory, "__globals__", {}).get(name)
215 module = getattr(value, "__module__", None)
216 return module if isinstance(value, type) and module else None
219def _parameter_names(factory: Any) -> set[str]:
220 """Parameter names of the factory itself (runtime values, not literals)."""
221 try:
222 return set(inspect.signature(factory).parameters)
223 except (TypeError, ValueError):
224 return set()
227def _factory_arguments(
228 call: ast.Call, parameters: set[str]
229) -> tuple[ReplacementArgument, ...]:
230 """The constructor keywords a factory passes, minus the wrapped module.
232 A value that names one of the factory's own parameters is recorded without
233 its text (the component's constructor default applies); a value naming a
234 callable in the factory's globals -- a kernel entry handed over -- keeps its
235 symbol so the artifact stays readable; anything else keeps its own text.
236 """
237 arguments: list[ReplacementArgument] = []
238 for keyword in call.keywords:
239 if keyword.arg is None:
240 continue
241 if keyword.arg == "module" and isinstance(keyword.value, ast.Name):
242 continue
243 value: str | None = (
244 None
245 if isinstance(keyword.value, ast.Name) and keyword.value.id in parameters
246 else ast.unparse(keyword.value)
247 )
248 arguments.append(ReplacementArgument(keyword.arg, value))
249 return tuple(arguments)
252def inner_wrapper_target(
253 factory_path: str | None, *, construction_kwargs: tuple[str, ...] = (),
254) -> InnerWrapperTarget | None:
255 """Recover an inner wrapper's emitted helper contract from its source."""
256 source = _wrapper_factory_ast(factory_path)
257 if source is None:
258 return None
259 module_name, tree, factory_node = source
260 request_owner = _request_owner(factory_node, tree)
261 replacement_name = _replacement_callable(request_owner)
262 literals = _wrapper_literals(factory_node, construction_kwargs)
263 if request_owner is not None and request_owner is not factory_node:
264 literals = _delegate_literals(factory_node, request_owner, literals)
265 bindings = _closure_source_bindings(request_owner, replacement_name, _factory_imported_modules(tree))
266 helper_name = (
267 _forward_helper_name(request_owner, replacement_name)
268 if request_owner is not None and replacement_name
269 else None
270 )
271 module_functions = {
272 node.name
273 for node in tree.body
274 if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
275 }
276 module_symbols = module_functions | _factory_imported_modules(tree).keys()
277 if not helper_name or helper_name not in module_functions:
278 inline_body = _nested_forward_body(
279 request_owner, replacement_name, target_name=_original_forward_target(request_owner),
280 literals=literals, bound_globals=set(bindings),
281 )
282 if inline_body is None:
283 return None
284 forward = next(node for node in ast.walk(request_owner)
285 if isinstance(node, ast.FunctionDef) and node.name == replacement_name)
286 return InnerWrapperTarget(
287 inline_body=inline_body,
288 extra_imports=_body_imports("\n".join((*bindings.values(), inline_body)), module_name, module_symbols),
289 definition=_wrapper_definition(forward, inline_body, False), bindings=tuple(bindings.values()),
290 )
291 inline_body = _helper_keyword_body(
292 request_owner, replacement_name, _module_function(tree, helper_name),
293 literals,
294 )
295 return InnerWrapperTarget(
296 helper_module=module_name,
297 helper_name=helper_name,
298 inline_body=inline_body,
299 extra_imports=_body_imports(inline_body, module_name, module_symbols - {helper_name}),
300 )
303def _wrapper_factory_ast(path: str | None) -> tuple[str, ast.Module, Any] | None:
304 """Find the declared factory without importing or invoking it."""
305 module_name, _, name = (path or "").rpartition(".")
306 if not module_name or not name:
307 return None
308 tree = _module_source_tree(module_name)
309 if tree is None:
310 return None
311 factory = _module_function(tree, name)
312 return (module_name, tree, factory) if factory is not None else None
315def _body_imports(body: str | None, module: str, functions: set[str]) -> tuple[tuple[str, str], ...]:
316 """Keep native helpers referenced by the lowered closure visible in its new module."""
317 names = {node.id for node in ast.walk(ast.parse(body or "")) if isinstance(node, ast.Name)}
318 imports = [(module, name) for name in sorted(names & functions)]
319 if "_get_cp_submesh" in names:
320 imports.append(("hyper_parallel.distributed._builder.applier", "_get_cp_submesh"))
321 return tuple(imports)
324def _single_helper_delegate(
325 tree: ast.AST, replacement_name: str, helper_name: str,
326) -> tuple[ast.FunctionDef, ast.Call | None]:
327 """Identify a pure return call without discarding surrounding control flow."""
328 forward = next(node for node in ast.walk(tree)
329 if isinstance(node, ast.FunctionDef) and node.name == replacement_name)
330 body = forward.body[1:] if ast.get_docstring(forward) is not None else forward.body
331 if len(body) != 1 or not isinstance(body[0], ast.Return):
332 return forward, None
333 call = body[0].value
334 if not (isinstance(call, ast.Call) and isinstance(call.func, ast.Name)
335 and call.func.id == helper_name and any(item.arg is not None for item in call.keywords)):
336 return forward, None
337 return forward, call
340def _positional_contract(args: ast.arguments, excluded: set[str]) -> tuple[tuple[str, bool, str | None], ...]:
341 """Compare names, positional-only constraints and default expressions."""
342 parameters = (*args.posonlyargs, *args.args)
343 defaults = [None] * (len(parameters) - len(args.defaults)) + list(args.defaults)
344 return tuple((item.arg, index < len(args.posonlyargs), ast.dump(value) if value is not None else None)
345 for index, (item, value) in enumerate(zip(parameters, defaults)) if item.arg not in excluded)
348def _keyword_names(call: ast.Call) -> set[str]:
349 """Collect symbols referenced by explicitly supplied helper keywords."""
350 return {node.id for item in call.keywords if item.arg is not None
351 for node in ast.walk(item.value) if isinstance(node, ast.Name)}
354def _forwards_parameters(args: ast.arguments, call: ast.Call) -> bool:
355 """Ensure the token can replace the native delegate's argument forwarding."""
356 names = [item.arg for item in (*args.posonlyargs, *args.args)]
357 if [ast.unparse(item) for item in call.args[1:]] != names:
358 return False
359 kwargs = [ast.unparse(item.value) for item in call.keywords if item.arg is None]
360 if kwargs != ([args.kwarg.arg] if args.kwarg else []):
361 return False
362 return not set(names).intersection(_keyword_names(call))
365def _helper_signature_matches(forward: ast.FunctionDef, helper: ast.FunctionDef, call: ast.Call) -> bool:
366 """Reject signature adaptation rather than changing positional/default behavior."""
367 if forward.args.vararg or forward.args.kwonlyargs:
368 return False
369 parameters = (*helper.args.posonlyargs, *helper.args.args)
370 if not parameters:
371 return False
372 excluded = {item.arg for item in call.keywords if item.arg is not None} | {parameters[0].arg}
373 if _positional_contract(forward.args, set()) != _positional_contract(helper.args, excluded):
374 return False
375 return _forwards_parameters(forward.args, call)
378def _original_forward_target(tree: ast.AST | None) -> str | None:
379 """Find the owner whose original forward the wrapper saves."""
380 if tree is None:
381 return None
382 for node in ast.walk(tree):
383 if (isinstance(node, ast.Assign) and isinstance(node.value, ast.Attribute)
384 and node.value.attr == "forward" and isinstance(node.value.value, ast.Name)):
385 return node.value.value.id
386 return None
389def _wrapper_literals(factory: ast.FunctionDef, construction_kwargs: tuple[str, ...]) -> dict[str, Any]:
390 """Read only literal native defaults and recorded overrides, never runtime resources."""
391 parameters = (*factory.args.posonlyargs, *factory.args.args)
392 values = {}
393 for parameter, value in zip(parameters[len(parameters) - len(factory.args.defaults):], factory.args.defaults):
394 if parameter.arg in WRAPPER_CONTEXT:
395 continue
396 try:
397 values[parameter.arg] = ast.literal_eval(value)
398 except (ValueError, TypeError):
399 continue
400 for argument in construction_kwargs:
401 name, text = argument.split("=", 1)
402 if name in WRAPPER_CONTEXT:
403 raise ValueError(f"codegen: native runtime argument {name!r} cannot be frozen as configuration")
404 values[name] = ast.literal_eval(text)
405 return values
408def _helper_keyword_body(
409 tree: ast.AST, replacement_name: str, helper: ast.FunctionDef, literals: dict[str, Any],
410) -> str | None:
411 """Keep explicit keywords only when native argument forwarding is preserved."""
412 forward, call = _single_helper_delegate(tree, replacement_name, helper.name)
413 if call is None:
414 return None
415 if not _helper_signature_matches(forward, helper, call):
416 raise RuntimeError(f"codegen: helper delegate {replacement_name!r} is not an argument passthrough")
417 target = _original_forward_target(tree)
418 if target is None:
419 raise RuntimeError(
420 f"codegen: cannot preserve helper arguments for {replacement_name!r} without its target binding"
421 )
422 if not call.args or not isinstance(call.args[0], ast.Name) or call.args[0].id != target:
423 raise RuntimeError(f"codegen: helper delegate {replacement_name!r} has a different target")
424 lowered = ast.parse(_nested_forward_body(tree, replacement_name, target_name=target, literals=literals))
425 for item in ast.walk(lowered):
426 if isinstance(item, ast.Call) and isinstance(item.func, ast.Name) and item.func.id == helper.name:
427 names = _keyword_names(item)
428 if names - {"self", "_get_cp_submesh"}:
429 raise RuntimeError(f"codegen: helper delegate has unresolved keyword names {sorted(names - {'self'})}")
430 item.args = [ast.Name(id="self", ctx=ast.Load()), ast.Name(id="__hp_forward_args__", ctx=ast.Load())]
431 item.keywords = [keyword for keyword in item.keywords if keyword.arg is not None]
432 active = ast.unparse(ast.fix_missing_locations(lowered))
433 return (f"if self.cp_enable:\n{textwrap.indent(active, ' ')}\n\n"
434 "return self._forward_impl(__hp_forward_args__)")
437def _module_function(tree: ast.Module, name: str) -> ast.AST | None:
438 """Return a named top-level function from a parsed module."""
439 return next(
440 (
441 node
442 for node in tree.body
443 if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
444 and node.name == name
445 ),
446 None,
447 )
450def _replacement_callable(request_owner: ast.AST | None) -> str | None:
451 """Resolve the callable installed by an inner-wrapper request."""
452 if request_owner is None:
453 return None
454 return _rewrite_request_callable(request_owner) or _returned_nested_callable(request_owner)
457def _request_owner(factory_node: ast.AST, tree: ast.Module) -> ast.AST | None:
458 """Return the factory or its module-level delegate that builds the request."""
459 if (
460 _rewrite_request_callable(factory_node) is not None
461 or _returned_nested_callable(factory_node) is not None
462 ):
463 return factory_node
464 functions = {
465 node.name: node
466 for node in tree.body
467 if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
468 }
469 for node in ast.walk(factory_node):
470 if not isinstance(node, ast.Return) or not isinstance(node.value, ast.Call):
471 continue
472 if not isinstance(node.value.func, ast.Name):
473 continue
474 delegate = functions.get(node.value.func.id)
475 if delegate is not None and (
476 _rewrite_request_callable(delegate) is not None or _returned_nested_callable(delegate) is not None
477 ):
478 return delegate
479 return None
482def _delegate_literals(factory: ast.FunctionDef, delegate: ast.FunctionDef, values: dict[str, Any]) -> dict[str, Any]:
483 """Bind one same-module delegate using only native defaults, literals and configured arguments."""
484 result = {}
485 for name, expression in _delegate_expressions(factory, delegate).items():
486 if name in WRAPPER_CONTEXT:
487 if not isinstance(expression, ast.Name) or expression.id != name:
488 raise RuntimeError(f"codegen cannot reinterpret native delegate context {name!r}")
489 continue
490 if isinstance(expression, ast.Name) and expression.id in values:
491 result[name] = values[expression.id]
492 continue
493 try:
494 result[name] = ast.literal_eval(expression)
495 except (ValueError, TypeError):
496 continue
497 return result
500def _delegate_expressions(factory: ast.FunctionDef, delegate: ast.FunctionDef) -> dict[str, ast.expr]:
501 """Project one direct delegate call onto its native positional and keyword parameters."""
502 call = next(node.value for node in ast.walk(factory) if isinstance(node, ast.Return)
503 and isinstance(node.value, ast.Call) and isinstance(node.value.func, ast.Name)
504 and node.value.func.id == delegate.name)
505 parameters = (*delegate.args.posonlyargs, *delegate.args.args)
506 expressions = {param.arg: value for param, value in zip(
507 parameters[len(parameters) - len(delegate.args.defaults):], delegate.args.defaults,
508 )}
509 expressions.update({param.arg: value for param, value in zip(delegate.args.kwonlyargs, delegate.args.kw_defaults)
510 if value is not None})
511 expressions.update({param.arg: value for param, value in zip(parameters, call.args)})
512 if any(keyword.arg is None for keyword in call.keywords):
513 raise RuntimeError("codegen cannot bind dynamic inner-wrapper delegate keywords")
514 expressions.update({keyword.arg: keyword.value for keyword in call.keywords})
515 return expressions
518def _closure_source_bindings(
519 owner: ast.AST | None, name: str | None, imported: dict[str, str],
520) -> dict[str, str]:
521 """Keep native module imports and callable aliases outside the generated forward."""
522 if owner is None or name is None:
523 return {}
524 forward = next((node for node in ast.walk(owner) if isinstance(node, ast.FunctionDef) and node.name == name), None)
525 if forward is None:
526 return {}
527 captured = _captured_forward_names(owner, name)
528 callables = {node.func.id for node in ast.walk(forward)
529 if isinstance(node, ast.Call) and isinstance(node.func, ast.Name)}
530 assignments = {node.targets[0].id: node for node in owner.body if isinstance(node, ast.Assign)
531 and len(node.targets) == 1 and isinstance(node.targets[0], ast.Name)}
532 bindings: dict[str, str] = {}
533 attempted: set[str] = set()
535 def resolve(symbol: str) -> bool:
536 """Accept only aliases rooted in native imports, with no object construction."""
537 if symbol in imported or symbol in bindings:
538 return True
539 if symbol in attempted:
540 return False
541 attempted.add(symbol)
542 statement = assignments.get(symbol)
543 if statement is None:
544 return False
545 if not _assigned_once(owner, symbol):
546 return False
547 value = statement.value
548 if not _module_import_expression(value, imported):
549 if symbol not in callables:
550 return False
551 while isinstance(value, ast.Attribute):
552 value = value.value
553 if not isinstance(value, ast.Name) or value.id == symbol or not resolve(value.id):
554 return False
555 bindings[symbol] = ast.unparse(statement)
556 return True
558 for symbol in sorted(captured):
559 resolve(symbol)
560 return bindings
563def _assigned_once(owner: ast.AST, name: str) -> bool:
564 """Require one lexical assignment before interpreting a captured native binding."""
565 return sum(isinstance(node, ast.Name) and node.id == name and isinstance(node.ctx, ast.Store)
566 for node in ast.walk(owner)) == 1
569def _module_import_expression(value: ast.expr, imported: dict[str, str]) -> bool:
570 """Recognize only a literal importlib module load, never an executor constructor."""
571 if not isinstance(value, ast.Call) or not isinstance(value.func, ast.Attribute):
572 return False
573 function = value.func
574 if not isinstance(function.value, ast.Name) or function.attr != "import_module":
575 return False
576 if imported.get(function.value.id) != "importlib" or value.keywords or len(value.args) != 1:
577 return False
578 return isinstance(value.args[0], ast.Constant) and isinstance(value.args[0].value, str)
581def _wrapper_definition(node: ast.FunctionDef, body: str, bound: bool) -> str:
582 """Reuse the native wrapper signature instead of guessing its variadic arguments."""
583 node = deepcopy(node)
584 node.name = "forward"
585 node.decorator_list = []
586 _strip_annotations(node)
587 if not bound:
588 parameters = node.args.posonlyargs if node.args.posonlyargs else node.args.args
589 parameters.insert(0, ast.arg(arg="self"))
590 if node.args.vararg:
591 body = body.replace("__hp_forward_positional__", node.args.vararg.arg)
592 if node.args.kwarg:
593 body = body.replace("__hp_forward_keywords__", node.args.kwarg.arg)
594 node.body = ast.parse(body).body
595 return ast.unparse(ast.fix_missing_locations(node))
598def _returned_nested_callable(tree: ast.AST) -> str | None:
599 """Return a nested callable returned directly by an inner wrapper."""
600 nested = {
601 node.name
602 for node in ast.iter_child_nodes(tree)
603 if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
604 }
605 for node in ast.walk(tree):
606 if isinstance(node, ast.Return) and isinstance(node.value, ast.Name):
607 if node.value.id in nested:
608 return node.value.id
609 return None
612@lru_cache(maxsize=None)
613def _module_source(module_name: str) -> str | None:
614 """Load module source once without importing optional accelerator deps."""
615 relative = os.path.join(*module_name.split(".")) + ".py"
616 for root in sys.path:
617 path = os.path.join(root or os.curdir, relative)
618 if not os.path.isfile(path):
619 continue
620 try:
621 with open(path, "r", encoding="utf-8") as handle:
622 return handle.read()
623 except (OSError, UnicodeError):
624 return None
625 return None
628def _module_source_tree(module_name: str) -> ast.Module | None:
629 """Parse cached module source into an isolated syntax tree."""
630 source = _module_source(module_name)
631 if source is None:
632 return None
633 try:
634 return ast.parse(source)
635 except SyntaxError:
636 return None
639def _rewrite_request_callable(tree: ast.AST) -> str | None:
640 """Return the replacement callable passed to ``_ForwardRewriteRequest``."""
641 for node in ast.walk(tree):
642 if not isinstance(node, ast.Call) or not isinstance(node.func, ast.Name):
643 continue
644 if node.func.id == "_ForwardRewriteRequest" and len(node.args) >= 2:
645 if isinstance(node.args[1], ast.Name):
646 return node.args[1].id
647 return None
650def _forward_helper_name(tree: ast.AST, replacement_name: str) -> str | None:
651 """Return the module-level helper called by the replacement forward."""
652 for node in ast.walk(tree):
653 if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) or node.name != replacement_name:
654 continue
655 for child in ast.walk(node):
656 if isinstance(child, ast.Return) and isinstance(child.value, ast.Call):
657 if isinstance(child.value.func, ast.Name):
658 return child.value.func.id
659 return None
662def _captured_forward_names(tree: ast.AST, name: str) -> set[str]:
663 """Read lexical captures without importing or executing the wrapper."""
664 pending = list(symtable.symtable(ast.unparse(tree), "<codegen wrapper>", "exec").get_children())
665 while pending:
666 scope = pending.pop()
667 if scope.get_name() == name and scope.get_type() == "function":
668 return set(scope.get_frees())
669 pending.extend(scope.get_children())
670 return set()
673def _uses_native_cp_argument(tree: ast.FunctionDef) -> bool:
674 """Do not reinterpret an unrelated local or reassigned mesh as native CP."""
675 return (
676 "cp_mesh" in {item.arg for item in (*tree.args.posonlyargs, *tree.args.args, *tree.args.kwonlyargs)}
677 and not any(isinstance(item, ast.Name) and item.id == "cp_mesh" and isinstance(item.ctx, ast.Store)
678 for item in ast.walk(tree))
679 )
682def _nested_forward_body(
683 tree: ast.AST, replacement_name: str | None, *, target_name: str | None = None,
684 literals: dict[str, Any] | None = None,
685 bound_globals: Collection[str] = (),
686) -> str | None:
687 """Lower a closure-backed rewrite into an imported-host dispatch body.
689 Keep the native control flow, including packed and exception branches.
690 Captured published state becomes instance attributes; the saved forward
691 calls the preserved source method. CP dispatch belongs to the helper path,
692 not to every closure (some wrappers run at CP1 or TP-only).
693 """
694 if not replacement_name:
695 return None
696 forward = next(
697 (
698 node
699 for node in ast.walk(tree)
700 if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
701 and node.name == replacement_name
702 ),
703 None,
704 )
705 if forward is None:
706 return None
707 companion_attrs = _companion_attr_bindings(tree)
708 original_forward = _original_forward_binding(tree)
709 if original_forward is None:
710 return None
711 captured = _captured_forward_names(tree, replacement_name)
712 runtime_cp = _uses_native_cp_argument(tree)
713 variadic = {}
714 if forward.args.vararg:
715 variadic[forward.args.vararg.arg] = "__hp_forward_positional__"
716 if forward.args.kwarg:
717 variadic[forward.args.kwarg.arg] = "__hp_forward_keywords__"
719 class ClosureBindings(ast.NodeTransformer):
720 """Rewrite captured closure bindings to generated-instance state."""
722 def visit_Name(self, node: ast.Name) -> ast.AST: # pylint: disable=invalid-name
723 """Rewrite a referenced symbol into its resolved source form."""
724 if node.id in variadic and isinstance(node.ctx, ast.Load):
725 return ast.copy_location(ast.Name(id=variadic[node.id], ctx=node.ctx), node)
726 if node.id == target_name:
727 return ast.copy_location(ast.Name(id="self", ctx=node.ctx), node)
728 if node.id == original_forward and node.id in captured and isinstance(node.ctx, ast.Load):
729 return ast.copy_location(ast.parse("self._forward_impl", mode="eval").body, node)
730 if literals is not None and node.id in captured and node.id in literals:
731 return ast.copy_location(ast.parse(repr(literals[node.id]), mode="eval").body, node)
732 if runtime_cp and node.id == "cp_mesh" and node.id in captured and node.id not in companion_attrs:
733 return ast.copy_location(ast.parse(
734 "_get_cp_submesh(self._hp_boundary.compiled.mesh, "
735 "self._hp_boundary.compiled.mesh_dim_names)", mode="eval",
736 ).body, node)
737 attr = companion_attrs.get(node.id)
738 if attr is None:
739 return node
740 return ast.copy_location(
741 ast.Attribute(
742 value=ast.Name(id="self", ctx=ast.Load()),
743 attr=attr,
744 ctx=node.ctx,
745 ),
746 node,
747 )
749 body = forward.body[1:] if ast.get_docstring(forward) is not None else forward.body
750 lowered = [ClosureBindings().visit(ast.fix_missing_locations(node)) for node in body]
751 if not lowered:
752 return None
753 _require_bound_captures(captured - set(bound_globals), lowered, replacement_name)
754 return "\n".join(ast.unparse(node) for node in lowered)
757def _require_bound_captures(captured: set[str], statements: list[ast.stmt], name: str) -> None:
758 """Reject emitted closure state without a source-visible binding."""
759 unresolved = sorted(captured & {
760 node.id for statement in statements for node in ast.walk(statement)
761 if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Load)
762 })
763 if unresolved:
764 raise RuntimeError(
765 f"codegen: cannot inline {name!r}; unresolved captured state {unresolved}"
766 )
769def _companion_attr_bindings(tree: ast.AST) -> dict[str, str]:
770 """Map closure variable names to their published companion attributes."""
771 result: dict[str, str] = {}
772 for node in ast.walk(tree):
773 if not isinstance(node, ast.keyword) or node.arg != "companion_attrs":
774 continue
775 if not isinstance(node.value, ast.Dict):
776 continue
777 for key, value in zip(node.value.keys, node.value.values):
778 if (
779 isinstance(key, ast.Constant)
780 and isinstance(key.value, str)
781 and isinstance(value, ast.Name)
782 ):
783 result[value.id] = key.value
784 return result
787def _original_forward_binding(tree: ast.AST) -> str | None:
788 """Return the local name that saves ``target.forward`` before rewriting."""
789 for node in ast.walk(tree):
790 if not isinstance(node, ast.Assign) or len(node.targets) != 1:
791 continue
792 target = node.targets[0]
793 value = node.value
794 if (
795 isinstance(target, ast.Name)
796 and isinstance(value, ast.Attribute)
797 and value.attr == "forward"
798 ):
799 return target.id
800 return None
803__all__ = [
804 "InnerWrapperTarget",
805 "ReplacementArgument",
806 "ReplacementTarget",
807 "adapter_path_parts",
808 "class_name_of",
809 "family_from_target",
810 "inner_wrapper_target",
811 "replacement_target",
812]