| 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 NvFp4LinearLayerConfig: |
| 14 | """Configuration for an NVFP4 linear layer. |
| 15 | |
| 16 | All NVFP4 layers share the same structure: packed uint8 weights (2 FP4 values per |
| 17 | byte), FP8-E4M3 per-block weight scales (group size 16), and scalar global |
| 18 | scales for both weights and activations. |
| 19 | """ |
| 20 | |
| 21 | pass |
| 22 | |
| 23 | |
| 24 | class NvFp4LinearKernel(ABC): |
| 25 | """Base class for NVFP4 quantized linear kernels. |
| 26 | |
| 27 | Each subclass implements a specific GEMM backend (CUTLASS, Marlin, etc). |
| 28 | The kernel selection mechanism iterates over registered subclasses in |
| 29 | priority order,calling ``is_supported`` and ``can_implement`` to find the best |
| 30 | match for the current hardware. |
| 31 | """ |
| 32 | |
| 33 | def __init__(self, config: NvFp4LinearLayerConfig) -> None: |
| 34 | assert self.can_implement(config)[0] |
| 35 | assert self.is_supported()[0] |
| 36 | self.config = config |
| 37 | |
| 38 | def input_quant_key(self) -> QuantKey | None: |
| 39 | """Return the input quantization key supported by this kernel. If the kernel |
| 40 | does not support input quantization outside of the kernel, return None. |
| 41 | """ |
| 42 | return None |
| 43 | |
| 44 | @classmethod |
| 45 | @abstractmethod |
| 46 | def is_supported( |
| 47 | cls, compute_capability: int | None = None |
| 48 | ) -> tuple[bool, str | None]: |
| 49 | """Return whether this kernel can run on the current platform.""" |
| 50 | raise NotImplementedError |
| 51 | |
| 52 | @classmethod |
| 53 | @abstractmethod |
| 54 | def can_implement(cls, config: NvFp4LinearLayerConfig) -> tuple[bool, str | None]: |
| 55 | """Return whether this kernel can handle *config*.""" |
| 56 | raise NotImplementedError |
| 57 | |
| 58 | @abstractmethod |
| 59 | def process_weights_after_loading(self, layer: torch.nn.Module) -> None: |
| 60 | """Transform weights into the format required by this kernel. |
| 61 | |
| 62 | Called once after checkpoint weights have been loaded onto the |
| 63 | device. Implementations should repack / swizzle / pad weights |
| 64 | and scales in-place on *layer*. |
| 65 | """ |
| 66 | raise NotImplementedError |
| 67 | |
| 68 | @abstractmethod |
| 69 | def apply_weights( |
| 70 | self, |
| 71 | layer: torch.nn.Module, |
| 72 | x: torch.Tensor, |
| 73 | bias: torch.Tensor | None = None, |
| 74 | ) -> torch.Tensor: |
| 75 | """Run the quantized GEMM.""" |
| 76 | raise NotImplementedError |