Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / codegen / plan / observation.py: 96%
128 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"""Observe only native-plan facts required for source emission."""
17from __future__ import annotations
19import ast
20from dataclasses import dataclass, field, fields
21from functools import lru_cache
22import inspect
23import textwrap
24from typing import Any
26from hyper_parallel.codegen.inline.component_source import observe_wrapper_source
27from hyper_parallel.codegen.inline.recognition import _function_source_qualname
28from hyper_parallel.codegen.plan.placements import (
29 named_placement_to_dict,
30 value_to_data,
31)
34@dataclass
35class EmissionPlanObservation:
36 """Plain-data projection consumed by Codegen emitters."""
38 param_plan: dict[str, dict[str, Any]] = field(default_factory=dict)
39 injections: list[dict[str, Any]] = field(default_factory=list)
40 boundary_classes: dict[str, str] = field(default_factory=dict)
41 boundary_types: dict[str, str] = field(default_factory=dict)
42 nested_components: list[dict[str, str]] = field(default_factory=list)
43 mesh_dim_names: tuple[str, ...] = ()
45 def to_dict(self) -> dict[str, Any]:
46 """Return the mutable mapping consumed by the session boundary."""
47 return {item.name: getattr(self, item.name) for item in fields(self)}
50def observe_emission_plan(plan: Any, model: Any) -> EmissionPlanObservation:
51 """Project native plan facts without executing wrapper factories or distributed operations."""
52 if plan is None:
53 return EmissionPlanObservation()
54 return EmissionPlanObservation(
55 param_plan=_observe_boundary_plan(plan),
56 injections=_observe_injections(plan),
57 boundary_classes=_observe_boundary_classes(plan, model),
58 boundary_types=_observe_boundary_types(plan, model),
59 nested_components=_observe_nested_components(plan, model),
60 mesh_dim_names=tuple(getattr(plan, "mesh_dim_names", ()) or ()),
61 )
64def _observe_boundary_plan(plan: Any) -> dict[str, dict[str, Any]]:
65 """Collect boundary layout contracts required for source emission."""
66 result: dict[str, dict[str, Any]] = {}
67 for fqn, spec in (getattr(plan, "modules", {}) or {}).items():
68 entry: dict[str, Any] = {}
69 for name in ("in_src", "in_dst", "out_src", "out_dst"):
70 value = getattr(spec, name, None)
71 if value is not None:
72 entry[name] = named_placement_to_dict(value)
73 for name in ("out_names", "_deferred_bias_params"):
74 value = getattr(spec, name, None)
75 if value:
76 key = "deferred_bias_params" if name.startswith("_") else name
77 entry[key] = list(value)
78 for name in ("is_boundary", "region_dispatch"):
79 value = getattr(spec, name, None)
80 if value is not None:
81 entry[name] = value
82 result[fqn] = entry
83 return result
86def _observe_injections(plan: Any) -> list[dict[str, Any]]:
87 """Collect compute and wrapper injections in stable module-path order."""
88 result = []
89 for fqn, spec in sorted((getattr(plan, "modules", {}) or {}).items()):
90 entry: dict[str, Any] = {}
91 for name in ("inner_wrapper", "inner_out_src", "local_compute_fn"):
92 value = getattr(spec, name, None)
93 if value is not None:
94 entry[name] = value_to_data(value)
95 inner_target = getattr(spec, "inner_target", None)
96 if inner_target is not None:
97 entry["inner_target"] = inner_target
98 if entry:
99 result.append({"match": fqn, **entry})
100 return result
103def _observe_boundary_classes(plan: Any, model: Any) -> dict[str, str]:
104 """Map planned module paths to their source class names."""
105 if model is None:
106 return {}
107 return {
108 fqn: type(model.get_submodule(fqn)).__name__
109 for fqn in (getattr(plan, "modules", {}) or {})
110 }
113def _observe_boundary_types(plan: Any, model: Any) -> dict[str, str]:
114 """Map planned module paths to fully qualified runtime type identities."""
115 if model is None:
116 return {}
117 result = {}
118 for fqn in (getattr(plan, "modules", {}) or {}):
119 module_type = type(model.get_submodule(fqn))
120 result[fqn] = f"{module_type.__module__}:{module_type.__qualname__}"
121 return result
124def _observe_nested_components(plan: Any, model: Any) -> list[dict[str, str]]:
125 """Identify nested model source owners needed for source composition."""
126 if model is None:
127 return []
128 root_module = type(model).__module__
129 components: dict[tuple[str, str], dict[str, str]] = {}
130 for boundary_fqn in (getattr(plan, "modules", {}) or {}):
131 parts = boundary_fqn.split(".")
132 for index in range(1, len(parts) + 1):
133 ancestor_fqn = ".".join(parts[:index])
134 ancestor_type = type(model.get_submodule(ancestor_fqn))
135 parent = model if index == 1 else model.get_submodule(".".join(parts[:index - 1]))
136 if (ancestor_type.__module__ == root_module
137 and parts[index - 1] in _auto_model_attributes(type(parent))):
138 identity = f"{root_module}:{ancestor_type.__qualname__}"
139 components[(ancestor_fqn, identity)] = {
140 "fqn": ancestor_fqn, "type": identity, "owner_module": root_module,
141 }
142 owner_module = type(model.get_submodule(boundary_fqn)).__module__
143 if (
144 owner_module == root_module
145 or owner_module.startswith("torch.")
146 or owner_module.startswith("hyper_parallel.")
147 ):
148 continue
149 candidates = []
150 for index in range(1, len(parts) + 1):
151 ancestor_fqn = ".".join(parts[:index])
152 ancestor_type = type(model.get_submodule(ancestor_fqn))
153 if ancestor_type.__module__ == owner_module:
154 candidates.append((ancestor_fqn, ancestor_type))
155 if not candidates:
156 continue
157 component_fqn, component_type = candidates[0]
158 identity = f"{component_type.__module__}:{component_type.__qualname__}"
159 components[(component_fqn, identity)] = {
160 "fqn": component_fqn,
161 "type": identity,
162 "owner_module": owner_module,
163 }
164 return [components[key] for key in sorted(components)]
167@lru_cache(maxsize=None)
168def _auto_model_attributes(parent_type: type) -> frozenset[str]:
169 """Read concrete child slots constructed through the native AutoModel registry."""
170 try:
171 tree = ast.parse(textwrap.dedent(inspect.getsource(parent_type.__init__)))
172 except (OSError, TypeError):
173 return frozenset()
174 result = set()
175 for node in ast.walk(tree):
176 if not isinstance(node, ast.Assign) or len(node.targets) != 1 or not isinstance(node.value, ast.Call):
177 continue
178 target, factory = node.targets[0], node.value.func
179 if (isinstance(target, ast.Attribute) and isinstance(target.value, ast.Name) and target.value.id == "self"
180 and isinstance(factory, ast.Attribute) and factory.attr == "from_config"
181 and isinstance(factory.value, ast.Name) and factory.value.id == "AutoModel"):
182 result.add(target.attr)
183 return frozenset(result)
186__all__ = ["EmissionPlanObservation", "observe_emission_plan"]
189def observe_final_forwards(model: Any, originals: dict[str, Any]) -> list[dict[str, Any]]:
190 """Read only methods changed after inner construction; never replay their factories."""
191 additions = []
192 for fqn, original in originals.items():
193 target = model.get_submodule(fqn)
194 forward = target.forward
195 if getattr(forward, "__func__", forward) is getattr(original, "__func__", original):
196 continue
197 if getattr(original, "__self__", None) is not target:
198 raise RuntimeError(f"codegen outer factory replaced observed module {fqn!r}")
199 source = observe_wrapper_source(target, forward, vars(target), original_forward=original)
200 source.update(host_class=type(target).__name__,
201 target_type=f"{type(target).__module__}:{type(target).__qualname__}")
202 function = getattr(forward, "__func__", forward)
203 qualname = _function_source_qualname(function)
204 additions.append({"match": fqn, "inner_target": "self", "observed_wrapper": source,
205 "inner_wrapper": f"{function.__globals__['__name__']}.{qualname}"})
206 return additions