Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / codegen / inline / observations.py: 95%
41 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 replacement and injection observations into source rules."""
17from __future__ import annotations
19import ast
20from typing import Any, Iterable
22from hyper_parallel.codegen.inline.ir import SourceObservation
23from hyper_parallel.codegen.inline.targets import projected_target_path
26def collect_source_observations(meta: Any) -> tuple[SourceObservation, ...]:
27 """Return normalized source rules from the already observed native plan.
29 Args:
30 meta: Observed native plan and replacement records.
31 """
32 rules: list[SourceObservation] = []
33 for record in getattr(meta, "module_overrides", None) or []:
34 target = _replacement_target(record)
35 if target:
36 rules.append(
37 SourceObservation(
38 match=_matches(record),
39 module_type=record.get("module_type"),
40 replace_target=target,
41 shared_fqns=tuple(record.get("fqns") or ()),
42 construction=record.get("construction"),
43 construction_kwargs=_construction_kwargs(record),
44 )
45 )
46 for record in getattr(meta, "injections", None) or []:
47 local = projected_target_path(record.get("local_compute_fn"))
48 inner = projected_target_path(record.get("inner_wrapper"))
49 if local is not None or inner is not None:
50 rules.append(
51 SourceObservation(
52 match=_matches(record),
53 inner_wrapper_target=inner,
54 local_compute_target=local,
55 observed_wrapper=record.get("observed_wrapper"),
56 construction_kwargs=_construction_kwargs({"target_config": {
57 key: value for key, value in record.get("inner_wrapper", {}).items()
58 if key not in ("_target_", "target")
59 }}) if isinstance(record.get("inner_wrapper"), dict) else (),
60 )
61 )
62 return tuple(rules)
66def _construction_kwargs(record: dict[str, Any]) -> tuple[str, ...]:
67 """Preserve static arguments; reject values that cannot round-trip as literals."""
68 arguments = []
69 for name, value in sorted((record.get("target_config") or {}).items()):
70 text = repr(value)
71 if not name.isidentifier() or ast.literal_eval(text) != value:
72 raise ValueError(f"codegen cannot preserve construction argument {name!r}")
73 arguments.append(f"{name}={text}")
74 return tuple(arguments)
77def _replacement_target(record: dict[str, Any]) -> Any:
78 """Prefer model-owned declarations and otherwise use the observed factory."""
79 declared = record.get("replacement_target")
80 parts = str(declared or "").split(".")
81 if len(parts) >= 4 and parts[:2] == ["hyper_parallel", "models"] and parts[3] == "adapter":
82 return declared
83 return record.get("factory")
86def _matches(record: dict[str, Any]) -> tuple[str, ...]:
87 """Normalize one observation's selected FQNs."""
88 value = record.get("fqns") or record.get("match") or record.get("fqn")
89 if value is None:
90 return ()
91 if isinstance(value, str):
92 return (value,)
93 if isinstance(value, Iterable):
94 return tuple(str(item) for item in value)
95 return (str(value),)
98__all__ = ["collect_source_observations"]