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

193 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"""Locate modeling source from native model configuration and recorded identity. 

16 

17Resolved HF configuration determines installed versus trusted remote code; 

18source identity also supports local repository models. These helpers locate 

19readable files without loading another AutoConfig or starting a model build. 

20Remote-code siblings are copied by the bundle emitter for source inspection. 

21""" 

22from __future__ import annotations 

23 

24import importlib.util 

25import logging 

26import os 

27import re 

28from dataclasses import dataclass 

29from typing import Any, Optional 

30 

31logger = logging.getLogger(__name__) 

32 

33 

34@dataclass 

35class ResolvedSource: 

36 """A located modeling source file, ready to be copied into a bundle.""" 

37 

38 module_name: str 

39 file_path: str 

40 architecture: Optional[str] = None 

41 model_type: Optional[str] = None 

42 

43 def to_dict(self) -> dict[str, Any]: 

44 """JSON-friendly form for ``CodegenMeta.source``.""" 

45 return { 

46 "module_name": self.module_name, 

47 "file_path": self.file_path, 

48 "architecture": self.architecture, 

49 "model_type": self.model_type, 

50 } 

51 

52 

53def resolve_hf_source(config: Any, hf_config: Any) -> ResolvedSource: 

54 """Resolve the modeling source for a resolved HF config. 

55 

56 Priority mirrors what the hyper trainer actually loads, which is plain 

57 transformers ``from_pretrained`` semantics (see auto_model._init_model -> 

58 _from_pretrained_parent_class, with ``trust_remote_code`` forwarded from the 

59 YAML ``model:`` block). The deciding input is ``trust_remote_code``, NOT 

60 the mere presence of ``auto_map``: 

61 

62 1. ``trust_remote_code`` AND the checkpoint ships remote code (``auto_map``) 

63 -> remote code wins, even when an installed module also exists (this is 

64 what HF loads). Must resolve to a file, else raise. 

65 2. Otherwise an installed transformers module for ``model_type`` -> use it 

66 (this is what HF loads when remote code is not trusted). 

67 3. Otherwise remote code, if any (a checkpoint whose model_type has no 

68 installed module; HF would require trust_remote_code to load it, so we 

69 only reach here to still produce a source for generation). 

70 """ 

71 arch = _first_architecture(hf_config) 

72 model_type = getattr(hf_config, "model_type", None) 

73 has_remote_code = bool(getattr(hf_config, "auto_map", None)) 

74 trust_remote_code = _trust_remote_code(config) 

75 model_path = _model_path_of(config) 

76 

77 module_name = _module_for_model_type(model_type) 

78 installed_path = import_module_file(module_name) if module_name else None 

79 

80 # 1. Trusted remote code is authoritative — HF loads the checkpoint's own 

81 # modeling file over any installed module. 

82 if has_remote_code and trust_remote_code: 

83 remote_path = resolve_remote_code_file(model_path, hf_config) 

84 if remote_path is not None: 

85 logger.debug("source: resolved to trusted remote code %s", remote_path) 

86 return _build_resolved_source(remote_path, "<remote>", arch, model_type) 

87 raise FileNotFoundError( 

88 f"codegen: trust_remote_code is set and the config for " 

89 f"{model_path or model_type!r} declares auto_map " 

90 f"({list(getattr(hf_config, 'auto_map', {}) or {})}), but no " 

91 "modeling_*.py was found in the checkpoint dir or the loaded " 

92 "config's module — remote code is the source HF would load" 

93 ) 

94 

95 # 2. Custom-registered model — what HyperParallel loads for a registered 

96 # architecture. The registry entry is 

97 # authoritative over an installed transformers module of the same 

98 # model_type: model resolution prefers the registered class. 

99 custom_module = _custom_registered_module(hf_config) 

100 if custom_module is not None: 

101 custom_path = import_module_file(custom_module) 

102 if custom_path is None: 

103 raise FileNotFoundError( 

104 f"codegen: architecture {arch!r} is registered to module " 

105 f"{custom_module!r} but its file could not be located" 

106 ) 

107 logger.debug( 

108 "source: resolved architecture=%r to registered module %s", 

109 arch, custom_path, 

110 ) 

111 return _build_resolved_source(custom_path, custom_module, arch, model_type) 

112 

113 # 3. Installed transformers module — what HF loads when remote code is not 

114 # trusted (or not present). 

