Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / codegen / inline / replacement_pass.py: 92%

48 statements  

« 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"""First inline pass: sink YAML module replacements into source constructors.""" 

16 

17from __future__ import annotations 

18 

19import logging 

20from collections import defaultdict 

21from typing import Any 

22 

23from hyper_parallel.codegen.inline.ir import ( 

24 ClassRemovalPatch, 

25 ConstructorReplacePatch, 

26 InlinePatchSet, 

27 SourceObservation, 

28 ModuleSnippetPatch, 

29) 

30from hyper_parallel.codegen.inline.framework_spec import ( 

31 replacement_spec_for_observation, 

32) 

33 

34logger = logging.getLogger(__name__) 

35 

36 

37def build_replacement_patches( 

38 rules: tuple[SourceObservation, ...], model_type: str | None = None 

39) -> InlinePatchSet: 

40 """Build constructor replacement patches from module actions. 

41 

42 The rule's settled FQNs (``rule.match``, recorded from the same plan the 

43 native path applies) define the *scope* of each rewrite: only the 

44 ``self.<attr>`` call sites those FQNs name are sunk. A rule that matched no 

45 module is not expanded at all -- generating a replacement the plan never 

46 decided would make the artifact diverge from the trained model. 

47 

48 The plan records one entry per matched FQN, so the entries sharing a 

49 module implementation must be merged: taking only the first would scope 

50 the rewrite to a single matched attribute (``input_layernorm``) and silently 

51 leave its siblings (``post_attention_layernorm``, ``model.norm``) on the 

52 original class. 

53 

54 Args: 

55 rules: Inline rules recovered from the plan's frozen metadata. 

56 model_type: Model family key used to resolve framework declarations. 

57 

58 Returns: 

59 The constructor replacement patches for the matched rules. 

60 """ 

61 

62 patch_set = InlinePatchSet() 

63 scopes_by_target: dict[tuple, set[str]] = defaultdict(set) 

64 fqns_by_target: dict[tuple, set[str]] = defaultdict(set) 

65 specs_by_target: dict[tuple, Any] = {} 

66 source_fqns_by_target: dict[tuple, set[str]] = defaultdict(set) 

67 shared_by_target: dict[tuple, list[tuple[str, ...]]] = defaultdict(list) 

68 for rule in rules: 

69 target = rule.replace_target 

70 if target is None: 

71 continue 

72 spec = replacement_spec_for_observation(rule, model_type) 

73 if spec is None: 

74 continue 

75 key = (target, rule.module_type, spec.keyword_args) 

76 specs_by_target.setdefault(key, spec) 

77 if rule.construction is not None: 

78 source_fqns_by_target[key].update(rule.construction["source_fqns"]) 

79 if len(rule.shared_fqns) > 1: 

80 shared_by_target[key].append(rule.shared_fqns) 

81 scopes_by_target[key].update(_scope_attrs(rule)) 

82 fqns_by_target[key].update(fqn for fqn in rule.match if fqn) 

83 for target, spec in specs_by_target.items(): 

84 scope_attrs = tuple(sorted(scopes_by_target[target])) 

85 if not scope_attrs: 

86 logger.warning( 

87 "codegen: module replacement %r matched no module and is not expanded", 

88 target, 

89 ) 

90 continue 

91 patch_set.imports.extend(spec.imports) 

92 if spec.replacement_note: 

93 patch_set.module_snippets.append( 

94 ModuleSnippetPatch(f"# Codegen replacement: {spec.replacement_note}") 

95 ) 

96 patch_set.module_snippets.extend(spec.snippets) 

97 deferred = _requires_deferred_scope(spec, source_fqns_by_target[target], 

98 scope_attrs, fqns_by_target[target], shared_by_target[target]) 

99 patch_set.constructor_replaces.append( 

100 ConstructorReplacePatch( 

101 old_ctor=spec.old_ctor, 

102 new_ctor=spec.new_ctor, 

103 mode="wrap_source" if deferred else spec.mode, # type: ignore[arg-type] 

104 keyword_args=spec.keyword_args, 

105 scope_attrs=scope_attrs, 

106 scope_fqns=tuple(sorted(fqns_by_target[target])), 

107 defer_to_fqns=deferred, 

108 scope_complete=bool(source_fqns_by_target[target]) and not deferred, 

109 shared_fqns=tuple(shared_by_target[target]), 

110 ) 

111 ) 

112 if spec.remove_class: 

113 patch_set.class_removals.append( 

114 ClassRemovalPatch(old_name=spec.old_ctor, new_name=spec.new_ctor) 

115 ) 

116 return patch_set 

117 

118 

119def _scope_attrs(rule: SourceObservation) -> tuple[str, ...]: 

120 """Attribute names of the rule's settled FQNs, i.e. the rewrite scope. 

121 

122 ``model.layers.3.post_attention_layernorm`` scopes the rewrite to 

123 ``self.post_attention_layernorm = <ctor>(...)`` assignments, which is the 

124 granularity native's FQN matching produces. ``model.norm`` is a sole-name 

125 FQN, so the whole FQN is the attribute. 

126 """ 

127 

128 return tuple(sorted({fqn.rsplit(".", 1)[-1] for fqn in rule.match if fqn})) 

129 

130 

131def _requires_deferred_scope(spec: Any, source_fqns: set[str], attrs: tuple[str, ...], 

132 matches: set[str], shared: list[tuple[str, ...]]) -> bool: 

133 """Do not widen a partial or shared instance replacement into a class rewrite.""" 

134 available = {fqn for fqn in source_fqns if fqn.rsplit(".", 1)[-1] in attrs} 

135 return spec.defer_to_fqns or bool(shared) or bool(source_fqns) and available != matches