Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / codegen / inline / ir.py: 97%
77 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"""Intermediate representation for inline generated-model patches."""
17from __future__ import annotations
19from dataclasses import dataclass, field
20from typing import Literal, Optional
23@dataclass(frozen=True)
24class SourceObservation:
25 """One normalized replacement or injection observed during native build."""
27 match: tuple[str, ...]
28 module_type: Optional[str] = None
29 replace_target: Optional[str] = None
30 construction_kwargs: tuple[str, ...] = ()
31 inner_wrapper_target: Optional[str] = None
32 local_compute_target: Optional[str] = None
33 observed_wrapper: dict | None = None
34 shared_fqns: tuple[str, ...] = ()
35 construction: dict | None = None
38@dataclass(frozen=True)
39class ImportPatch:
40 """A ``from module import names`` insertion."""
42 module: str
43 names: tuple[str, ...]
44 raw: str | None = None
47@dataclass(frozen=True)
48class ModuleSnippetPatch:
49 """A top-level source snippet inserted after imports."""
51 text: str
54@dataclass(frozen=True)
55class ConstructorReplacePatch:
56 """Replace constructor calls in source text.
58 ``scope_attrs`` carries the attribute names of the rule's *matched* FQNs
59 (``{"input_layernorm", "post_attention_layernorm", "norm"}`` for the
60 RMSNorm rule). Native replaces module instances by FQN, so a whole-file
61 class-name rewrite would silently replace call sites the rule never
62 matched -- for example the Q/K norm inside the attention class that the
63 recipe deliberately leaves as the original implementation. An empty scope
64 means the caller imposes no restriction; the YAML-driven pass never emits
65 an unscoped patch.
66 """
68 old_ctor: str
69 new_ctor: str
70 mode: Literal["name", "wrap_source", "construct", "config"] = "name"
71 keyword_args: tuple[str, ...] = ()
72 scope_attrs: tuple[str, ...] = ()
73 scope_fqns: tuple[str, ...] = ()
74 defer_to_fqns: bool = False
75 shared_fqns: tuple[tuple[str, ...], ...] = ()
76 scope_complete: bool = False
79@dataclass(frozen=True)
80class ForwardExtractPatch:
81 """Keep the original method as ``_forward_impl`` and replace its body."""
83 class_name: str
84 method_name: str
85 body: str
86 definition: str | None = None
87 initializers: tuple[str, ...] = ()
90@dataclass(frozen=True)
91class ClassRemovalPatch:
92 """Remove an unused original HF class definition and rewrite its references.
94 ``old_name`` is the class being removed; ``new_name`` is the fused
95 replacement that any surviving bare reference (e.g. inside
96 ``_can_record_outputs`` or ``isinstance`` checks) should be rewritten to.
97 Constructor calls are handled separately by ``ConstructorReplacePatch``.
98 """
100 old_name: str
101 new_name: str
104@dataclass
105class InlinePatchSet:
106 """All edits emitted by one inline pass."""
108 imports: list[ImportPatch] = field(default_factory=list)
109 module_snippets: list[ModuleSnippetPatch] = field(default_factory=list)
110 constructor_replaces: list[ConstructorReplacePatch] = field(default_factory=list)
111 forward_extracts: list[ForwardExtractPatch] = field(default_factory=list)
112 class_removals: list[ClassRemovalPatch] = field(default_factory=list)
115@dataclass(frozen=True)
116class ReplacementSpec:
117 """Source-level form of one module replacement implementation."""
119 old_ctor: str
120 new_ctor: str
121 imports: tuple[ImportPatch, ...]
122 mode: str = "name"
123 keyword_args: tuple[str, ...] = ()
124 snippets: tuple[ModuleSnippetPatch, ...] = ()
125 remove_class: bool = True
126 replacement_note: str | None = None
127 defer_to_fqns: bool = False
130@dataclass(frozen=True)
131class StrategySpec:
132 """Source-level form of one parallel strategy target."""
134 kind: str
135 imports: tuple[ImportPatch, ...]
136 method_name: str = "forward"
137 subclass_shell: str | None = None
138 definition: str | None = None
139 snippets: tuple[ModuleSnippetPatch, ...] = ()
140 initializers: tuple[str, ...] = ()
142 def __post_init__(self) -> None:
143 """Require a complete method patch or an imports-only declaration."""
144 if not self.method_name.isidentifier():
145 raise ValueError("Inline strategy method_name must be a Python identifier")
146 if self.subclass_shell is not None:
147 if not self.subclass_shell.strip():
148 raise ValueError("Inline strategy subclass shell must be nonempty")