Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / codegen / emit / snapshot_patches.py: 68%

157 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"""Convert native-build snapshot observations into emitter patch records.""" 

16 

17from __future__ import annotations 

18 

19import ast 

20import importlib 

21import os 

22from typing import Any, Optional 

23 

24from hyper_parallel.codegen.inline.targets import import_target_path 

25from hyper_parallel.codegen.source.resolver import resolve_remote_siblings 

26 

27 

28def emission_patches_from_snapshot_payload( 

29 payload: dict[str, Any], 

30) -> dict[str, Any]: 

31 """Translate resolved native observations into emitter patch records. 

32 

33 Args: 

34 payload: Serialized native observations and selected strategy records. 

35 """ 

36 applications = payload["replacements"]["applications"] 

37 factories = { 

38 item["rule_id"]: import_target_path(item["replacement_target"]) 

39 for item in payload["replacements"].get("declarations", ()) 

40 if item.get("replacement_target") 

41 } 

42 replacements = [ 

43 { 

44 "module_fqn": item["primary_fqn"], 

45 "source_type": item["source_type"], 

46 "replacement_type": item["replacement_type"], 

47 **({"factory": factories[item["rule_id"]]} if item.get("rule_id") in factories else {}), 

48 **({"factory": item["family_request"]["factory"], 

49 "factory_kwargs": {**item["family_request"]["kwargs"], 

50 "context": item["family_request"]["context"]}} 

51 if item.get("family_request") else {}), 

52 } 

53 for item in applications 

54 ] 

55 replacement_types = { 

56 module_fqn: item["replacement_type"] 

57 for item in applications 

58 for module_fqn in item.get("module_fqns", (item["primary_fqn"],)) 

59 } 

60 source = payload["source"] 

61 plan = payload.get("plan") or {} 

62 injections = plan.get("injections") or () 

63 boundary_classes = plan.get("boundary_classes") or {} 

64 boundary_types = plan.get("boundary_types") or {} 

65 param_plan = plan.get("param_plan") or {} 

66 local_computes, inner_wrappers = [], [] 

67 for injection in injections: 

68 local, wrapper = _injection_patches( 

69 injection, 

70 source, 

71 boundary_classes, 

72 boundary_types, 

73 replacement_types, 

74 param_plan, 

75 ) 

76 if local is not None: 

77 local_computes.append(local) 

78 if wrapper is not None: 

79 inner_wrappers.append(wrapper) 

80 return { 

81 "module_replacements": replacements, 

82 "local_computes": local_computes, 

83 "inner_wrappers": inner_wrappers, 

84 } 

85 

86 

87def _injection_patches( 

88 injection: dict[str, Any], 

89 source: dict[str, Any], 

90 boundary_classes: dict[str, Any], 

91 boundary_types: dict[str, Any], 

92 replacement_types: dict[str, str], 

93 param_plan: dict[str, Any], 

94) -> tuple[Optional[dict[str, Any]], Optional[dict[str, Any]]]: 

95 """Translate one resolved injection into source-emission patches.""" 

96 module_fqn = injection.get("match") 

97 class_name = boundary_classes.get(module_fqn) 

98 module_name = source.get("module_name") 

99 declared_type = ( 

100 f"{module_name}:{class_name}" if module_name and class_name else None 

101 ) 

102 source_type = _source_type_identity(source, class_name) 

103 observed_type = boundary_types.get(module_fqn) 

104 if source_type is None and _is_remote_boundary_type(observed_type): 

105 source_type = observed_type 

106 bound_forward = _bound_forward_identity(source, module_fqn) 

107 local = _local_compute_patch( 

108 injection, 

109 source, 

110 module_fqn, 

111 class_name, 

112 declared_type, 

113 source_type, 

114 bound_forward, 

115 param_plan, 

116 ) 

117 wrapper = _inner_wrapper_patch( 

118 injection, 

119 module_fqn, 

120 declared_type, 

121 source_type, 

122 replacement_types, 

123 ) 

124 return local, wrapper 

125 

126 

127def _is_remote_boundary_type(value: Any) -> bool: 

128 """Return whether an observed type identifies non-framework source.""" 

129 return isinstance(value, str) and not value.startswith( 

130 ("hyper_parallel.", "torch.") 

131 ) 

132 

133 

