Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / codegen / source / composition.py: 91%

109 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"""Compose nested AutoModel sources into one generated modeling unit.""" 

16 

17from __future__ import annotations 

18 

19import ast 

20import importlib.util 

21import keyword 

22import os 

23import re 

24from typing import Any 

25 

26 

27def compose_nested_model_sources(source_text: str, meta: Any) -> str: 

28 """Inline source modules that own boundaries below a nested model root. 

29 

30 The native model remains unchanged. This is an artifact-only composition: 

31 it replaces a nested ``AutoModel.from_config`` construction with the 

32 observed concrete class and appends that class's original source module to 

33 the same generated file before normal TP/EP lowering runs. 

34 

35 Args: 

36 source_text: Primary model source. 

37 meta: Frozen codegen metadata carrying observed nested components. 

38 

39 Returns: 

40 One source string containing the primary and nested model definitions. 

41 """ 

42 components = getattr(meta, "nested_components", None) or () 

43 if not components: 

44 return source_text 

45 rendered = source_text 

46 source = getattr(meta, "source", None) 

47 module_name = source.get("module_name") if isinstance(source, dict) else getattr(source, "module_name", None) 

48 included_modules: set[str] = {module_name} if module_name else set() 

49 for component in components: 

50 identity = component.get("type") 

51 if not isinstance(identity, str) or ":" not in identity: 

52 raise ValueError(f"invalid nested component identity: {identity!r}") 

53 module_name, class_name = identity.split(":", 1) 

54 class_name = class_name.rsplit(".", 1)[-1] 

55 replaced = _replace_auto_model_construction( 

56 rendered, 

57 component_fqn=str(component.get("fqn") or ""), 

58 class_name=class_name, 

59 ) 

60 if replaced is None: 

61 continue 

62 rendered = replaced 

63 if module_name not in included_modules: 

64 nested_source = _read_module_source(module_name) 

65 rendered = _append_source_module(rendered, nested_source, module_name) 

66 included_modules.add(module_name) 

67 return rendered 

68 

69 

70def _read_module_source(module_name: str) -> str: 

71 """Read an installed module without importing its runtime dependencies.""" 

72 spec = importlib.util.find_spec(module_name) 

73 path = None if spec is None else spec.origin 

74 if not path or not os.path.isfile(path): 

75 raise FileNotFoundError( 

76 f"codegen: nested model source {module_name!r} is not readable" 

77 ) 

78 with open(path, "r", encoding="utf-8", errors="replace") as handle: 

79 return handle.read() 

80 

81 

82def _append_source_module(primary: str, nested: str, module_name: str) -> str: 

83 """Append one nested module after removing module-only syntax.""" 

84 tree = ast.parse(nested, filename=module_name) 

85 package = module_name.rpartition(".")[0] 

86 tree = _AbsoluteImports(package).visit(tree) 

87 ast.fix_missing_locations(tree) 

88 primary_tree = ast.parse(primary) 

89 primary_bindings = _top_level_definitions(primary_tree) 

90 nested_bindings = _top_level_definitions(tree) 

91 collisions = { 

92 name for name in primary_bindings.keys() & nested_bindings.keys() 

93 if not isinstance(nested_bindings[name], ast.ClassDef) 

94 } 

95 if collisions: 

96 replacements = {name: f"_hp_nested_{name}" for name in collisions} 

97 for node in tree.body: 

98 if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): 

99 node.name = replacements.get(node.name, node.name) 

100 tree = _RenameBindings(replacements).visit(tree) 

101 ast.fix_missing_locations(tree) 

102 nodes = [ 

103 node for node in tree.body 

104 if not isinstance(node, ast.Expr) or not _is_docstring(node) 

105 ] 

106 nodes = [ 

107 node for node in nodes 

108 if not isinstance(node, ast.ImportFrom) or node.module != "__future__" 

109 ] 

110 body = "\n\n".join(ast.unparse(node) for node in nodes) 

111 marker = ( 

112 "# [HYPER NESTED MODEL] source merged from " 

113 f"{module_name}; TP/EP lowering below targets these concrete classes." 

114 ) 

115 return f"{primary.rstrip()}\n\n\n{marker}\n{body}\n" 

116 

117 

118def _top_level_definitions(tree: ast.Module) -> dict[str, ast.AST]: 

