| 1 | # SPDX-License-Identifier: Apache-2.0 |
| 2 | # SPDX-FileCopyrightText: Copyright contributors to the vLLM project |
| 3 | |
| 4 | from abc import ABC, abstractmethod |
| 5 | from collections.abc import Callable |
| 6 | from dataclasses import dataclass |
| 7 | |
| 8 | import torch |
| 9 | |
| 10 | from vllm.model_executor.layers.quantization.utils import replace_parameter |
| 11 | from vllm.scalar_type import ScalarType |
| 12 | |
| 13 | |
| 14 | @dataclass |
| 15 | class MPLinearLayerConfig: |
| 16 | full_weight_shape: tuple[int, int] # [in, out] |
| 17 | partition_weight_shape: tuple[int, int] |
| 18 | weight_type: ScalarType |
| 19 | act_type: torch.dtype |
| 20 | group_size: int |
| 21 | zero_points: bool |
| 22 | out_type: torch.dtype | None = None |
| 23 | |
| 24 | |
| 25 | class MPLinearKernel(ABC): |
| 26 | @classmethod |
| 27 | @abstractmethod |
| 28 | def get_min_capability(cls) -> int: |
| 29 | raise NotImplementedError |
| 30 | |
| 31 | @classmethod |
| 32 | @abstractmethod |
| 33 | def can_implement(cls, c: MPLinearLayerConfig) -> tuple[bool, str | None]: |
| 34 | raise NotImplementedError |
| 35 | |
| 36 | def __init__( |
| 37 | self, |
| 38 | c: MPLinearLayerConfig, |
| 39 | w_q_param_name: str, |
| 40 | w_s_param_name: str, |
| 41 | w_zp_param_name: str | None = None, |
| 42 | ) -> None: |
| 43 | assert self.can_implement(c) |
| 44 | self.config = c |
| 45 | self.w_q_name = w_q_param_name |
| 46 | self.w_s_name = w_s_param_name |
| 47 | if c.zero_points: |
| 48 | assert w_zp_param_name is not None |
| 49 | self.w_zp_name: str | None = w_zp_param_name |
| 50 | |
| 51 | @abstractmethod |
| 52 | def process_weights_after_loading(self, layer: torch.nn.Module) -> None: |
| 53 | raise NotImplementedError |
| 54 | |
| 55 | @abstractmethod |
| 56 | def apply_weights( |
| 57 | self, |
| 58 | layer: torch.nn.Module, |
| 59 | x: torch.Tensor, |
| 60 | bias: torch.Tensor | None = None, |
| 61 | ) -> torch.Tensor: |
| 62 | raise NotImplementedError |
| 63 | |
| 64 | def _transform_param( |
| 65 | self, layer: torch.nn.Module, name: str | None, fn: Callable |
| 66 | ) -> None: |
| 67 | if name is not None and getattr(layer, name, None) is not None: |
| 68 | old_param = getattr(layer, name) |
| 69 | new_param = fn(old_param) |
| 70 | # replace the parameter with torch.nn.Parameter for TorchDynamo |
| 71 | # compatibility |
| 72 | replace_parameter( |
| 73 | layer, name, torch.nn.Parameter(new_param.data, requires_grad=False) |
| 74 | ) |
| 75 | |
| 76 | def _get_weight_params( |
| 77 | self, layer: torch.nn.Module |
| 78 | ) -> tuple[ |
| 79 | torch.Tensor, # w_q |
| 80 | torch.Tensor, # w_s |
| 81 | torch.Tensor | None, # w_zp |
| 82 | ]: |
| 83 | return ( |
| 84 | getattr(layer, self.w_q_name), |
| 85 | getattr(layer, self.w_s_name), |
| 86 | getattr(layer, self.w_zp_name or "", None), |
| 87 | ) |