115 if installed_path is not None: 

116 logger.debug( 

117 "source: resolved model_type=%r to installed module %s", 

118 model_type, installed_path, 

119 ) 

120 return _build_resolved_source(installed_path, module_name, arch, model_type) 

121 

122 # 4. Remote code without an installed module (HF would need 

123 # trust_remote_code, but we can still locate the file for generation). 

124 if has_remote_code: 

125 remote_path = resolve_remote_code_file(model_path, hf_config) 

126 if remote_path is not None: 

127 logger.debug( 

128 "source: resolved to remote code %s (no installed module)", 

129 remote_path, 

130 ) 

131 return _build_resolved_source(remote_path, "<remote>", arch, model_type) 

132 

133 raise FileNotFoundError( 

134 f"codegen: cannot resolve modeling source for model_type={model_type!r}, " 

135 f"architecture={arch!r} (no installed transformers module, no remote code)" 

136 ) 

137 

138 

139def _custom_registered_module(hf_config: Any) -> Optional[str]: 

140 """Consult hyper_parallel's custom-model registry for the modeling module. 

141 

142 ``MODEL_ARCH_MAPPING`` is filled lazily: a family's ``registration.py`` 

143 self-registers on first import (directory convention, see 

144 :mod:`hyper_parallel.models.registry`). Call ``get_model_adapter`` first 

145 so the lookup cannot miss an undiscovered family. 

146 """ 

147 arch = _first_architecture(hf_config) 

148 if not arch: 

149 return None 

150 try: 

151 from hyper_parallel.models.registry import ( # pylint: disable=C0415 

152 MODEL_ARCH_MAPPING, 

153 get_model_adapter, 

154 ) 

155 except ImportError: 

156 return None 

157 if MODEL_ARCH_MAPPING.get(arch) is None: 

158 # Either spelling may be the key that discovers the family (mirrors 

159 # get_is_hf_model's identity loop); stop once the architecture is 

160 # registered. The architecture goes first: it is the registry key. 

161 for identity in (arch, getattr(hf_config, "model_type", "")): 

162 if not identity: 

163 continue 

164 get_model_adapter(identity) 

165 if MODEL_ARCH_MAPPING.get(arch) is not None: 

166 break 

167 entry = MODEL_ARCH_MAPPING.get(arch) 

168 return entry[0] if entry is not None else None 

169 

170 

171def resolve_source_identity(model_id: str) -> Optional[ResolvedSource]: 

172 """Best-effort source resolution keyed only on a model id. 

173 

174 Used as a degradation when no ``hf_config`` / ``AutoConfig`` is available. 

175 Derives the module name from the model id's basename: model ids usually 

176 carry the repo name the transformers module is keyed on (``DeepSeek-V3`` 

177 -> ``deepseek_v3``). ``None`` when nothing resolves so the caller falls 

178 back further (or records the unresolved ``SourceSpec``). 

179 """ 

180 if not model_id: 

181 return None 

182 name = os.path.basename(str(model_id).rstrip("/\\")) 

183 safe = "".join(c if c.isalnum() or c == "_" else "_" for c in name).lower() 

184 module_name = _module_for_model_type(safe) 

185 if module_name is None: 

186 return None 

187 file_path = import_module_file(module_name) 

188 if file_path is None: 

189 return None 

190 return ResolvedSource( 

191 module_name=module_name, 

192 file_path=file_path, 

193 architecture=None, 

194 model_type=safe, 

195 ) 

196 

197 

198def resolve_remote_code_file(model_path: str, hf_config: Any) -> Optional[str]: 

199 """Locate the remote-code modeling file for a checkpoint. 

200 

201 Remote-code checkpoints carry ``modeling_*.py`` + ``configuration_*.py`` 

202 next to the weights. Two layouts are handled: 

203 

204 * A local checkpoint directory — scan it. 

205 * A Hub id — the files live in the HF cache, not under ``model_path``. A 

206 config loaded with ``trust_remote_code`` was constructed from the cached 

207 ``configuration_*.py``, so its class's ``__module__`` file locates the 

208 cache dir to scan. 

209 

210 Within a directory, resolve in order of increasing specificity: 

211 

212 1. ``auto_map["AutoModel..."]`` value, e.g. ``"modeling_foo.FooForCausalLM"`` 

213 -> ``<dir>/modeling_foo.py``. 

214 2. The architecture class name, e.g. ``FooForCausalLM`` -> the file whose 

215 basename contains it. 

216 3. The single ``modeling_*.py`` when there is exactly one. 

217 

218 Returns None when no remote code is reachable. 

219 """ 

