Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / codegen / inline / strategy_pass.py: 91%
47 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"""Second inline pass: insert parallel strategies into replaced modules."""
17from __future__ import annotations
19from fnmatch import fnmatch
20from typing import Mapping
22from hyper_parallel.codegen.inline.ir import (
23 ForwardExtractPatch,
24 ImportPatch,
25 InlinePatchSet,
26 ModuleSnippetPatch,
27 SourceObservation,
28 StrategySpec,
29)
30from hyper_parallel.codegen.inline.framework_spec import CP_ATTENTION_KIND, strategy_spec_for as strategy_spec
33def rule_block_classes(
34 rule: SourceObservation, boundary_classes: Mapping[str, str] | None
35) -> set[str]:
36 """The concrete classes a rule's match patterns select in the boundary map.
38 Per-model fact, derived (never registered): the frozen boundary map names
39 each matched FQN's class, so any custom model class picked up by the
40 pattern materializes without a framework-side registration.
41 """
42 classes: set[str] = set()
43 for fqn, class_name in (boundary_classes or {}).items():
44 if any(fnmatch(fqn, pattern) for pattern in rule.match):
45 classes.add(class_name)
46 return classes
49def build_strategy_patches(
50 rules: tuple[SourceObservation, ...],
51 model_type: str | None = None,
52 boundary_classes: Mapping[str, str] | None = None,
53) -> InlinePatchSet:
54 """Materialize selected inner-wrapper forwards, deduplicating shared source bindings.
56 Host classes come from each rule's observed FQNs. Local-compute methods
57 are materialized separately from native records by ``emit.recorded``.
58 """
59 patch_set = InlinePatchSet()
60 imported: set[str] = set()
61 subclassed: dict[str, tuple[str, tuple[str, ...]]] = {}
62 for rule in rules:
63 target = rule.inner_wrapper_target
64 if target is None:
65 continue
66 spec = _rule_strategy(rule, target, model_type)
67 if spec is None:
68 continue
69 patch_set.imports.extend(spec.imports)
70 if target not in imported:
71 imported.add(target)
72 patch_set.module_snippets.extend(spec.snippets)
73 if spec.subclass_shell is not None:
74 _materialize_cp_forward(
75 patch_set, spec, rule, target, model_type,
76 boundary_classes, subclassed,
77 )
78 return patch_set
81def _materialize_cp_forward(
82 patch_set: InlinePatchSet,
83 spec: StrategySpec,
84 rule: SourceObservation,
85 target: str,
86 model_type: str | None,
87 boundary_classes: Mapping[str, str] | None,
88 subclassed: dict[str, tuple[str, tuple[str, ...]]],
89) -> None:
90 """Materialize CP dispatch in the original host class exactly once."""
91 host_classes = ({rule.observed_wrapper["host_class"]} if rule.observed_wrapper is not None
92 else rule_block_classes(rule, boundary_classes))
93 if not host_classes:
94 raise _unmaterialized_strategy_error(spec.kind, target, rule, model_type)
95 for host_class in sorted(host_classes):
96 definition = (spec.definition or spec.subclass_shell, spec.initializers)
97 if host_class in subclassed:
98 if subclassed[host_class] != definition:
99 raise RuntimeError(f"codegen: conflicting CP bindings for source class {host_class!r}")
100 continue
101 subclassed[host_class] = definition
102 patch_set.forward_extracts.append(
103 ForwardExtractPatch(
104 class_name=host_class,
105 method_name=spec.method_name,
106 body=spec.subclass_shell,
107 definition=spec.definition,
108 initializers=spec.initializers,
109 )
110 )
113def _unmaterialized_strategy_error(
114 kind: str, target: str, rule: SourceObservation, model_type: str | None
115) -> RuntimeError:
116 """The error for a declared strategy that selects no boundary module."""
117 return RuntimeError(
118 f"codegen: {kind} strategy {target!r} matched no boundary "
119 f"module (patterns {list(rule.match)}, model_type="
120 f"{model_type!r}) — the declared strategy cannot be "
121 "materialized; check the match pattern or the plan's "
122 "boundary coverage"
123 )
126def _rule_strategy(
127 rule: SourceObservation, target: str, model_type: str | None,
128) -> StrategySpec | None:
129 """Use an already-installed factory-tail method or the declared wrapper source."""
130 if rule.observed_wrapper is not None:
131 return StrategySpec(
132 kind=CP_ATTENTION_KIND, subclass_shell=rule.observed_wrapper["body"],
133 definition=rule.observed_wrapper.get("definition"),
134 initializers=tuple(rule.observed_wrapper.get("initializers", ())),
135 imports=tuple(ImportPatch(module, (name,)) for module, name in rule.observed_wrapper["imports"]),
136 snippets=tuple(ModuleSnippetPatch(source) for source in rule.observed_wrapper.get("bindings", ())),
137 )
138 return strategy_spec(target, model_type, inner_wrapper=True, construction_kwargs=rule.construction_kwargs)