Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / codegen / inline / pipeline.py: 82%
172 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"""Two-stage inline modeling source pipeline."""
17from __future__ import annotations
19import ast
20from dataclasses import replace
21import importlib
22import textwrap
23from typing import Any
25from hyper_parallel.codegen.inline.ir import (
26 ImportPatch,
27 InlinePatchSet,
28 ModuleSnippetPatch,
29)
30from hyper_parallel.codegen.inline.meta_plan import normalize_inline_meta
31from hyper_parallel.codegen.inline.definition_edits import drop_shadowed_definitions
32from hyper_parallel.codegen.inline.forward_edits import _parallel_state_prefix
33from hyper_parallel.codegen.emit.parallel import _cp_dispatch_call
34from hyper_parallel.codegen.inline.patch_engine import apply_patch_set
35from hyper_parallel.codegen.inline.framework_spec import (
36 replacement_spec_for_observation,
37 strategy_spec_for as strategy_spec,
38)
39from hyper_parallel.codegen.inline.strategy_pass import build_strategy_patches, rule_block_classes
40from hyper_parallel.codegen.inline.observations import collect_source_observations
41from hyper_parallel.codegen.inline.source_plan import build_source_patch_plan
44def render_inline_modeling_with_plan(
45 source_text: str,
46 meta: Any,
47 model_type: str | None = None,
48 *,
49 patch_plan: Any = None,
50) -> tuple[str, Any]:
51 """Render source and return the independently normalized emission plan."""
52 rules = collect_source_observations(meta)
53 if not rules:
54 return source_text, meta
55 patches = patch_plan
56 recorded_local_compute = bool(
57 getattr(patches, "local_computes", ()) if patches is not None else ()
58 )
59 strategy_rules = (
60 tuple(replace(rule, local_compute_target=None) for rule in rules)
61 if recorded_local_compute
62 else rules
63 )
64 _require_inline_coverage(strategy_rules, model_type)
65 patch_set = build_source_patch_plan(
66 rules,
67 strategy_rules,
68 model_type,
69 _observed_boundary_classes(meta, patch_plan),
70 )
71 _add_recorded_forward_host_imports(source_text, patch_set, patch_plan)
72 _materialize_imported_forward_hosts(source_text, patch_set)
73 model_class = (getattr(meta, "source", None) or {}).get("model_class")
74 root_class_name = model_class.rsplit(":", 1)[-1].rsplit(".", 1)[-1] if model_class else None
75 rendered = apply_patch_set(source_text, patch_set, root_class_name=root_class_name)
76 # The copied modeling source brings its own decorated helpers that share
77 # names with the library functions the artifact imports, and a local
78 # definition wins over the import: the native path calls the library
79 # implementation (whose kernel binding is resolved in its own module), so a
80 # redefined copy makes the generated model run something else. Only names
81 # the base source defines with a decorator are candidates, so the classes and
82 # snippets the inline passes render (which share names with library imports
83 # on purpose) keep their definitions.
84 rendered = drop_shadowed_definitions(
85 rendered, _library_import_names(rendered) & _decorated_names(source_text)
86 )
87 normalized_meta = normalize_inline_meta(meta)
88 return rendered, normalized_meta
91def _add_recorded_forward_host_imports(
92 source_text: str,
93 patch_set: InlinePatchSet,
94 patch_plan: Any,
95) -> None:
96 """Expose observed replacement hosts needed by a forward rewrite.
98 A replacement application can be observed after the root model has built,
99 while its constructor belongs to an imported decoder rather than the copied
100 top-level source. In that case the frozen replacement record is the source
101 of truth for the concrete host type. Add its real import so the generic
102 imported-host materializer can emit the CP dispatch class.
103 """
104 source_classes = {
105 node.name
106 for node in ast.parse(source_text).body
107 if isinstance(node, ast.ClassDef)
108 }
109 imported_names = {
110 name
111 for item in patch_set.imports
112 if not item.raw
113 for name in item.names
114 }
115 replacements = (
116 getattr(patch_plan, "module_replacements", ())
117 if patch_plan is not None
118 else ()
119 )
120 replacement_types = {
121 record.replacement_type.__name__: record.replacement_type
122 for record in replacements
123 }
124 for patch in patch_set.forward_extracts:
125 if patch.class_name in source_classes or patch.class_name in imported_names:
126 continue
127 replacement_type = replacement_types.get(patch.class_name)
128 if replacement_type is None:
129 continue
130 patch_set.imports.append(
131 ImportPatch(replacement_type.__module__, (replacement_type.__name__,))
132 )
133 imported_names.add(patch.class_name)
136def _observed_boundary_classes(meta: Any, patch_plan: Any) -> dict[str, str]:
137 """Return boundary owners after native inner-wrapper target resolution."""
138 classes = dict(getattr(meta, "boundary_classes", None) or {})
139 wrappers = (
140 getattr(patch_plan, "inner_wrappers", ())
141 if patch_plan is not None
142 else ()
143 )
144 for record in wrappers:
145 target_type = getattr(record, "target_type", None)
146 if target_type is None:
147 continue
148 target_fqn = (
149 record.module_fqn
150 if record.target_fqn == "self"
151 else f"{record.module_fqn}.{record.target_fqn}"
152 )
153 classes[target_fqn] = target_type.__name__
154 return classes
157def _materialize_imported_forward_hosts(
158 source_text: str, patch_set: InlinePatchSet
159) -> None:
160 """Render same-name subclasses when a strategy host is an imported component."""
161 source_classes = {
162 node.name
163 for node in ast.parse(source_text).body
164 if isinstance(node, ast.ClassDef)
165 }
166 remaining = []
167 rendered: set[str] = set()
168 for patch in patch_set.forward_extracts:
169 if patch.class_name in source_classes:
170 remaining.append(patch)
171 continue
172 import_index = next(
173 (
174 index
175 for index, item in enumerate(patch_set.imports)
176 if not item.raw and patch.class_name in item.names
177 ),
178 None,
179 )
180 if import_index is None:
181 remaining.append(patch)
182 continue
183 if patch.class_name in rendered:
184 continue
185 rendered.add(patch.class_name)
186 imported = patch_set.imports[import_index]
187 other_names = tuple(name for name in imported.names if name != patch.class_name)
188 replacement_imports = [ImportPatch(imported.module, other_names)] if other_names else []
189 replacement_imports.append(ImportPatch("", (), raw=f"import {imported.module}"))
190 patch_set.imports[import_index:import_index + 1] = replacement_imports
191 base = f"{imported.module}.{patch.class_name}"
192 if patch.definition is not None:
193 definition = _imported_forward_definition(patch.definition)
194 snippet = (f"class {patch.class_name}({base}):\n"
195 + _parallel_state_prefix(definition) + textwrap.indent(definition, " ") + "\n")
196 patch_set.module_snippets.append(ModuleSnippetPatch(snippet))
197 continue
198 body, local = _imported_forward_source(patch.body)
199 state = _parallel_state_prefix(body)
200 snippet = (
201 f"class {patch.class_name}({base}):\n"
202 f"{state}"
203 f"{local}"
204 " def forward(self, *args, **kwargs):\n"
205 f"{textwrap.indent(body.strip(), ' ')}\n"
206 )
207 patch_set.module_snippets.append(ModuleSnippetPatch(snippet))
208 patch_set.forward_extracts = remaining
211def _imported_forward_definition(definition: str) -> str:
212 """Bind the saved native method outside nested callbacks before rendering its real signature."""
213 parts = []
214 for node in ast.parse(definition).body:
215 if isinstance(node, ast.FunctionDef):
216 body = "\n".join(ast.unparse(statement) for statement in node.body)
217 body, local = _imported_forward_source(body)
218 node.body = ast.parse(body).body
219 if local:
220 parts.append(textwrap.dedent(local).strip())
221 parts.append(ast.unparse(node))
222 return "\n\n".join(parts)
225def _imported_forward_source(body: str) -> tuple[str, str]:
226 """Keep a helper's original-method callback separate from its imported host dispatch."""
227 dispatch = _cp_dispatch_call(body)
228 body = body.replace("__hp_forward_args__", "*args, **kwargs").replace(
229 "__hp_forward_positional__", "args",
230 ).replace("__hp_forward_keywords__", "kwargs")
231 if dispatch is not None:
232 local = (" def _forward_impl(self, *args, **kwargs):\n"
233 " return super().forward(*args, **kwargs)\n\n")
234 return body, local
235 body = body.replace("self._forward_impl(", "original_forward(")
236 if "original_forward(" in body:
237 body = "original_forward = super().forward\n" + body
238 return body, ""
241def render_inline_strategies_for_source_unit(
242 source_text: str,
243 meta: Any,
244 model_type: str | None = None,
245 *,
246 patch_plan: Any = None,
247) -> str:
248 """Render only strategy forwards owned by one sibling source unit."""
249 rules = collect_source_observations(meta)
250 if not rules:
251 return source_text
252 recorded_local_compute = bool(
253 getattr(patch_plan, "local_computes", ())
254 if patch_plan is not None
255 else ()
256 )
257 strategy_rules = (
258 tuple(replace(rule, local_compute_target=None) for rule in rules)
259 if recorded_local_compute
260 else rules
261 )
262 _require_inline_coverage(strategy_rules, model_type)
263 source_classes = {
264 node.name
265 for node in ast.parse(source_text).body
266 if isinstance(node, ast.ClassDef)
267 }
268 boundaries = _observed_boundary_classes(meta, patch_plan)
269 owned_rules = tuple(
270 rule for rule in strategy_rules
271 if ((rule.observed_wrapper or {}).get("host_class") in source_classes
272 or rule_block_classes(rule, boundaries) & source_classes)
273 )
274 patches = build_strategy_patches(
275 owned_rules, model_type, boundaries,
276 )
277 patches.forward_extracts = [
278 patch for patch in patches.forward_extracts
279 if patch.class_name in source_classes
280 ]
281 if not patches.forward_extracts:
282 return source_text
283 patches.constructor_replaces.clear()
284 patches.class_removals.clear()
285 return apply_patch_set(source_text, patches)
288def _library_import_names(text: str) -> set[str]:
289 """Names the artifact imports from the library, i.e. the winning bindings.
291 Args:
292 text: Rendered modeling source.
294 Returns:
295 The set of names bound by its ``hyper_parallel`` imports.
296 """
298 names: set[str] = set()
299 try:
300 tree = ast.parse(text)
301 except SyntaxError:
302 return names
303 for node in ast.walk(tree):
304 if isinstance(node, ast.ImportFrom) and (node.module or "").startswith("hyper_parallel"):
305 names.update(alias.asname or alias.name for alias in node.names)
306 return names
309def _decorated_names(text: str) -> set[str]:
310 """Names of the module-level definitions the base source decorates.
312 A decorator is what makes a copied helper behave differently from the library
313 function of the same name (a per-module kernel binding, for instance), so
314 only those definitions may be dropped.
316 Args:
317 text: Base modeling source before the inline patches are applied.
319 Returns:
320 The set of decorated top-level definition names.
321 """
323 try:
324 tree = ast.parse(text)
325 except SyntaxError:
326 return set()
327 return {
328 node.name
329 for node in tree.body
330 if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef))
331 and node.decorator_list
332 }
335def _is_local_compute_factory(target: str) -> bool:
336 """Whether a local_compute target is a ``@local_compute`` factory.
338 Structural injection discipline: the decorator stamps the factory with
339 ``_injection_meta`` (kind ``LOCAL_COMPUTE``), so a decorated factory is
340 recognizable without a table. Such a target carries no inline strategy
341 body -- its region is bound at install time (the emitted region template
342 for an in-source class, the runtime local-region skeleton for an imported
343 class), which resolves the factory exactly as the native applier does.
344 """
345 from hyper_parallel.distributed.recipe_spec import LOCAL_COMPUTE # pylint: disable=C0415
347 module_name, _, attr = target.rpartition(".")
348 if not module_name or not attr:
349 return False
350 try:
351 module = importlib.import_module(module_name)
352 except ImportError:
353 return False
354 factory = getattr(module, attr, None)
355 if not callable(factory):
356 return False
357 meta = getattr(factory, "_injection_meta", None)
358 return getattr(meta, "kind", None) == LOCAL_COMPUTE
361def _require_inline_coverage(rules: tuple[Any, ...], model_type: str | None = None) -> None:
362 """Fail when a YAML rule has no structural resolution behind it.
364 Covers both rule kinds: a replacement target needs a ``ReplacementSpec``,
365 and every strategy target needs a ``StrategySpec``. One exception: a
366 ``local_compute_fn`` target that is itself a ``@local_compute`` factory
367 needs no inline strategy -- its region is runtime-bound (see
368 :func:`_is_local_compute_factory`), so the factory's injection discipline
369 is the coverage proof. Reporting all gaps at once keeps one fix cycle
370 from hiding the next gap.
371 """
373 uncovered: list[str] = []
374 for rule in rules:
375 if (
376 rule.replace_target is not None
377 and replacement_spec_for_observation(rule, model_type) is None
378 ):
379 uncovered.append(rule.replace_target)
380 for target in (rule.local_compute_target, rule.inner_wrapper_target):
381 if target is None:
382 continue
383 if target == rule.inner_wrapper_target and rule.observed_wrapper is not None:
384 continue
385 if strategy_spec(
386 target, model_type, inner_wrapper=target == rule.inner_wrapper_target,
387 construction_kwargs=rule.construction_kwargs if target == rule.inner_wrapper_target else (),
388 ) is not None:
389 continue
390 # An inner_wrapper target has no runtime channel and stays
391 # fail-closed; a local_compute target passes through the
392 # @local_compute decoration check.
393 if target == rule.local_compute_target and _is_local_compute_factory(target):
394 continue
395 uncovered.append(target)
396 if uncovered:
397 raise RuntimeError(
398 f"codegen: no inline declaration for {sorted(set(uncovered))} "
399 f"(model_type={model_type!r}); the target names no known generic "
400 "component or framework strategy, and a local_compute target "
401 "names no @local_compute factory"
402 )