119 """Return named functions, classes, and simple assignments.""" 

120 result: dict[str, ast.AST] = {} 

121 for node in tree.body: 

122 if isinstance(node, (ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)): 

123 result[node.name] = node 

124 elif isinstance(node, (ast.Assign, ast.AnnAssign)): 

125 targets = node.targets if isinstance(node, ast.Assign) else (node.target,) 

126 for target in targets: 

127 if isinstance(target, ast.Name): 

128 result[target.id] = node 

129 return result 

130 

131 

132def _is_docstring(node: ast.Expr) -> bool: 

133 return isinstance(node.value, ast.Constant) and isinstance(node.value.value, str) 

134 

135 

136class _RenameBindings(ast.NodeTransformer): 

137 """Rename colliding nested-module globals and their references.""" 

138 

139 def __init__(self, names: dict[str, str]) -> None: 

140 """Create a renamer for the supplied module-global bindings.""" 

141 self._names = names 

142 

143 def visit_Name(self, node: ast.Name) -> ast.AST: # pylint: disable=invalid-name 

144 """Rename a matching load or store while preserving its AST context.""" 

145 replacement = self._names.get(node.id) 

146 if replacement is None: 

147 return node 

148 return ast.copy_location(ast.Name(id=replacement, ctx=node.ctx), node) 

149 

150 

151class _AbsoluteImports(ast.NodeTransformer): 

152 """Anchor nested-module relative imports on their original package.""" 

153 

154 def __init__(self, package: str) -> None: 

155 """Create a transformer for one installed source package.""" 

156 self._package = package 

157 

158 def visit_ImportFrom( # pylint: disable=invalid-name 

159 self, 

160 node: ast.ImportFrom, 

161 ) -> ast.AST | list[ast.AST]: 

162 """Convert one relative import into its installed absolute module.""" 

163 if node.level == 0: 

164 return node 

165 relative = "." * node.level + (node.module or "") 

166 module = importlib.util.resolve_name(relative, self._package) 

167 if not all(part.isidentifier() and not keyword.iskeyword(part) for part in module.split(".")): 

168 return self._dynamic_imports(node, module) 

169 return ast.copy_location( 

170 ast.ImportFrom(module=module, names=node.names, level=0), 

171 node, 

172 ) 

173 

174 @staticmethod 

175 def _dynamic_imports(node: ast.ImportFrom, module: str) -> list[ast.AST]: 

176 """Render imports whose dynamic package contains non-Python identifiers.""" 

177 assignments = [] 

178 for alias in node.names: 

179 if alias.name == "*": 

180 raise ValueError( 

181 f"codegen cannot compose a wildcard import from dynamic module {module!r}" 

182 ) 

183 imported = ast.Call( 

184 func=ast.Name(id="__import__", ctx=ast.Load()), 

185 args=[ast.Constant(module)], 

186 keywords=[ast.keyword(arg="fromlist", value=ast.List( 

187 elts=[ast.Constant(alias.name)], 

188 ctx=ast.Load(), 

189 ))], 

190 ) 

191 assignment = ast.Assign( 

192 targets=[ast.Name(id=alias.asname or alias.name, ctx=ast.Store())], 

193 value=ast.Attribute(value=imported, attr=alias.name, ctx=ast.Load()), 

194 ) 

195 assignments.append(ast.copy_location(assignment, node)) 

196 return assignments 

197 

198 

199def _replace_auto_model_construction( 

200 source_text: str, 

201 *, 

202 component_fqn: str, 

203 class_name: str, 

204) -> str | None: 

205 """Replace an observed AutoModel construction, or reject the candidate.""" 

206 attribute = component_fqn.rsplit(".", 1)[-1] 

207 if not attribute: 

208 raise ValueError("nested component FQN must not be empty") 

209 pattern = re.compile( 

210 rf"(?m)^(?P<indent>\s*)self\.{re.escape(attribute)}\s*=\s*" 

211 r"AutoModel\.from_config\((?P<config>[^\n]+)\)\s*$" 

212 ) 

213 replacement = rf"\g<indent>self.{attribute} = {class_name}(\g<config>)" 

214 rendered, count = pattern.subn(replacement, source_text, count=1) 

215 return rendered if count == 1 else None 

216 

217 

218__all__ = ["compose_nested_model_sources"]