Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / codegen / model_build_overlay.py: 98%
180 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"""Codegen-owned model observation layered over the native AutoModel API."""
17from collections.abc import Sequence
18from contextlib import contextmanager
19from dataclasses import dataclass, field
20import inspect
21import random
22from typing import Any, Callable, Iterator, Optional
24import torch
26from hyper_parallel.codegen.manager import ensure_codegen_artifact_from_snapshot
27from hyper_parallel.codegen.session import CodegenBuildSession
28from hyper_parallel.components.modules.module_family import get_family_build_info
29from hyper_parallel.core.dtensor.init_weights import init_empty_weights
30from hyper_parallel.distributed._builder.applier import (
31 _get_active_mesh,
32 _preflight_compute_injection,
33)
34from hyper_parallel.models._transformers import auto_model, model_builder
35from hyper_parallel.models import module_build, replacement as replacement_api
38def _prepare_model_source_compat(adapter: Any) -> None:
39 """Run an optional model-owned compatibility hook before construction."""
40 loader = getattr(adapter, "codegen", None) if adapter is not None else None
41 provider = loader() if loader is not None else None
42 prepare = getattr(provider, "prepare_model_import", None)
43 if prepare is not None:
44 prepare()
47@dataclass
48class CodegenModelBuildResult:
49 """Result populated by one scoped offline model observation."""
51 artifact_layout: Optional[Any] = None
52 snapshot: Optional[Any] = None
53 model: Optional[Any] = field(default=None, repr=False)
56@contextmanager
57def _codegen_model_init_context() -> Iterator[None]:
58 """Build codegen's observation model with parameters and buffers on meta."""
59 with init_empty_weights(include_buffers=True), auto_model._model_init_context( # pylint: disable=protected-access
60 True
61 ):
62 yield
65def _codegen_current_device() -> torch.device:
66 """Preserve the target backend without querying an ordinal that lazily initializes it."""
67 return torch.device(auto_model.get_device_type())
70def _record_source(
71 session: CodegenBuildSession,
72 model: Any,
73 hf_config: Any,
74 pretrained_model_name_or_path: Any,
75 is_hf_model: bool,
76) -> None:
77 """Record deterministic source identity from the constructed meta model."""
78 model_type = type(model)
79 source_path = inspect.getsourcefile(model_type)
80 architectures = list(getattr(hf_config, "architectures", None) or ())
81 architecture = architectures[0] if architectures else model_type.__name__
82 session.record_source({
83 "model_type": getattr(hf_config, "model_type", None),
84 "architecture": architecture,
85 "architectures": architectures,
86 "model_class": f"{model_type.__module__}:{model_type.__qualname__}",
87 "module_name": model_type.__module__,
88 "file_path": source_path,
89 "pretrained_model_name_or_path": (
90 None if pretrained_model_name_or_path is None else str(pretrained_model_name_or_path)
91 ),
92 "is_hf_model": bool(is_hf_model),
93 })
96def _observe_replacements(
97 model: Any,
98 distributed_setup: Any,
99 low_precision_config: Any,
100 load_base_model: bool,
101 session: CodegenBuildSession,
102) -> Any:
103 """Apply native replacement declarations while recording their result."""
104 specs = list(getattr(distributed_setup, "module_replacements", None) or ())
105 original_compile = module_build.compile_module_replacements
107 def _observe_compile(*args: Any, **kwargs: Any) -> Any:
108 plan = original_compile(*args, **kwargs)
109 specs[:] = plan.specs
110 return plan
112 module_build.compile_module_replacements = _observe_compile
113 try:
114 with _observe_replacement_installations(specs) as applications:
115 model, _ = model_builder._maybe_apply_module_replacements( # pylint: disable=protected-access
116 model, distributed_setup, low_precision_config, load_base_model,
117 )
118 except replacement_api.ModuleReplacementMatchError as exc:
119 session.record_replacements(
120 declarations=replacement_api.describe_replacement_declarations(specs),
121 applications=(), unmatched=exc.unmatched,
122 )
123 raise
124 finally:
125 module_build.compile_module_replacements = original_compile
126 session.record_replacements(
127 declarations=replacement_api.describe_replacement_declarations(specs),
128 applications=applications, unmatched=(),
129 )
130 return model
133@contextmanager
134def _observe_replacement_installations(specs: Sequence[Any]) -> Iterator[list[dict[str, Any]]]:
135 """Record metadata only after the shared installer commits a prepared candidate."""
136 applications: list[dict[str, Any]] = []
137 spec_indexes = {id(spec): index for index, spec in enumerate(specs)}
138 pending = {}
139 original_prepare = replacement_api._prepare_replacement_target # pylint: disable=protected-access
140 original_install = replacement_api._install_module_candidates # pylint: disable=protected-access
142 def _observe_prepare(target: Any, *args: Any, **kwargs: Any) -> Any:
143 candidate, transforms = original_prepare(target, *args, **kwargs)
144 if id(target.spec) not in spec_indexes:
145 spec_indexes.update({id(spec): index for index, spec in enumerate(specs)})
146 index = spec_indexes.setdefault(id(target.spec), len(spec_indexes))
147 pending[(target.module_fqns, id(candidate))] = {
148 "rule_id": replacement_api._replacement_rule_id(target.spec, index), # pylint: disable=protected-access
149 "module_fqns": list(target.module_fqns),
150 "primary_fqn": target.module_fqns[0],
151 "source_type": replacement_api._symbol_path(type(target.source)),
152 "replacement_type": replacement_api._symbol_path(type(candidate)),
153 "weight_transforms": [replacement_api._symbol_path(type(transform)) for transform in transforms],
154 }
155 family = get_family_build_info(candidate)
156 if family is not None:
157 # Model depth is needed by expert constructors even when their source
158 # does not retain a config. Keep the native result without runtime owners.
159 context = args[0] if args else kwargs["context"]
160 construction_context = {f"{axis}_size": size for axis, size in family.resolved.axis_sizes.items()}
161 if context.get("num_layers") is not None:
162 construction_context["num_layers"] = context["num_layers"]
163 pending[(target.module_fqns, id(candidate))]["family_request"] = {
164 "factory": replacement_api._symbol_path(family.request.target), # pylint: disable=protected-access
165 "kwargs": dict(family.request.kwargs),
166 "context": construction_context,
167 }
168 return candidate, transforms
170 def _observe_install(root: Any, candidates: Any) -> Any:
171 candidates = tuple(candidates)
172 source_scopes = {}
173 for fqn, module in root.named_modules(remove_duplicate=False):
174 source_scopes.setdefault(replacement_api._symbol_path(type(module)), []).append(fqn)
175 result = original_install(root, candidates)
176 for fqns, _, candidate in candidates:
177 record = pending.pop((fqns, id(candidate)), None)
178 if record is not None:
179 record["construction"] = {
180 "implementation": record["replacement_type"],
181 "source_fqns": sorted(source_scopes.get(record["source_type"], [])),
182 }
183 if hasattr(candidate, "rms_norm_cast_order"):
184 record["construction"]["arguments"] = {
185 "cast_order": candidate.rms_norm_cast_order, "fp32_weight": candidate.fp32_weight,
186 }
187 applications.append(record)
188 return result
190 replacement_api._prepare_replacement_target = _observe_prepare # pylint: disable=protected-access
191 replacement_api._install_module_candidates = _observe_install # pylint: disable=protected-access
192 try:
193 yield applications
194 finally:
195 replacement_api._prepare_replacement_target = original_prepare # pylint: disable=protected-access
196 replacement_api._install_module_candidates = original_install # pylint: disable=protected-access
199def _observe_plan(
200 model: Any,
201 mesh: Any,
202 sharding_planner: Any,
203 is_hf_model: bool,
204 session: CodegenBuildSession,
205) -> None:
206 """Derive a native plan without applying distributed runtime operations."""
207 model_sharding_requested = (
208 mesh is not None
209 and any(size > 1 for size in (mesh.tp_size, mesh.cp_size, mesh.ep_size))
210 )
211 if sharding_planner is None:
212 session.mark_not_required("planner_unavailable")
213 return
214 if mesh is None:
215 session.mark_not_required("mesh_unavailable")
216 return
217 if mesh.device_mesh is None:
218 session.mark_not_required("device_mesh_unavailable")
219 return
220 if (is_hf_model and not model_sharding_requested
221 and not model_builder._has_module_owned_layouts(model)): # pylint: disable=protected-access
222 if session.has_replacement_applications:
223 session.observe_plan(None, None, mesh)
224 else:
225 session.mark_not_required("pure_data_parallel")
226 return
227 plan = sharding_planner.plan(
228 model,
229 mesh.device_mesh,
230 tp_size=mesh.tp_size,
231 cp_size=mesh.cp_size,
232 ep_size=mesh.ep_size,
233 sequence_parallel=mesh.sequence_parallel,
234 loss_parallel=mesh.loss_parallel,
235 )
236 active_mesh = _get_active_mesh(mesh.device_mesh, plan.mesh_dim_names)
237 _preflight_compute_injection(plan, active_mesh, model=model)
238 session.observe_plan(plan, model, mesh)
241def _publish_session(
242 session: CodegenBuildSession,
243 artifact_dir: Optional[str],
244 result: CodegenModelBuildResult,
245) -> Any:
246 """Publish an offline snapshot while preserving host RNG state."""
247 cpu_rng_state = torch.get_rng_state()
248 python_rng_state = random.getstate()
250 def _publish(snapshot: Any) -> None:
251 """Publish one snapshot and restore RNG state afterward."""
252 try:
253 result.artifact_layout = ensure_codegen_artifact_from_snapshot(snapshot, artifact_dir)
254 finally:
255 torch.set_rng_state(cpu_rng_state)
256 random.setstate(python_rng_state)
258 return session.finish(_publish)
261def _codegen_build_model(
262 session: CodegenBuildSession, artifact_dir: Optional[str], result: CodegenModelBuildResult,
263 on_observed: Optional[Callable[[Any], None]] = None,
264):
265 """Create the classmethod used only while the CLI constructs a meta model."""
267 def _build_model(
268 cls,
269 pretrained_model_name_or_path,
270 *model_args,
271 is_hf_model,
272 hf_config,
273 mesh,
274 sharding_planner,
275 fsdp2_manager,
276 peft_config,
277 torch_dtype,
278 attn_implementation,
279 validate_placement,
280 load_base_model,
281 distributed_setup=None,
282 qat_config=None,
283 fp8_config=None,
284 compile_config=None,
285 freeze_config=None,
286 activation_checkpoint=None,
287 model_init_dtype=None,
288 **kwargs,
289 ) -> Any:
290 """Construct and observe a meta model without runtime infrastructure."""
291 del (
292 fsdp2_manager,
293 validate_placement,
294 compile_config,
295 activation_checkpoint,
296 )
297 factory, context = auto_model._resolve_module_construction( # pylint: disable=protected-access
298 kwargs, hf_config, distributed_setup, model_init_dtype or torch_dtype,
299 )
300 init_kwargs = auto_model._model_init_kwargs( # pylint: disable=protected-access
301 dict(kwargs),
302 load_base_model=False,
303 )
304 if "trust_remote_code" in kwargs:
305 init_kwargs["trust_remote_code"] = kwargs["trust_remote_code"]
306 _prepare_model_source_compat(context["model_spec"])
307 with _codegen_model_init_context():
308 if factory is not None:
309 if model_args:
310 raise ValueError("model_factory uses config and context, not additional positional model arguments")
311 model = auto_model.construct_family_model(factory, hf_config, context=context)
312 else:
313 _, model = auto_model._init_model( # pylint: disable=protected-access
314 cls, None, hf_config, attn_implementation, torch_dtype, is_hf_model,
315 *model_args, **init_kwargs,
316 )
317 auto_model.attach_build_context(model, context)
318 _record_source(
319 session,
320 model,
321 hf_config,
322 pretrained_model_name_or_path,
323 is_hf_model,
324 )
325 model_builder._apply_pre_sharding_features( # pylint: disable=protected-access
326 peft_config,
327 qat_config,
328 fp8_config,
329 )
330 model = _observe_replacements(
331 model,
332 distributed_setup,
333 getattr(distributed_setup, "low_precision_config", None),
334 load_base_model,
335 session,
336 )
337 model_builder._tie_model_weights_before_parallelism(model) # pylint: disable=protected-access
338 if freeze_config is not None:
339 model_builder._apply_parameter_freezing( # pylint: disable=protected-access
340 model,
341 freeze_config,
342 )
343 model_builder._apply_model_method_replacements( # pylint: disable=protected-access
344 model, distributed_setup, getattr(distributed_setup, "low_precision_config", None),
345 )
346 _observe_plan(model, mesh, sharding_planner, is_hf_model, session)
347 if on_observed is not None:
348 on_observed(model)
349 else:
350 snapshot = _publish_session(session, artifact_dir, result)
351 result.snapshot = snapshot
352 model._hp_codegen_snapshot = snapshot # pylint: disable=protected-access
353 model.train()
354 return model
356 return _build_model
359@contextmanager
360def use_codegen_model_build_overlay(
361 session: CodegenBuildSession,
362 artifact_dir: Optional[str] = None,
363 *,
364 defer_publish: bool = False,
365) -> Iterator[CodegenModelBuildResult]:
366 """Temporarily replace AutoModel's final build step for offline codegen.
368 Args:
369 session: Build session receiving native observations and emitted artifacts.
370 artifact_dir: Optional output directory for generated sources.
371 defer_publish: Observe and publish after the configured outer factory returns.
372 """
373 model_class = auto_model._BaseHyperAutoModelClass # pylint: disable=protected-access
374 original = model_class.__dict__["_build_model"]
375 original_device = auto_model._current_device # pylint: disable=protected-access
376 result = CodegenModelBuildResult()
377 pending = []
379 def _defer(model: Any) -> None:
380 """Keep live references only inside this factory observation scope."""
381 result.model = model
382 pending.append((model, {fqn: module.forward for fqn, module in model.named_modules()}))
384 model_class._build_model = classmethod( # pylint: disable=protected-access
385 _codegen_build_model(session, artifact_dir, result, _defer if defer_publish else None)
386 )
387 auto_model._current_device = _codegen_current_device # pylint: disable=protected-access
388 try:
389 yield result
390 if pending:
391 model, originals = pending.pop()
392 if result.model is not model:
393 raise RuntimeError("codegen outer factory returned a different model root")
394 session.observe_final_forwards(model, originals)
395 result.snapshot = _publish_session(session, artifact_dir, result)
396 finally:
397 pending.clear()
398 result.model = None
399 model_class._build_model = original # pylint: disable=protected-access
400 auto_model._current_device = original_device # pylint: disable=protected-access
403__all__ = ["CodegenModelBuildResult", "use_codegen_model_build_overlay"]