Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / modules / linear / linear.py: 88%
43 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"""Dense Linear replacement baseline and strategy-bound low-precision Linear."""
17from __future__ import annotations
19from collections.abc import Mapping
20from typing import Any
22import torch
23from torch import nn
25from hyper_parallel.components.quantization.functional.base_linear_func import (
26 LinearStrategy,
27 _LinearFunction,
28)
29from hyper_parallel.models.replacement import module_replacement
32def _adopt_linear_parameters(target: nn.Linear, source: nn.Linear) -> None:
33 """Reuse source Linear parameters without temporary allocation."""
34 nn.Module.__init__(target) # pylint: disable=non-parent-init-called,unnecessary-dunder-call
35 target.in_features = source.in_features
36 target.out_features = source.out_features
37 target.register_parameter("weight", source.weight)
38 target.register_parameter("bias", source.bias)
41@module_replacement
42class Linear(nn.Linear):
43 """Baseline Dense replacement using ordinary torch linear computation."""
45 def __init__(
46 self,
47 *,
48 module: nn.Linear,
49 module_fqn: str = "",
50 context: Mapping[str, Any] | None = None,
51 ) -> None:
52 """Reuse parameters without allocating or initializing a second weight set.
54 Args:
55 module: Source Linear with loaded weight and optional bias.
56 module_fqn: Replacement path; unused by baseline computation.
57 context: Replacement context; unused by baseline computation.
58 """
59 del module_fqn, context
60 _adopt_linear_parameters(self, module)
61 self.train(module.training)
64class LowPrecisionLinear(nn.Linear):
65 """Preserve Linear state while delegating compute to one bound strategy."""
67 _hp_linear_compute_kind = "npu_quant"
69 def __init__(
70 self,
71 in_features: int,
72 out_features: int,
73 bias: bool = True,
74 *,
75 strategy: LinearStrategy,
76 ) -> None:
77 """Create a low-precision Linear with newly allocated Parameters."""
78 self._validate_strategy(strategy)
79 super().__init__(in_features, out_features, bias=bias)
80 self.strategy = strategy
82 @staticmethod
83 def _validate_strategy(strategy: LinearStrategy) -> None:
84 """Require a plain strategy so module registration stays unchanged."""
85 if isinstance(strategy, nn.Module) or not isinstance(strategy, LinearStrategy):
86 raise TypeError("strategy must be a non-Module LinearStrategy instance")
88 @classmethod
89 def from_linear(
90 cls,
91 linear: nn.Linear,
92 *,
93 strategy: LinearStrategy,
94 ) -> "LowPrecisionLinear":
95 """Create a shell retaining the source Parameters and training mode.
97 Args:
98 linear: Source Linear whose weight and optional bias are reused.
99 strategy: Low-precision compute strategy bound to the replacement.
101 Returns:
102 A new module sharing the source Parameters without reinitializing them.
103 """
104 cls._validate_strategy(strategy)
105 # object.__new__ is a static method; passing cls explicitly avoids the
106 # allocation and initialization performed by nn.Linear.__init__.
107 converted = cls.__new__(cls) # pylint: disable=no-value-for-parameter
108 _adopt_linear_parameters(converted, linear)
109 converted.strategy = strategy
110 converted.training = linear.training
111 return converted
113 def forward(self, input: torch.Tensor) -> torch.Tensor: # pylint: disable=redefined-builtin
114 """Apply the selected low-precision compute and high-precision bias."""
115 output = _LinearFunction.apply(input, self.weight, self.strategy)
116 if self.bias is not None:
117 output = output + self.bias
118 return output
121__all__ = ["Linear", "LowPrecisionLinear"]