| 1 | # SPDX-License-Identifier: Apache-2.0 |
| 2 | # SPDX-FileCopyrightText: Copyright contributors to the vLLM project |
| 3 | |
| 4 | import torch |
| 5 | |
| 6 | from vllm.model_executor.layers.quantization.utils.nvfp4_emulation_utils import ( |
| 7 | kE2M1ToFloat_handle, |
| 8 | run_nvfp4_emulations, |
| 9 | ) |
| 10 | |
| 11 | from .base import NvFp4LinearKernel, NvFp4LinearLayerConfig |
| 12 | |
| 13 | |
| 14 | class EmulationNvFp4LinearKernel(NvFp4LinearKernel): |
| 15 | """Software emulation fallback for NVFP4 (dequant → BF16 matmul).""" |
| 16 | |
| 17 | @classmethod |
| 18 | def is_supported( |
| 19 | cls, compute_capability: int | None = None |
| 20 | ) -> tuple[bool, str | None]: |
| 21 | # Always available as a last-resort fallback. |
| 22 | return True, None |
| 23 | |
| 24 | @classmethod |
| 25 | def can_implement(cls, config: NvFp4LinearLayerConfig) -> tuple[bool, str | None]: |
| 26 | return True, None |
| 27 | |
| 28 | def process_weights_after_loading(self, layer: torch.nn.Module) -> None: |
| 29 | # Move the E2M1 lookup table to the device now, because |
| 30 | # `.to(device)` is not allowed during CUDA graph capture. |
| 31 | kE2M1ToFloat_handle.val = kE2M1ToFloat_handle.val.to(layer.weight.device) |
| 32 | |
| 33 | def apply_weights( |
| 34 | self, |
| 35 | layer: torch.nn.Module, |
| 36 | x: torch.Tensor, |
| 37 | bias: torch.Tensor | None = None, |
| 38 | ) -> torch.Tensor: |
| 39 | out = run_nvfp4_emulations( |
| 40 | x=x, |
| 41 | input_global_scale=layer.input_global_scale_inv, |
| 42 | weight=layer.weight, |
| 43 | weight_scale_swizzled=layer.weight_scale, |
| 44 | weight_global_scale=layer.weight_global_scale, |
| 45 | swizzle=False, |
| 46 | ) |
| 47 | if bias is not None: |
| 48 | out = out + bias |
| 49 | return out |