main
py 74 lines 2.33 KB
Raw
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 dataclasses import dataclass
6
7 import torch
8
9 from vllm.model_executor.layers.quantization.utils.quant_utils import QuantKey
10
11
12 @dataclass
13 class MxFp4LinearLayerConfig:
14 """Configuration for an MXFP4 linear layer.
15
16 All MXFP4 layers share the same structure: packed uint8 weights (2 FP4 values per
17 byte) and per-block weight scales (group size 32).
18
19 Attributes:
20 activation_quant_key: Identifies the activation quantization format,
21 or `None` when activations must not be quantized.
22
23 """
24
25 activation_quant_key: QuantKey | None = None
26
27
28 class MxFp4LinearKernel(ABC):
29 """Base class for MXFP4 quantized linear kernels.
30
31 Each subclass implements a specific GEMM backend (CUTLASS, Marlin, etc).
32 The kernel selection mechanism iterates over registered subclasses in
33 priority order,calling ``is_supported`` and ``can_implement`` to find the best
34 match for the current hardware.
35 """
36
37 def __init__(self, config: MxFp4LinearLayerConfig) -> None:
38 assert self.can_implement(config)[0]
39 assert self.is_supported()[0]
40 self.config = config
41
42 @classmethod
43 @abstractmethod
44 def is_supported(
45 cls, compute_capability: int | None = None
46 ) -> tuple[bool, str | None]:
47 """Return whether this kernel can run on the current platform."""
48 raise NotImplementedError
49
50 @classmethod
51 @abstractmethod
52 def can_implement(cls, config: MxFp4LinearLayerConfig) -> tuple[bool, str | None]:
53 """Return whether this kernel can handle *config*."""
54 raise NotImplementedError
55
56 @abstractmethod
57 def process_weights_after_loading(self, layer: torch.nn.Module) -> None:
58 """Transform weights into the format required by this kernel.
59
60 Called once after checkpoint weights have been loaded onto the
61 device. Implementations should repack / swizzle / pad weights
62 and scales in-place on *layer*.
63 """
64 raise NotImplementedError
65
66 @abstractmethod
67 def apply_weights(
68 self,
69 layer: torch.nn.Module,
70 x: torch.Tensor,
71 bias: torch.Tensor | None = None,
72 ) -> torch.Tensor:
73 """Run the quantized GEMM."""
74 raise NotImplementedError