220 for directory in _remote_code_dirs(model_path, hf_config): 

221 found = _scan_remote_code_dir(directory, hf_config) 

222 if found is not None: 

223 return found 

224 return None 

225 

226 

227def _remote_code_dirs(model_path: str, hf_config: Any) -> list[str]: 

228 """Directories that may hold this checkpoint's remote code, best first.""" 

229 dirs: list[str] = [] 

230 if model_path and os.path.isdir(model_path): 

231 dirs.append(model_path) 

232 # A remote-code config instance is defined in the cached configuration 

233 # module (``.../modules/transformers_modules/<repo>/configuration_x.py``), 

234 # which sits next to the cached modeling file. This is how a Hub id 

235 # resolves without downloading anything extra. 

236 module_name = getattr(type(hf_config), "__module__", "") or "" 

237 if module_name and module_name not in ("builtins", "types"): 

238 origin = import_module_file(module_name) 

239 if origin is None: 

240 module = __import__("sys").modules.get(module_name) 

241 origin = getattr(module, "__file__", None) if module else None 

242 if origin: 

243 cached_dir = os.path.dirname(origin) 

244 if cached_dir and cached_dir not in dirs and os.path.isdir(cached_dir): 

245 dirs.append(cached_dir) 

246 return dirs 

247 

248 

249def _scan_remote_code_dir(model_path: str, hf_config: Any) -> Optional[str]: 

250 """Pick this checkpoint's modeling file out of one directory.""" 

251 try: 

252 candidates = sorted( 

253 name for name in os.listdir(model_path) 

254 if name.startswith("modeling_") and name.endswith(".py") 

255 ) 

256 except OSError: 

257 return None 

258 if not candidates: 

259 return None 

260 

261 auto_map = getattr(hf_config, "auto_map", None) or {} 

262 for value in auto_map.values(): 

263 if not isinstance(value, str) or "." not in value: 

264 continue 

265 # "modeling_foo.FooForCausalLM" -> "modeling_foo.py". Hub auto_map 

266 # values can be "<repo>--modeling_foo.FooForCausalLM"; keep the tail. 

267 module_ref = value.split("--")[-1] 

268 module_file = module_ref.split(".", 1)[0] + ".py" 

269 if module_file in candidates: 

270 return os.path.join(model_path, module_file) 

271 

272 arch = _first_architecture(hf_config) 

273 if arch: 

274 for name in candidates: 

275 if arch in name: 

276 return os.path.join(model_path, name) 

277 if len(candidates) == 1: 

278 return os.path.join(model_path, candidates[0]) 

279 return None 

280 

281 

282def import_module_file(module_name: str) -> Optional[str]: 

283 """Resolve a Python module's ``__file__`` without importing it.""" 

284 try: 

285 spec = importlib.util.find_spec(module_name) 

286 except (ImportError, ModuleNotFoundError, ValueError, AttributeError): 

287 return None 

288 if spec is None or spec.origin is None: 

289 return None 

290 if not spec.origin.endswith(".py"): 

291 return None 

292 return spec.origin 

293 

294 

295def _module_for_model_type(model_type: Optional[str]) -> Optional[str]: 

296 """Map ``config.model_type`` to a transformers ``modeling_*`` module name.""" 

297 if not model_type: 

298 return None 

299 safe = "".join(c if c.isalnum() or c == "_" else "_" for c in model_type) 

300 return f"transformers.models.{safe}.modeling_{safe}" 

301 

302 

303def _first_architecture(hf_config: Any) -> Optional[str]: 

304 architectures = getattr(hf_config, "architectures", None) or [] 

305 return architectures[0] if architectures else None 

306 

307 

308def _model_path_of(config: Any) -> str: 

309 """Extract the checkpoint dir / HF id from the model target. 

310 

311 Same key order as ``project_source_spec``: most YAMLs and 

312 ``HyperAutoModel.from_pretrained`` configure the id under 

313 ``pretrained_model_name_or_path``, with ``model_name_or_path`` and the 

314 cropped/custom-builder ``config_path`` spelling as fallbacks. 

315 """ 

316 model = getattr(config, "model", None) 

317 if model is None: 

318 return "" 

