Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / high_availability / validation.py: 96%
69 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"""Validate configuration and runtime state for process recovery."""
17from typing import Any, Mapping
19import torch
21from hyper_parallel.components.quantization.functional.base_gmm_func import GroupedLinear
22from hyper_parallel.components.quantization.functional.base_linear_func import LinearStrategy
23from hyper_parallel.components.quantization.functional.fake_w4a8_gmm_func import FakeW4A8GroupedLinear
24from hyper_parallel.components.quantization.functional.hifloat8_gmm_func import HiFloat8GroupedLinear
25from hyper_parallel.components.quantization.functional.hifloat8_linear_func import HiFloat8LinearStrategy
26from hyper_parallel.components.quantization.functional.mxfp8_gmm_func import MXFP8GroupedLinear
27from hyper_parallel.components.quantization.functional.mxfp8_linear_func import MXFP8LinearStrategy
28from hyper_parallel.components.quantization.functional.w4a8_gmm_func import W4A8GroupedLinear
29from hyper_parallel.components.quantization.quantizers.base import Quantizer
30from hyper_parallel.components.quantization.quantizers.fake_w4a8 import FakeW4A8Quantizer
31from hyper_parallel.components.quantization.quantizers.hifloat8 import HiFloat8Quantizer
32from hyper_parallel.components.quantization.quantizers.mxfp8 import MXFP8Quantizer
33from hyper_parallel.components.quantization.quantizers.w4a8 import W4A8Quantizer
34from hyper_parallel.components.quantization.tensor.quantized_tensor import QuantizedTensor
35from hyper_parallel.components.modules.engram.host_state import HostEngramState
38_ROLE_QUANTIZERS = ("input_quantizer", "weight_quantizer", "grad_output_quantizer")
39_STRATEGIES = {
40 MXFP8LinearStrategy: (MXFP8Quantizer, ("quantizer",)),
41 HiFloat8LinearStrategy: (HiFloat8Quantizer, _ROLE_QUANTIZERS),
42 MXFP8GroupedLinear: (MXFP8Quantizer, ("quantizer",)),
43 HiFloat8GroupedLinear: (HiFloat8Quantizer, _ROLE_QUANTIZERS),
44 W4A8GroupedLinear: (W4A8Quantizer, ("quantizer",)),
45 FakeW4A8GroupedLinear: (FakeW4A8Quantizer, ("quantizer",)),
46}
47_QUANTIZERS = (MXFP8Quantizer, HiFloat8Quantizer, W4A8Quantizer, FakeW4A8Quantizer)
48_PARAMETER_DTYPES = (torch.float16, torch.bfloat16, torch.float32, torch.float64)
51def validate_recovery_config(config: Any) -> None:
52 """Reject unsupported Trainer configurations before construction.
54 Args:
55 config: Trainer configuration for a recovery-enabled job.
56 """
57 if config.accelerator.pp_size != 1:
58 raise ValueError("PP schedule state requires a dedicated recovery adapter")
59 if config.training.backend not in ("hccl", "nccl"):
60 raise ValueError("worker recovery requires an HCCL or NCCL backend")
61 if config.compile.enabled:
62 raise ValueError("worker recovery requires eager training")
63 if config.dataloader is None or config.dataloader.use_background_prefetcher:
64 raise ValueError("worker recovery requires a stateful loader without background prefetch")
65 if config.model_integration.mode != "off" or config.peft is not None or config.magi is not None:
66 raise ValueError("worker recovery does not yet cover integration probes, PEFT or external model state")
67 if config.training.eval_iters or config.training.eval_steps or config.training.eval_epochs:
68 raise ValueError("worker recovery does not yet cover evaluation data state")
71def validate_recovery_model(model: torch.nn.Module) -> None:
72 """Check model-owned state and low-precision recovery compatibility before binding.
74 Args:
75 model: Materialized model with its parallel strategies applied.
76 """
77 external = getattr(model, "_hp_external_state", None)
78 if external is not None and not isinstance(external, HostEngramState):
79 raise ValueError("model-owned external state requires its own recovery provider")
80 validate_low_precision_state(model)
83def validate_low_precision_state(model: torch.nn.Module) -> None:
84 """Allow built-in current-scaling computation with ordinary persistent weights.
86 Args:
87 model: Materialized model, including module-family quantization entries.
89 Raises:
90 ValueError: A strategy, quantizer or persistent quantized tensor needs a
91 dedicated recovery contract. Subclasses are checked explicitly because
92 they may introduce unregistered observer or scaling-history state.
93 """
94 for name, module in model.named_modules():
95 has_quantization = False
96 for attribute, value in vars(module).items():
97 location = f"{name or '<root>'}.{attribute}"
98 if isinstance(value, (LinearStrategy, GroupedLinear)):
99 specification = _STRATEGIES.get(type(value))
100 if specification is None:
101 raise ValueError(f"{location}: custom low-precision strategy requires a recovery adapter")
102 quantizer_type, fields = specification
103 for field in fields:
104 actual_type = type(getattr(value, field, None))
105 if actual_type is not quantizer_type:
106 raise ValueError(f"{location}.{field}: custom quantizer requires a recovery adapter")
107 has_quantization = True
108 elif isinstance(value, Quantizer):
109 if type(value) not in _QUANTIZERS:
110 raise ValueError(f"{location}: custom quantizer requires a recovery adapter")
111 has_quantization = True
112 for parameter_name, parameter in module.named_parameters(recurse=False):
113 local = getattr(parameter, "_local_tensor", parameter)
114 if isinstance(local, QuantizedTensor) or (has_quantization and local.dtype not in _PARAMETER_DTYPES):
115 raise ValueError(f"{name or '<root>'}.{parameter_name}: recovery requires high-precision parameters")
116 for buffer_name, buffer in module.named_buffers(recurse=False):
117 if isinstance(getattr(buffer, "_local_tensor", buffer), QuantizedTensor):
118 raise ValueError(f"{name or '<root>'}.{buffer_name}: persistent quantized buffers require an adapter")
121def validate_recovery_state_providers(loader: Any, replica_providers: Mapping[str, Any]) -> None:
122 """Check that the loader and replica providers expose state save and restore.
124 Args:
125 loader: Training loader bound to the recovery session.
126 replica_providers: Named objects with equivalent state across replicas.
127 """
128 for provider in (loader, *replica_providers.values()):
129 if (not callable(getattr(provider, "state_dict", None))
130 or not callable(getattr(provider, "load_state_dict", None))):
131 raise ValueError("recovery requires state_dict/load_state_dict for every training state provider")