134def _local_compute_patch( 

135 injection: dict[str, Any], 

136 source: dict[str, Any], 

137 module_fqn: str, 

138 class_name: str, 

139 declared_type: Optional[str], 

140 source_type: Optional[str], 

141 bound_forward: Optional[str], 

142 param_plan: dict[str, Any], 

143) -> Optional[dict[str, Any]]: 

144 """Build one local-compute emission record.""" 

145 local_compute = injection.get("local_compute_fn") 

146 if local_compute is None: 

147 return None 

148 if declared_type is None: 

149 raise ValueError( 

150 "snapshot local_compute_fn requires a source module and " 

151 f"boundary class for {module_fqn!r}" 

152 ) 

153 if source_type is None and bound_forward is None: 

154 return None 

155 module_type = ( 

156 (_imported_type_identity(source, class_name) if bound_forward else source_type) 

157 or source_type 

158 or declared_type 

159 ) 

160 return { 

161 "module_fqn": module_fqn, 

162 "module_type": module_type, 

163 "factory": import_target_path(local_compute), 

164 "region_dispatch": (param_plan.get(module_fqn) or {}).get("region_dispatch"), 

165 "original_forward": bound_forward or f"{source_type}.forward", 

166 } 

167 

168 

169def _inner_wrapper_patch( 

170 injection: dict[str, Any], 

171 module_fqn: str, 

172 declared_type: Optional[str], 

173 source_type: Optional[str], 

174 replacement_types: dict[str, str], 

175) -> Optional[dict[str, Any]]: 

176 """Build one inner-wrapper emission record.""" 

177 wrapper = injection.get("inner_wrapper") 

178 if wrapper is None: 

179 return None 

180 target_type = ((injection.get("observed_wrapper") or {}).get("target_type") 

181 or replacement_types.get(module_fqn) or source_type or declared_type) 

182 if target_type is None: 

183 raise ValueError( 

184 "snapshot inner_wrapper requires an observed replacement or " 

185 f"boundary class for {module_fqn!r}" 

186 ) 

187 definition = (injection.get("observed_wrapper") or {}).get("definition") 

188 return { 

189 "module_fqn": module_fqn, 

190 "target_fqn": injection.get("inner_target") or "self", 

191 "wrapper": None if definition else import_target_path(wrapper), 

192 "target_type": target_type, 

193 "factory_kwargs": {name: value for name, value in wrapper.items() if name not in ("_target_", "target")} 

194 if isinstance(wrapper, dict) else {}, 

195 **({"observed_definition": definition} if definition else {}), 

196 } 

197 

198 

199def _source_class_names(source: dict[str, Any]) -> set[str]: 

200 """Return classes defined by the snapshot's modeling source file.""" 

201 file_path = source.get("file_path") 

202 if not file_path: 

203 return set() 

204 try: 

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

206 tree = ast.parse(handle.read(), filename=file_path) 

207 except (OSError, SyntaxError): 

208 return set() 

209 return {node.name for node in tree.body if isinstance(node, ast.ClassDef)} 

210 

211 

212def _source_type_identity( 

213 source: dict[str, Any], class_name: Optional[str] 

214) -> Optional[str]: 

215 """Resolve a class to the remote source unit that actually defines it.""" 

216 if not class_name: 

217 return None 

218 module_name = source.get("module_name") 

219 if not isinstance(module_name, str) or not module_name: 

220 return None 

221 if class_name in _source_class_names(source): 

222 return f"{module_name}:{class_name}" 

223 

224 package, separator, _ = module_name.rpartition(".") 

225 candidates = [] 

226 for path in resolve_remote_siblings(source).values(): 

227 sibling_source = {"file_path": path} 

228 if class_name not in _source_class_names(sibling_source): 

229 continue 

230 stem = os.path.splitext(os.path.basename(path))[0] 

231 sibling_module = f"{package}.{stem}" if separator else stem 

232 candidates.append(f"{sibling_module}:{class_name}") 

233 if len(candidates) > 1: 

234 raise ValueError( 

235 f"snapshot class {class_name!r} is defined by multiple bundled source units: " 

236 f"{sorted(candidates)}" 

237 ) 

238 return candidates[0] if candidates else None 

239 

240 

241def _bound_forward_identity( 

242 source: dict[str, Any], module_fqn: Optional[str] 

243) -> Optional[str]: 

