Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / codegen / session.py: 89%
131 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"""Stateful collector for immutable codegen build snapshots."""
17from __future__ import annotations
19from collections.abc import Mapping, Sequence
20from typing import Any, Callable, Optional
22from hyper_parallel.codegen.plan.observation import observe_emission_plan, observe_final_forwards
23from hyper_parallel.codegen.snapshot import (
24 CodegenSnapshot,
25 CodegenStatus,
26 FailureSnapshot,
27 ReplacementSnapshot,
28 copy_mapping,
29)
32class CodegenBuildSession:
33 """Collect native build observations without influencing the build."""
35 def __init__(self) -> None:
36 """Initialize an empty collection session."""
37 self._status = CodegenStatus.COLLECTING
38 self._source: dict[str, Any] = {}
39 self._replacements = ReplacementSnapshot()
40 self._plan: Optional[dict[str, Any]] = None
41 self._diagnostics: dict[str, Any] = {}
42 self._reason: Optional[str] = None
43 self._failure: Optional[FailureSnapshot] = None
44 self._source_recorded = False
45 self._replacements_recorded = False
46 self._diagnostics_recorded = False
47 self._finished = False
48 self._final_forwards_recorded = False
49 self._snapshot: Optional[CodegenSnapshot] = None
51 @property
52 def status(self) -> CodegenStatus:
53 """Return the current session status."""
54 return self._status
56 @property
57 def has_replacement_applications(self) -> bool:
58 """Whether native model construction installed any replacement."""
59 return bool(self._replacements.applications)
61 def record_source(self, source: Mapping[str, Any]) -> None:
62 """Record source and model identity once while collecting."""
63 self._require_open(CodegenStatus.COLLECTING)
64 if self._source_recorded:
65 raise RuntimeError("codegen source has already been recorded")
66 self._source = self._as_mapping(source, "source")
67 self._source_recorded = True
69 def record_replacements(
70 self,
71 *,
72 declarations: Sequence[Mapping[str, Any]] = (),
73 applications: Sequence[Mapping[str, Any]] = (),
74 unmatched: Sequence[Mapping[str, Any]] = (),
75 ) -> None:
76 """Record native replacement declarations and observed applications."""
77 self._require_open(CodegenStatus.COLLECTING)
78 if self._replacements_recorded:
79 raise RuntimeError("codegen replacements have already been recorded")
80 self._replacements = ReplacementSnapshot.from_data(
81 declarations=declarations,
82 applications=applications,
83 unmatched=unmatched,
84 )
85 self._replacements_recorded = True
87 def record_plan(self, plan: Mapping[str, Any]) -> None:
88 """Record the native planner result and enter the derived state."""
89 self._require_open(CodegenStatus.COLLECTING)
90 if not self._source_recorded:
91 raise RuntimeError("record_source() must run before record_plan()")
92 self._plan = self._as_mapping(plan, "plan")
93 self._status = CodegenStatus.DERIVED
95 def observe_plan(self, plan: Any, model: Any, mesh: Any) -> None:
96 """Observe a native planner result without exposing codegen to the builder."""
97 observed_plan = observe_emission_plan(plan, model).to_dict()
98 observed_plan["parallel_dims"] = {
99 "dp_size": getattr(mesh, "dp_size", 1),
100 "tp_size": mesh.tp_size,
101 "cp_size": mesh.cp_size,
102 "pp_size": getattr(mesh, "pp_size", 1),
103 "ep_size": mesh.ep_size,
104 "sequence_parallel": mesh.sequence_parallel,
105 "loss_parallel": mesh.loss_parallel,
106 }
107 self.record_plan(observed_plan)
109 def observe_final_forwards(self, model: Any, originals: Mapping[str, Any]) -> None:
110 """Append factory-tail facts once, before freezing the existing native plan."""
111 self._require_open(CodegenStatus.DERIVED, CodegenStatus.NOT_REQUIRED)
112 if self._final_forwards_recorded:
113 raise RuntimeError("codegen final forwards have already been observed")
114 additions = observe_final_forwards(model, originals)
115 self._final_forwards_recorded = True
116 if additions:
117 if self._plan is None:
118 self._plan = observe_emission_plan(None, None).to_dict()
119 self._plan.setdefault("injections", []).extend(additions)
120 self._status = CodegenStatus.DERIVED
121 self._reason = None
123 def record_diagnostics(self, diagnostics: Mapping[str, Any]) -> None:
124 """Record optional counters and audit facts once."""
125 self._require_open()
126 if self._diagnostics_recorded:
127 raise RuntimeError("codegen diagnostics have already been recorded")
128 self._diagnostics = self._as_mapping(diagnostics, "diagnostics")
129 self._diagnostics_recorded = True
131 def mark_not_required(self, reason: str) -> None:
132 """Finish collection when the native build has no sharding plan."""
133 self._require_open(CodegenStatus.COLLECTING)
134 if not self._source_recorded:
135 raise RuntimeError("record_source() must run before mark_not_required()")
136 self._reason = self._require_reason(reason)
137 self._status = CodegenStatus.NOT_REQUIRED
139 def mark_generating(self) -> None:
140 """Mark the future side-effecting generation boundary."""
141 self._require_open(CodegenStatus.DERIVED)
142 self._status = CodegenStatus.GENERATING
144 def mark_generated(self) -> None:
145 """Mark successful generation."""
146 self._require_open(CodegenStatus.GENERATING)
147 self._status = CodegenStatus.GENERATED
149 def mark_skipped(self, reason: str) -> None:
150 """Mark generation as intentionally skipped with a stable reason."""
151 self._require_open(CodegenStatus.COLLECTING, CodegenStatus.DERIVED)
152 if not self._source_recorded:
153 raise RuntimeError("record_source() must run before mark_skipped()")
154 self._reason = self._require_reason(reason)
155 self._status = CodegenStatus.SKIPPED
157 def mark_failed(
158 self,
159 stage: str,
160 reason: str,
161 details: Optional[Mapping[str, Any]] = None,
162 ) -> None:
163 """Record a codegen-owned failure without retaining an exception."""
164 self._require_open(
165 CodegenStatus.COLLECTING,
166 CodegenStatus.DERIVED,
167 CodegenStatus.GENERATING,
168 CodegenStatus.NOT_REQUIRED,
169 )
170 self._failure = FailureSnapshot.from_data(stage, reason, details)
171 self._status = CodegenStatus.FAILED
173 def finish(
174 self,
175 generator: Optional[Callable[[CodegenSnapshot], Any]] = None,
176 ) -> CodegenSnapshot:
177 """Seal the session, optionally publishing a derived snapshot.
179 ``generator`` is invoked only for a fully derived native build. Its
180 failure is recorded as codegen-owned state and deliberately does not
181 escape into the caller's already successful model build.
183 Args:
184 generator: Optional side-effecting publisher that consumes the
185 immutable derived snapshot.
187 Returns:
188 The same snapshot instance on repeated calls.
190 Raises:
191 RuntimeError: If collection or generation is incomplete.
192 """
193 if self._finished:
194 if self._snapshot is None:
195 raise RuntimeError("finished codegen session has no snapshot")
196 return self._snapshot
197 if self._status == CodegenStatus.COLLECTING:
198 raise RuntimeError("codegen session is still collecting")
199 if self._status == CodegenStatus.GENERATING:
200 raise RuntimeError("codegen session is still generating")
201 if self._status == CodegenStatus.DERIVED and generator is not None:
202 publish_snapshot = self._build_snapshot(CodegenStatus.DERIVED)
203 self.mark_generating()
204 try:
205 generator(publish_snapshot)
206 except Exception as exc: # pylint: disable=broad-exception-caught
207 # Generation must not invalidate an already successful native build.
208 self.mark_failed(
209 "generation",
210 str(exc) or type(exc).__name__,
211 {"exception_type": type(exc).__name__},
212 )
213 else:
214 self.mark_generated()
215 elif self._status == CodegenStatus.NOT_REQUIRED and generator is not None:
216 publish_snapshot = self._build_snapshot(CodegenStatus.NOT_REQUIRED)
217 try:
218 generator(publish_snapshot)
219 except Exception as exc: # pylint: disable=broad-exception-caught
220 # Publication must not invalidate an already successful native build.
221 self.mark_failed(
222 "generation",
223 str(exc) or type(exc).__name__,
224 {"exception_type": type(exc).__name__},
225 )
226 self._snapshot = self._build_snapshot(self._status)
227 self._finished = True
228 return self._snapshot
230 def _build_snapshot(self, status: CodegenStatus) -> CodegenSnapshot:
231 """Build an immutable view without sealing the session."""
232 return CodegenSnapshot._from_owned_data( # pylint: disable=protected-access
233 status=status,
234 source=self._source,
235 replacements=self._replacements,
236 plan=self._plan,
237 diagnostics=self._diagnostics,
238 reason=self._reason,
239 failure=self._failure,
240 )
242 def _require_open(self, *statuses: CodegenStatus) -> None:
243 if self._finished:
244 raise RuntimeError("codegen session is already finished")
245 if statuses and self._status not in statuses:
246 expected = ", ".join(status.value for status in statuses)
247 raise RuntimeError(
248 f"codegen session is {self._status.value}; expected one of: {expected}"
249 )
251 @staticmethod
252 def _as_mapping(value: Mapping[str, Any], path: str) -> dict[str, Any]:
253 return copy_mapping(value, path)
255 @staticmethod
256 def _require_reason(reason: str) -> str:
257 if not isinstance(reason, str) or not reason.strip():
258 raise ValueError("codegen reason must be a non-empty string")
259 return reason
262__all__ = ["CodegenBuildSession"]