Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / quantization / config.py: 93%
177 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"""Typed low-precision policies and their FQN-independent dtype-scheme catalog."""
17from collections.abc import Mapping
18from dataclasses import dataclass, field, fields
19from typing import Literal, Optional, TypeAlias, Union, cast
22MXBlockSizeValue: TypeAlias = Literal[32]
23FP4_BITS = 4
24FP8_BITS = 8
25MX_BLOCK_SIZE_32 = 32
26SUPPORTED_MX_BLOCK_SIZES = (MX_BLOCK_SIZE_32,)
28# MX tensor and scale layout.
29MX_SCALE_SLOTS = 2
30MX_SCALE_TILE = MX_BLOCK_SIZE_32 * MX_SCALE_SLOTS
31MXFP4_VALUES_PER_BYTE = 2
32MXFP4_NIBBLE_BITS = 4
33MXFP4_NIBBLE_MASK = (1 << MXFP4_NIBBLE_BITS) - 1
35# E8M0/FP8 conversion limits used by the fake-QAT path.
36E8M0_BIAS = 127.0
37E8M0_MAX_EXPONENT = 255.0
38MXFP4_MAX_VALUE = 6.0
39FP8_E4M3_MAX = 448.0
40MAIN_KV_GROUP_SIZE = 16
41SWA_KV_GROUP_SIZE = 32
43# GroupedMatmul and DynamicMxQuant protocol values.
44GROUP_LIST_OFFSETS = 0
45GROUP_LIST_COUNTS = 1
46GMM_GROUP_M = 0
47GMM_GROUP_K = 2
48GMM_SPLIT_ANTIQ = 2
49GMM_SPLIT_MXFP8 = 2
50GMM_SPLIT_SCALE = 3
51MX_SCALE_ALG_OCP = 0
52MX_SCALE_ALG_CUBALS = 1
53NPU_FORMAT_FRACTAL_NZ = 29
55# Shape ranks used by grouped quantization contracts.
56MATRIX_NDIM = 2
57GROUPED_NDIM = 3
58SCALE_NDIM = 4
59_SUPPORTED_BLOCK_SIZE_TEXT = " or ".join(
60 str(block_size) for block_size in SUPPORTED_MX_BLOCK_SIZES
61)
64def validate_mx_block_size(block_size: int) -> MXBlockSizeValue:
65 """Validate a configured integer and preserve its numeric representation."""
67 if isinstance(block_size, bool) or not isinstance(block_size, int):
68 raise ValueError(
69 f"MX block_size must be {_SUPPORTED_BLOCK_SIZE_TEXT}, "
70 f"got {block_size!r}."
71 )
72 if block_size not in SUPPORTED_MX_BLOCK_SIZES:
73 raise ValueError(
74 f"MX block_size must be {_SUPPORTED_BLOCK_SIZE_TEXT}, "
75 f"got {block_size!r}."
76 )
77 return cast(MXBlockSizeValue, block_size)
80# One registry row per accepted dtype: (format family, bit width).
81# weight_format and act_format must share one family (operators never mix
82# families). The weight/activation bit widths are read directly from these
83# rows to select the native strategy (e.g. mxfp4 weight + mxfp8 act => W4A8).
84# Future dtypes (int/fp/bf, e.g. bf16) are one new row here; hif4 is
85# pre-listed as part of the hifloat family (reserved for its flow).
86_FORMAT_SPECS = {
87 "mxfp4": ("mxfp", FP4_BITS),
88 "mxfp8": ("mxfp", FP8_BITS),
89 "hif4": ("hifloat", FP4_BITS),
90 "hif8": ("hifloat", FP8_BITS),
91}
92_FORMATS = tuple(_FORMAT_SPECS)
95def _format_spec(format_name: str) -> tuple[str, int]:
96 """Look up one dtype format in ``_FORMAT_SPECS``.
98 Drives ``LowPrecisionDtypeScheme.__post_init__`` validation (family and
99 bit width). Raises ``ValueError`` on an unregistered
100 format so a bad ``weight_format``/``act_format`` fails at config time.
101 """
103 try:
104 return _FORMAT_SPECS[format_name]
105 except (KeyError, TypeError) as exc:
106 raise ValueError(
107 f"Unsupported low-precision format {format_name!r}; "
108 f"expected {_FORMATS}."
109 ) from exc
112def _format_family(format_name: str) -> str:
113 """Resolve one dtype format to its family name for the factory family gate.
115 Exported for the strategy factory, which must reject cross-family schemes
116 without coupling to the raw ``_FORMAT_SPECS`` tuple layout.
117 """
119 return _format_spec(format_name)[0]
122@dataclass(frozen=True)
123class LowPrecisionDtypeScheme:
124 """One complete low-precision dtype scheme referenced by a plan entry.
125 Defines the quantization dtypes for weights and activations together with
126 the quantization granularity and whether the scheme runs the native
127 operator flow or a future fake-quantize (fake QAT) seam. The native
128 strategy (W4A8/W8A8) is derived downstream from ``weight_format`` /
129 ``act_format`` bit widths, so it is not a separate field here.
130 """
132 # Optional: True = future fake-QAT seam; False (default) = native flow.
133 is_fake_quantize: bool = False
134 weight_format: Literal["mxfp4", "mxfp8", "hif4", "hif8"] = "mxfp8"
135 act_format: Literal["mxfp4", "mxfp8", "hif4", "hif8"] = "mxfp8"
136 block_size: int = MX_BLOCK_SIZE_32
138 def __post_init__(self) -> None:
139 """Validate that the scheme names a consistent native/QAT policy.
140 ``weight_format``/``act_format`` must share one format family (the
141 underlying operator never mixes families); their bit widths drive
142 strategy selection downstream. ``block_size`` must be an integer;
143 only MX formats restrict it to the currently supported block32 value.
144 """
146 if not isinstance(self.is_fake_quantize, bool):
147 raise ValueError(
148 "LowPrecisionDtypeScheme.is_fake_quantize must be a bool, "
149 f"but got {self.is_fake_quantize!r}."
150 )
151 if isinstance(self.block_size, bool) or not isinstance(self.block_size, int):
152 raise ValueError("LowPrecisionDtypeScheme.block_size must be an integer.")
154 weight_family, _ = _format_spec(self.weight_format)
155 act_family, _ = _format_spec(self.act_format)
156 if weight_family != act_family:
157 raise ValueError(
158 "weight_format and act_format must belong to the same format "
159 "family (the underlying operator never mixes families); got "
160 f"weight={self.weight_format!r}/act={self.act_format!r}."
161 )
162 if weight_family == "mxfp":
163 try:
164 block_size = validate_mx_block_size(self.block_size)
165 except ValueError as exc:
166 raise ValueError(f"LowPrecisionDtypeScheme.{exc}") from exc
167 object.__setattr__(self, "block_size", block_size)
170@dataclass(frozen=True)
171class CSA2IndexerQKFormat:
172 """OCP MXFP4 activation QDQ for CSA2 Indexer queries and keys."""
174 act_format: Literal["mxfp4"]
176 def __post_init__(self) -> None:
177 if self.act_format != "mxfp4":
178 raise ValueError("indexer_qk.act_format must be 'mxfp4'.")
181@dataclass(frozen=True)
182class CSA2MainKVFormat:
183 """Main KV E2M1 with one E4M3 or E8M7 scale per 16 channels."""
185 act_format: Literal["fp4_e2m1"]
186 scale_format: Literal["e4m3", "e8m7"]
187 group: Literal[16] = MAIN_KV_GROUP_SIZE
189 def __post_init__(self) -> None:
190 if self.act_format != "fp4_e2m1":
191 raise ValueError("main_kv.act_format must be 'fp4_e2m1'.")
192 if self.scale_format not in ("e4m3", "e8m7"):
193 raise ValueError("main_kv.scale_format must be 'e4m3' or 'e8m7' (BF16).")
194 if isinstance(self.group, bool) or not isinstance(self.group, int) or self.group != MAIN_KV_GROUP_SIZE:
195 raise ValueError("main_kv.group must be 16.")
198@dataclass(frozen=True)
199class CSA2SWAKVFormat:
200 """FP8 E4M3 sliding-window KV with E8M0 or E8M7 scales."""
202 act_format: Literal["fp8_e4m3"]
203 scale_format: Literal["e8m0", "e8m7"] = "e8m0"
204 group: Literal[32] = SWA_KV_GROUP_SIZE
206 def __post_init__(self) -> None:
207 if self.act_format != "fp8_e4m3":
208 raise ValueError("swa_kv.act_format must be 'fp8_e4m3'.")
209 if self.scale_format not in ("e8m0", "e8m7"):
210 raise ValueError("swa_kv.scale_format must be 'e8m0' or 'e8m7' (BF16).")
211 if isinstance(self.group, bool) or not isinstance(self.group, int) or self.group != SWA_KV_GROUP_SIZE:
212 raise ValueError("swa_kv.group must be 32.")
215_CSA2_FORMAT_TYPES = {
216 "indexer_qk": CSA2IndexerQKFormat,
217 "main_kv": CSA2MainKVFormat,
218 "swa_kv": CSA2SWAKVFormat,
219}
221CSA2DtypeScheme: TypeAlias = Union[
222 LowPrecisionDtypeScheme, CSA2IndexerQKFormat, CSA2MainKVFormat, CSA2SWAKVFormat,
223]
226@dataclass
227class LowPrecisionConfig:
228 """Global switch plus a catalog of named dtype schemes.
230 A W/A dtype scheme is selected by the surrounding ``PlanOverride`` entry.
231 CSA2 formats are read directly by a matching attention replacement from
232 the shared build context; unused formats remain in this catalog.
234 ``format``/``scaling`` retain the pre-catalog configuration surface. They
235 are converted to one implicit scheme when no named catalog is supplied,
236 so existing callers remain valid while mixed W8A8/W4A8 plans use
237 ``dtype_schemes`` explicitly.
238 """
240 enabled: bool = False
241 format: Literal["mxfp8_e4m3", "mxfp4_e2m1", "hif8"] = "mxfp8_e4m3"
242 scaling: Literal["mx_block", "current"] = "mx_block"
243 dtype_schemes: dict[str, CSA2DtypeScheme] = field(default_factory=dict)
244 default_dtype_scheme: Optional[str] = None
246 def __post_init__(self) -> None:
247 """Validate catalog keys and the optional default dtype scheme."""
249 if not isinstance(self.enabled, bool):
250 raise ValueError("LowPrecisionConfig.enabled must be a bool.")
251 legacy_pairs = {
252 ("mxfp8_e4m3", "mx_block"),
253 ("mxfp4_e2m1", "mx_block"),
254 ("hif8", "current"),
255 }
256 if (self.format, self.scaling) not in legacy_pairs:
257 raise ValueError(
258 "Unsupported low-precision format/scaling combination "
259 f"{self.format!r}/{self.scaling!r}."
260 )
262 if not isinstance(self.dtype_schemes, Mapping):
263 raise ValueError(
264 "LowPrecisionConfig.dtype_schemes must be a mapping of "
265 "non-empty names to dtype schemes."
266 )
267 typed_schemes = {}
268 for name, scheme in self.dtype_schemes.items():
269 if not isinstance(name, str) or not name:
270 raise ValueError("LowPrecisionConfig.dtype_schemes keys must be non-empty strings.")
271 scheme_type = _CSA2_FORMAT_TYPES.get(name, LowPrecisionDtypeScheme)
272 if isinstance(scheme, Mapping):
273 try:
274 scheme = scheme_type(**dict(scheme))
275 except (TypeError, ValueError) as exc:
276 raise ValueError(
277 f"Invalid LowPrecisionConfig.dtype_schemes.{name}: {exc}"
278 ) from exc
279 if not isinstance(scheme, scheme_type):
280 raise ValueError(
281 f"LowPrecisionConfig.dtype_schemes.{name} must be a {scheme_type.__name__}."
282 )
283 typed_schemes[name] = scheme
284 self.dtype_schemes = typed_schemes
285 if self.default_dtype_scheme is not None:
286 if not isinstance(self.default_dtype_scheme, str) or not self.default_dtype_scheme:
287 raise ValueError(
288 "LowPrecisionConfig.default_dtype_scheme must be a dtype scheme name."
289 )
290 if not isinstance(self.dtype_schemes.get(self.default_dtype_scheme), LowPrecisionDtypeScheme):
291 raise ValueError(
292 f"LowPrecisionConfig.default_dtype_scheme "
293 f"{self.default_dtype_scheme!r} is not a W/A scheme in dtype_schemes."
294 )
296 @property
297 def indexer_qk(self) -> Optional[CSA2IndexerQKFormat]:
298 """Return the configured Indexer activation format, if present."""
299 value = self.dtype_schemes.get("indexer_qk")
300 return value if isinstance(value, CSA2IndexerQKFormat) else None
302 @property
303 def main_kv(self) -> Optional[CSA2MainKVFormat]:
304 """Return the configured Main KV cache format, if present."""
305 value = self.dtype_schemes.get("main_kv")
306 return value if isinstance(value, CSA2MainKVFormat) else None
308 @property
309 def swa_kv(self) -> Optional[CSA2SWAKVFormat]:
310 """Return the configured SWA KV cache format, if present."""
311 value = self.dtype_schemes.get("swa_kv")
312 return value if isinstance(value, CSA2SWAKVFormat) else None
314 def active_direct_formats(self) -> frozenset[str]:
315 """Return explicitly configured CSA2 formats."""
316 return frozenset(self.dtype_schemes.keys() & _CSA2_FORMAT_TYPES.keys())
318 @property
319 def supported_parallel_axes(self) -> frozenset[str]:
320 """Return model-parallel axes implemented by the configured formats.
322 Direct activation/cache formats support TP and CP. Legacy W/A precision
323 and catalogs mixing W/A schemes with direct formats retain their
324 single-card restriction.
325 """
326 direct_formats = self.active_direct_formats()
327 if direct_formats and len(direct_formats) == len(self.dtype_schemes):
328 return frozenset({"tp", "cp"})
329 return frozenset()
331 def resolve_dtype_scheme(
332 self, dtype_scheme_name: Optional[str] = None,
333 ) -> LowPrecisionDtypeScheme:
334 """Map a dtype-scheme *name* to the scheme object used downstream.
336 The input is either ``plan_overrides[].low_precision_dtype_scheme`` or
337 ``default_dtype_scheme``; the returned ``LowPrecisionDtypeScheme`` is
338 what the strategy factory and adapters actually consume. Only resolves
339 catalog names -- which modules are matched is decided by the plan.
340 """
342 selected = dtype_scheme_name or self.default_dtype_scheme
343 if selected is not None:
344 if not isinstance(selected, str) or not selected:
345 raise ValueError(
346 "low-precision dtype scheme name must be a non-empty string."
347 )
348 scheme = self.dtype_schemes.get(selected)
349 if not isinstance(scheme, LowPrecisionDtypeScheme):
350 available = sorted(
351 name for name, value in self.dtype_schemes.items()
352 if isinstance(value, LowPrecisionDtypeScheme)
353 )
354 raise ValueError(
355 f"Unknown W/A low-precision dtype scheme {selected!r}; "
356 f"available W/A schemes: {available}."
357 )
358 return scheme
359 if any(isinstance(value, LowPrecisionDtypeScheme) for value in self.dtype_schemes.values()):
360 # A catalog exists but nothing was selected: fail loudly instead of
361 # silently running the model unquantized.
362 raise ValueError(
363 "LowPrecisionConfig.dtype_schemes is configured, but the replacement "
364 "plan did not select low_precision_dtype_scheme and no "
365 "default_dtype_scheme was declared."
366 )
367 legacy_scheme = {
368 ("mxfp8_e4m3", "mx_block"): LowPrecisionDtypeScheme(),
369 ("mxfp4_e2m1", "mx_block"): LowPrecisionDtypeScheme(
370 weight_format="mxfp4",
371 act_format="mxfp8",
372 ),
373 ("hif8", "current"): LowPrecisionDtypeScheme(
374 weight_format="hif8",
375 act_format="hif8",
376 ),
377 }
378 return legacy_scheme[(self.format, self.scaling)]
380 def to_dict(self) -> dict[str, object]:
381 """Serialize legacy fields and the optional named scheme catalog."""
383 result: dict[str, object] = {
384 "enabled": self.enabled,
385 "format": self.format,
386 "scaling": self.scaling,
387 }
388 if self.dtype_schemes:
389 result["dtype_schemes"] = {
390 name: {scheme_field.name: getattr(scheme, scheme_field.name) for scheme_field in fields(scheme)}
391 for name, scheme in self.dtype_schemes.items()
392 }
393 if self.default_dtype_scheme is not None:
394 result["default_dtype_scheme"] = self.default_dtype_scheme
395 return result
398__all__ = [
399 "MXBlockSizeValue",
400 "LowPrecisionConfig",
401 "LowPrecisionDtypeScheme",
402 "CSA2IndexerQKFormat",
403 "CSA2MainKVFormat",
404 "CSA2SWAKVFormat",
405 "MAIN_KV_GROUP_SIZE",
406 "SWA_KV_GROUP_SIZE",
407 "MX_BLOCK_SIZE_32",
408 "SUPPORTED_MX_BLOCK_SIZES",
409 "validate_mx_block_size",
410]