244 """Resolve a model-owned function installed through ``MethodType``.""" 

245 file_path = source.get("file_path") 

246 module_name = source.get("module_name") 

247 if not file_path or not module_name or not module_fqn: 

248 return None 

249 try: 

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

251 tree = ast.parse(handle.read(), filename=file_path) 

252 except (OSError, SyntaxError): 

253 return None 

254 

255 boundary_name = module_fqn.rsplit(".", 1)[-1] 

256 candidates = set() 

257 for node in ast.walk(tree): 

258 candidate = _method_type_forward_name(node, boundary_name) 

259 if candidate: 

260 candidates.add(candidate) 

261 if len(candidates) > 1: 

262 raise ValueError( 

263 f"snapshot boundary {module_fqn!r} has multiple MethodType forwards: " 

264 f"{sorted(candidates)}" 

265 ) 

266 return f"{module_name}:{next(iter(candidates))}" if candidates else None 

267 

268 

269def _method_type_forward_name(node: ast.AST, boundary_name: str) -> Optional[str]: 

270 """Return the function assigned as one boundary's MethodType forward.""" 

271 if not isinstance(node, ast.Assign) or len(node.targets) != 1: 

272 return None 

273 target, call = node.targets[0], node.value 

274 valid_target = ( 

275 isinstance(target, ast.Attribute) 

276 and target.attr == "forward" 

277 and isinstance(target.value, ast.Attribute) 

278 and target.value.attr == boundary_name 

279 ) 

280 if not valid_target or not isinstance(call, ast.Call): 

281 return None 

282 if _ast_name(call.func) != "MethodType" or not call.args: 

283 return None 

284 return call.args[0].id if isinstance(call.args[0], ast.Name) else None 

285 

286 

287def _imported_type_identity( 

288 source: dict[str, Any], class_name: Optional[str] 

289) -> Optional[str]: 

290 """Resolve an imported boundary class from modules referenced by the source.""" 

291 file_path = source.get("file_path") 

292 if not file_path or not class_name: 

293 return None 

294 try: 

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

296 tree = ast.parse(handle.read(), filename=file_path) 

297 except (OSError, SyntaxError): 

298 return None 

299 

300 explicit_modules = _explicit_import_modules(tree, class_name) 

301 if len(explicit_modules) > 1: 

302 raise ValueError( 

303 f"snapshot class {class_name!r} is imported from multiple modules: " 

304 f"{sorted(explicit_modules)}" 

305 ) 

306 if explicit_modules: 

307 return f"{next(iter(explicit_modules))}:{class_name}" 

308 candidates = _exporting_import_modules(tree, class_name) 

309 if len(candidates) > 1: 

310 raise ValueError( 

311 f"snapshot class {class_name!r} is exported by multiple imported modules: " 

312 f"{candidates}" 

313 ) 

314 return candidates[0] if candidates else None 

315 

316 

317def _explicit_import_modules(tree: ast.AST, class_name: str) -> set[str]: 

318 """Return modules that explicitly import one class name.""" 

319 return { 

320 node.module 

321 for node in tree.body 

322 if isinstance(node, ast.ImportFrom) 

323 and node.level == 0 

324 and node.module 

325 and any( 

326 alias.name == class_name and (alias.asname or alias.name) == class_name 

327 for alias in node.names 

328 ) 

329 } 

330 

331 

332def _exporting_import_modules(tree: ast.AST, class_name: str) -> list[str]: 

333 """Return imported modules that export one class name.""" 

334 modules = { 

335 node.module 

336 for node in tree.body 

337 if isinstance(node, ast.ImportFrom) and node.level == 0 and node.module 

338 } 

339 candidates = [] 

340 for module_name in sorted(modules): 

341 try: 

342 module = importlib.import_module(module_name) 

343 except (ImportError, AttributeError): 

344 continue 

345 if hasattr(module, class_name): 

346 candidates.append(f"{module_name}:{class_name}") 

347 return candidates 

348 

349 

350def _ast_name(node: ast.AST) -> Optional[str]: 

351 """Return the terminal name of a callable expression.""" 

352 if isinstance(node, ast.Name): 

353 return node.id 

354 if isinstance(node, ast.Attribute): 

355 return node.attr 

356 return None 

357 

358 

359__all__ = ["emission_patches_from_snapshot_payload"]