319 path = getattr(model, "pretrained_model_name_or_path", None) 

320 if path is None: 

321 path = getattr(model, "model_name_or_path", None) 

322 if path is None: 

323 path = getattr(model, "config_path", None) 

324 if path is None: 

325 kwargs = getattr(model, "_kwargs", {}) 

326 path = kwargs.get("pretrained_model_name_or_path") or kwargs.get("config_path", "") 

327 return path or "" 

328 

329 

330def _trust_remote_code(config: Any) -> bool: 

331 """Whether this model is loaded with trusted remote code. 

332 

333 The truth is the YAML's ``model.trust_remote_code`` — it is what the 

334 trainer forwards into ``AutoConfig.from_pretrained`` / the HF 

335 ``from_pretrained`` kwargs, and therefore what decides whether HF loads 

336 the checkpoint's own modeling file or an installed transformers module. 

337 The ``TrainerConfig`` object itself has no such field, so this must read 

338 through the model target. 

339 """ 

340 model = getattr(config, "model", None) 

341 if model is None: 

342 return False 

343 value = getattr(model, "trust_remote_code", None) 

344 if value is None: 

345 value = getattr(model, "_kwargs", {}).get("trust_remote_code", False) 

346 return bool(value) 

347 

348 

349def _relative_imports_of(path: str) -> list[str]: 

350 """Names a file relatively imports from its own package (one level). 

351 

352 Mirrors ``transformers.dynamic_module_utils.get_relative_imports`` without 

353 importing transformers (source resolution must stay dependency-free). Only 

354 single-dot relatives are considered: a sibling ``from .name import x`` / 

355 ``import .name`` resolves within the same package directory, which is what 

356 a ``<remote>`` modeling source ships. Multi-dot relatives (``..x``) do not 

357 resolve against a flat remote code dir and are ignored. 

358 """ 

359 try: 

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

361 content = handle.read() 

362 except OSError: 

363 return [] 

364 names = re.findall(r"(?m)^\s*import\s+\.([A-Za-z_][A-Za-z0-9_]*)\s*$", content) 

365 names += re.findall(r"(?m)^\s*from\s+\.([A-Za-z_][A-Za-z0-9_]*)\s+import", content) 

366 return sorted(set(names)) 

367 

368 

369def resolve_remote_siblings(source: ResolvedSource) -> dict[str, str]: 

370 """Transitive closure of a ``<remote>`` source's package siblings. 

371 

372 Relative imports of a checkpoint-owned source must resolve within its 

373 source directory. ``<remote>`` and ``transformers_modules.*`` identify 

374 these sources; installed transformers modules use absolute imports. 

375 

376 Returns ``{absolute_path: absolute_path}`` for each reachable sibling. 

377 The emitter copies these files beside the generated modeling source. 

378 """ 

379 if isinstance(source, dict): 

380 module_name = source.get("module_name") 

381 file_path = source.get("file_path") 

382 else: 

383 module_name = getattr(source, "module_name", None) 

384 file_path = getattr(source, "file_path", None) 

385 is_remote = module_name == "<remote>" or ( 

386 isinstance(module_name, str) 

387 and module_name.startswith("transformers_modules.") 

388 ) 

389 if not is_remote or not file_path: 

390 return {} 

391 base_dir = os.path.dirname(os.path.abspath(file_path)) 

392 seen: dict[str, str] = {} 

393 queue: list[str] = [os.path.abspath(file_path)] 

394 while queue: 

395 module_file = queue.pop(0) 

396 for name in _relative_imports_of(module_file): 

397 sibling = os.path.join(base_dir, f"{name}.py") 

398 if not os.path.isfile(sibling): 

399 continue 

400 if sibling in seen: 

401 continue 

402 seen[sibling] = sibling 

403 queue.append(sibling) 

404 return seen 

405 

406 

407def _build_resolved_source( 

408 file_path: str, module_name: str, arch: Optional[str], model_type: Optional[str], 

409) -> ResolvedSource: 

410 return ResolvedSource( 

411 module_name=module_name, 

412 file_path=file_path, 

413 architecture=arch, 

414 model_type=model_type, 

415 ) 

416 

417 

418__all__ = [ 

419 "ResolvedSource", 

420 "import_module_file", 

421 "resolve_hf_source", 

422 "resolve_remote_code_file", 

423 "resolve_remote_siblings", 

424 "resolve_source_identity", 

425]