Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / modules / linear / linear_family.py: 100%

29 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"""Dense Linear Module Family registration and shared low-precision factories.""" 

16 

17from __future__ import annotations 

18 

19from collections.abc import Mapping 

20from typing import Any 

21 

22from torch import nn 

23 

24from hyper_parallel.components.modules.linear.linear import Linear, LowPrecisionLinear 

25from hyper_parallel.components.modules.module_family import ( 

26 ModuleFamily, 

27 SelectorSpec, 

28 VariantRule, 

29 register_module_family, 

30) 

31from hyper_parallel.components.quantization.config import LowPrecisionConfig, LowPrecisionDtypeScheme 

32from hyper_parallel.components.quantization.functional.linear_strategy_factory import build_linear_strategy 

33from hyper_parallel.models.replacement import module_replacement 

34 

35_MXFP8_DENSE_SCHEME = LowPrecisionDtypeScheme(weight_format="mxfp8", act_format="mxfp8") 

36_HIF8_DENSE_SCHEME = LowPrecisionDtypeScheme(weight_format="hif8", act_format="hif8") 

37 

38 

39def replace_linear_with_policy( 

40 *, 

41 module: nn.Module, 

42 module_fqn: str, 

43 context: Mapping[str, Any], 

44 scheme: LowPrecisionDtypeScheme | LowPrecisionConfig | None, 

45) -> LowPrecisionLinear: 

46 """Validate an exact Dense Linear boundary and bind its resolved compute strategy. 

47 

48 Args: 

49 module: Source Linear whose loaded parameters are retained. 

50 module_fqn: Module path for diagnostics. 

51 context: Replacement context containing parallel topology. 

52 scheme: Explicit or policy-resolved low-precision dtype scheme. 

53 

54 Returns: 

55 A ``LowPrecisionLinear`` sharing the source parameters without reinitializing them. 

56 """ 

57 if type(module) is not nn.Linear: # pylint: disable=unidiomatic-typecheck 

58 raise TypeError(f"{module_fqn!r} must be exact nn.Linear, got {type(module).__name__}") 

59 if context.get("pp"): 

60 raise NotImplementedError( 

61 "Low-precision Linear training is not yet supported with pipeline parallelism." 

62 ) 

63 try: 

64 strategy = build_linear_strategy( 

65 scheme, 

66 in_features=module.in_features, 

67 out_features=module.out_features, 

68 ) 

69 except ValueError as error: 

70 raise ValueError( 

71 f"Low-precision Linear target {module_fqn!r} is invalid: {error}" 

72 ) from error 

73 return LowPrecisionLinear.from_linear(module, strategy=strategy) 

74 

75 

76@module_replacement 

77def replace_mxfp8_linear( 

78 *, module: nn.Module, module_fqn: str, context: Mapping[str, Any], 

79) -> LowPrecisionLinear: 

80 """Bind the MXFP8 Dense strategy selected by the Linear Family rule. 

81 

82 Args: 

83 module: Exact nn.Linear source with feature dimensions divisible by 32. 

84 module_fqn: Module path for diagnostics. 

85 context: Replacement context containing parallel topology. 

86 

87 Returns: 

88 A low-precision Linear sharing the source parameters and training mode. 

89 """ 

90 return replace_linear_with_policy( 

91 module=module, 

92 module_fqn=module_fqn, 

93 context=context, 

94 scheme=_MXFP8_DENSE_SCHEME, 

95 ) 

96 

97 

98@module_replacement 

99def replace_hif8_linear( 

100 *, module: nn.Module, module_fqn: str, context: Mapping[str, Any], 

101) -> LowPrecisionLinear: 

102 """Bind the HiFloat8 Dense strategy selected by the Linear Family rule. 

103 

104 Args: 

105 module: Exact nn.Linear source; MX block alignment is not required. 

106 module_fqn: Module path for diagnostics. 

107 context: Replacement context containing parallel topology. 

108 

109 Returns: 

110 A low-precision Linear sharing the source parameters and training mode. 

111 """ 

112 return replace_linear_with_policy( 

113 module=module, 

114 module_fqn=module_fqn, 

115 context=context, 

116 scheme=_HIF8_DENSE_SCHEME, 

117 ) 

118 

119 

120register_module_family(ModuleFamily( 

121 name="linear", 

122 baseline=Linear, 

123 variants={ 

124 "mxfp8": "hyper_parallel.components.modules.linear.linear_family.replace_mxfp8_linear", 

125 "hif8": "hyper_parallel.components.modules.linear.linear_family.replace_hif8_linear", 

126 }, 

127 selector_specs={ 

128 "weight_format": SelectorSpec(str, ""), 

129 "act_format": SelectorSpec(str, ""), 

130 "is_fake_quantize": SelectorSpec(bool, False), 

131 "fused": SelectorSpec(bool, False), 

132 }, 

133 variant_rules=( 

134 VariantRule( 

135 {"weight_format": "mxfp8", "act_format": "mxfp8", "is_fake_quantize": False, "fused": False}, 

136 "mxfp8", 

137 ), 

138 VariantRule( 

139 {"weight_format": "hif8", "act_format": "hif8", "is_fake_quantize": False, "fused": False}, 

140 "hif8", 

141 ), 

142 ), 

143)) 

144 

145__all__ = [ 

146 "replace_hif8_linear", 

147 "replace_linear_with_policy", 

148 "replace_mxfp8_linear", 

149]