diff --git a/docs/features/quantization/b12x.md b/docs/features/quantization/b12x.md new file mode 100644 index 0000000000..534bc6eb60 --- /dev/null +++ b/docs/features/quantization/b12x.md @@ -0,0 +1,24 @@ +# B12X Linear Backend + +[B12X](https://pypi.org/project/b12x/) provides optional CUDA kernels for +NVIDIA SM120 and SM121 GPUs. Install the dependency with: + +```bash +uv pip install "vllm[b12x]" +``` + +B12X participates in automatic kernel selection after established optimized +backends and before emulation. Select it explicitly with: + +```bash +vllm serve --linear-backend b12x +``` + +## Supported Configurations + +| Backend | Supported configurations | +| ------- | ------------------------ | +| Linear | Per-tensor FP8, 128x128 block FP8, MXFP8, NVFP4, and MXFP4 | + +Dense W4A16 layers are not handled by B12X and continue to use another +compatible backend such as Marlin. diff --git a/setup.py b/setup.py index 680376d512..24bff16ff6 100644 --- a/setup.py +++ b/setup.py @@ -1291,6 +1291,7 @@ setup( # only; also needs system GStreamer + libv4l (see docs). "deepstream": ["nvidia-deepstream-videodecode-cu13>=9.0.2"], "flashinfer": [], # Kept for backwards compatibility + "b12x": ["b12x==1.2.4"], # Optional deps for Helion kernel development # NOTE: When updating helion version, also update CI files: # - .buildkite/test_areas/kernels.yaml diff --git a/tests/kernels/quantization/test_block_fp8.py b/tests/kernels/quantization/test_block_fp8.py index 9b41765de6..6f86aed59e 100644 --- a/tests/kernels/quantization/test_block_fp8.py +++ b/tests/kernels/quantization/test_block_fp8.py @@ -14,6 +14,10 @@ from tests.kernels.quant_utils import ( ) from tests.kernels.utils import fp8_ulp_distance from vllm.config import VllmConfig +from vllm.model_executor.kernels.linear.scaled_mm.b12x_block import ( + B12xFp8BlockScaledMMKernel, + _run_b12x_fp8_block_scaled_mm, +) from vllm.model_executor.kernels.linear.scaled_mm.cutlass import cutlass_scaled_mm from vllm.model_executor.layers.quantization.utils.fp8_utils import ( per_token_group_quant_fp8, @@ -353,3 +357,54 @@ def test_w8a8_block_fp8_flashinfer_matmul(M, N, K, block_size, out_dtype, seed): torch.abs(out.to(torch.bfloat16) - ref_out.to(torch.bfloat16)) ) / torch.mean(torch.abs(ref_out.to(torch.bfloat16))) assert rel_diff < 0.001 + + +@pytest.mark.parametrize( + "M,N,K", + [(1, 128, 256), (8, 256, 512), (129, 256, 256), (2, 4096, 4096)], +) +@torch.inference_mode() +def test_w8a8_block_fp8_b12x_matmul(M, N, K): + supported, reason = B12xFp8BlockScaledMMKernel.is_supported() + if not supported: + pytest.skip(reason) + + torch.manual_seed(M) + fp8_max = torch.finfo(torch.float8_e4m3fn).max + A_bf16 = (torch.rand(M, K, dtype=torch.bfloat16) - 0.5) * 2 * fp8_max + B_bf16 = (torch.rand(N, K, dtype=torch.bfloat16) - 0.5) * 2 * fp8_max + A_fp8, As = per_token_group_quant_fp8(A_bf16, 128, use_ue8m0=False) + B_fp8, Bs = per_block_cast_to_fp8( + B_bf16, + block_size=[128, 128], + use_ue8m0=False, + ) + As = As.float() + Bs = Bs.float() + + ref_out = native_w8a8_block_matmul( + A_fp8, + B_fp8, + As, + Bs, + [128, 128], + torch.bfloat16, + ) + out = _run_b12x_fp8_block_scaled_mm( + A_fp8, + B_fp8, + As, + Bs, + torch.bfloat16, + ) + + rel_diff = torch.mean(torch.abs(out.float() - ref_out.float())) / torch.mean( + torch.abs(ref_out.float()) + ) + cosine = torch.nn.functional.cosine_similarity( + out.float().flatten(), + ref_out.float().flatten(), + dim=0, + ) + assert rel_diff < 0.002 + assert cosine >= 0.9999 diff --git a/tests/model_executor/kernels/test_b12x_mxfp4_linear.py b/tests/model_executor/kernels/test_b12x_mxfp4_linear.py new file mode 100644 index 0000000000..7ba1aad817 --- /dev/null +++ b/tests/model_executor/kernels/test_b12x_mxfp4_linear.py @@ -0,0 +1,199 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +from __future__ import annotations + +import types + +import torch + +from vllm.model_executor.kernels.linear import ( + _LINEAR_BACKEND_KERNEL_MAP, + _POSSIBLE_MXFP4_KERNELS, + init_mxfp4_linear_kernel, +) +from vllm.model_executor.kernels.linear.mxfp4.b12x import ( + B12xMxFp4LinearKernel, + warmup_b12x_mxfp4_linear, +) +from vllm.model_executor.layers.quantization.utils.quant_utils import ( + kMxfp4Dynamic, +) +from vllm.platforms import PlatformEnum + + +def test_b12x_backend_maps_mxfp4_kernel() -> None: + assert B12xMxFp4LinearKernel in _LINEAR_BACKEND_KERNEL_MAP["b12x"] + assert B12xMxFp4LinearKernel in _POSSIBLE_MXFP4_KERNELS[PlatformEnum.CUDA] + + +def test_b12x_mxfp4_fallback_priority() -> None: + kernels = _POSSIBLE_MXFP4_KERNELS[PlatformEnum.CUDA] + names = [kernel.__name__ for kernel in kernels] + + assert ( + names.index("HummingMxFp4LinearKernel") + < names.index("B12xMxFp4LinearKernel") + < names.index("EmulationMxfp4LinearKernel") + ) + + +def test_b12x_mxfp4_explicit_backend_selects_native_kernel(monkeypatch) -> None: + import vllm.model_executor.kernels.linear as linear_mod + + monkeypatch.setattr(linear_mod.current_platform, "_enum", PlatformEnum.CUDA) + monkeypatch.setattr(linear_mod, "_get_linear_backend", lambda: "b12x") + monkeypatch.setattr( + B12xMxFp4LinearKernel, + "is_supported", + classmethod(lambda cls, compute_capability=None: (True, None)), + ) + monkeypatch.setattr( + B12xMxFp4LinearKernel, + "can_implement", + classmethod(lambda cls, config: (True, None)), + ) + + kernel = init_mxfp4_linear_kernel(activation_quant_key=kMxfp4Dynamic) + + assert isinstance(kernel, B12xMxFp4LinearKernel) + + +def test_b12x_mxfp4_requires_dynamic_activations() -> None: + config = types.SimpleNamespace(activation_quant_key=kMxfp4Dynamic) + can_implement, reason = B12xMxFp4LinearKernel.can_implement(config) + + assert can_implement + assert reason is None + + config.activation_quant_key = None + can_implement, reason = B12xMxFp4LinearKernel.can_implement(config) + + assert not can_implement + assert reason == "B12X MXFP4 GEMM requires dynamic MXFP4 activations" + + +def test_b12x_mxfp4_processes_scale_and_preserves_loader(monkeypatch) -> None: + import vllm.model_executor.kernels.linear.mxfp4.b12x as b12x_mod + + scale = torch.empty((48, 8), dtype=torch.uint8) + swizzled_scale = torch.empty((128, 8), dtype=torch.uint8) + monkeypatch.setattr( + b12x_mod, + "_import_b12x_intrinsics", + lambda: types.SimpleNamespace(swizzle_block_scale=lambda value: swizzled_scale), + ) + + layer = torch.nn.Module() + layer.prefix = "model.layers.0.mlp.shared_expert.down_proj" + layer.weight_scale = torch.nn.Parameter(scale, requires_grad=False) + weight_loader = object() + layer.weight_scale.weight_loader = weight_loader + kernel = object.__new__(B12xMxFp4LinearKernel) + + kernel.process_weights_after_loading(layer) + + assert layer.weight_scale.data_ptr() == swizzled_scale.data_ptr() + assert layer.weight_scale.weight_loader is weight_loader + assert layer.b12x_mxfp4_linear + + +def test_b12x_mxfp4_apply_calls_native_blockscaled_gemm(monkeypatch) -> None: + import vllm.model_executor.kernels.linear.mxfp4.b12x as b12x_mod + import vllm.utils.flashinfer as flashinfer_utils + + calls: list[tuple] = [] + x_packed = torch.empty((6, 64), dtype=torch.uint8) + x_scale_storage = torch.empty((128, 4), dtype=torch.uint8) + + def mm_mxfp4(*args, **kwargs): + calls.append((args, kwargs)) + return torch.full((6, 48), 3.0, dtype=torch.bfloat16) + + monkeypatch.setattr( + flashinfer_utils, + "flashinfer_mxfp4_quantize", + lambda *args, **kwargs: (x_packed, x_scale_storage), + ) + monkeypatch.setattr( + b12x_mod, + "_import_b12x_blockscaled", + lambda: types.SimpleNamespace(mm_mxfp4=mm_mxfp4), + ) + + layer = torch.nn.Module() + layer.output_size_per_partition = 48 + layer.weight = torch.empty((48, 64), dtype=torch.uint8) + layer.weight_scale = torch.empty((128, 4), dtype=torch.uint8) + x = torch.empty((2, 3, 128), dtype=torch.bfloat16) + bias = torch.ones(48, dtype=torch.bfloat16) + kernel = object.__new__(B12xMxFp4LinearKernel) + + output = kernel.apply_weights(layer, x, bias) + + assert output.shape == (2, 3, 48) + torch.testing.assert_close(output, torch.full_like(output, 4.0)) + assert len(calls) == 1 + args, kwargs = calls[0] + assert args == ( + x_packed, + x_scale_storage, + layer.weight, + layer.weight_scale, + ) + assert kwargs == {"out_dtype": torch.bfloat16} + + +def test_warmup_b12x_mxfp4_dedupes_weight_signatures(monkeypatch) -> None: + import vllm.model_executor.kernels.linear.mxfp4.b12x as b12x_mod + + calls = [] + + def apply(source, weight, weight_scale, bias): + calls.append((source.shape, weight, weight_scale, bias)) + return source.new_empty((source.shape[0], weight.shape[0])) + + platform = types.SimpleNamespace( + is_cuda=lambda: True, + is_device_capability_family=lambda family: family == 120, + ) + monkeypatch.setattr(b12x_mod, "current_platform", platform) + monkeypatch.setattr( + b12x_mod, + "_import_b12x_blockscaled", + lambda: types.SimpleNamespace(), + ) + monkeypatch.setattr(b12x_mod, "_apply_b12x_mxfp4_linear", apply) + + def layer(n: int): + return types.SimpleNamespace( + b12x_mxfp4_linear=True, + weight=torch.empty((n, 64), dtype=torch.uint8), + weight_scale=torch.empty((128, 4), dtype=torch.uint8), + ) + + layer_a = layer(48) + layer_b = layer(48) + layer_c = layer(96) + model = types.SimpleNamespace( + modules=lambda: iter([layer_a, layer_b, layer_c, types.SimpleNamespace()]) + ) + + warmed = warmup_b12x_mxfp4_linear( + model, + max_tokens=8, + cudagraph_capture_sizes=[1, 2], + ) + + assert warmed == 6 + assert [call[0] for call in calls] == [ + torch.Size([1, 128]), + torch.Size([2, 128]), + torch.Size([8, 128]), + torch.Size([1, 128]), + torch.Size([2, 128]), + torch.Size([8, 128]), + ] + assert calls[0][1] is layer_a.weight + assert calls[3][1] is layer_c.weight + assert all(call[3] is None for call in calls) diff --git a/tests/model_executor/kernels/test_b12x_mxfp8_linear.py b/tests/model_executor/kernels/test_b12x_mxfp8_linear.py new file mode 100644 index 0000000000..f1525b971b --- /dev/null +++ b/tests/model_executor/kernels/test_b12x_mxfp8_linear.py @@ -0,0 +1,935 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +from __future__ import annotations + +import types +from dataclasses import dataclass + +import pytest +import torch + +from vllm.model_executor.kernels.linear import ( + _LINEAR_BACKEND_KERNEL_MAP, + _POSSIBLE_FP8_BLOCK_KERNELS, + _POSSIBLE_FP8_KERNELS, + _POSSIBLE_MXFP8_KERNELS, + init_fp8_linear_kernel, + init_mxfp8_linear_kernel, +) +from vllm.model_executor.kernels.linear.mxfp8.b12x import ( + B12xMxfp8LinearKernel, + _b12x_mxfp8_expected_m, + warmup_b12x_mxfp8_linear, +) +from vllm.model_executor.kernels.linear.mxfp8.Mxfp8LinearKernel import ( + Mxfp8LinearLayerConfig, +) +from vllm.model_executor.kernels.linear.scaled_mm.b12x_block import ( + B12xFp8BlockScaledMMKernel, + _run_b12x_fp8_block_scaled_mm, + warmup_b12x_block_fp8_linear, +) +from vllm.model_executor.kernels.linear.scaled_mm.b12x_tensor import ( + B12xTensorFP8ScaledMMLinearKernel, + warmup_b12x_tensor_fp8_linear, +) +from vllm.model_executor.kernels.linear.scaled_mm.ScaledMMLinearKernel import ( + FP8ScaledMMLinearLayerConfig, +) +from vllm.model_executor.layers.linear import ( + ReplicatedLinear, + UnquantizedLinearMethod, +) +from vllm.model_executor.layers.quantization.utils.quant_utils import ( + kFp8Dynamic128Sym, + kFp8Static128BlockSym, + kFp8StaticTensorSym, +) +from vllm.platforms import PlatformEnum +from vllm.utils.b12x import b12x_warmup_token_counts + + +def test_b12x_backend_maps_mxfp8_kernel() -> None: + assert B12xMxfp8LinearKernel in _LINEAR_BACKEND_KERNEL_MAP["b12x"] + assert B12xMxfp8LinearKernel in _POSSIBLE_MXFP8_KERNELS[PlatformEnum.CUDA] + + +def test_b12x_backend_maps_tensor_fp8_kernel() -> None: + assert B12xTensorFP8ScaledMMLinearKernel in _LINEAR_BACKEND_KERNEL_MAP["b12x"] + assert B12xTensorFP8ScaledMMLinearKernel in _POSSIBLE_FP8_KERNELS[PlatformEnum.CUDA] + + +@pytest.mark.parametrize( + ("kernels", "before", "b12x", "after"), + [ + ( + _POSSIBLE_FP8_KERNELS[PlatformEnum.CUDA], + "CutlassFP8ScaledMMLinearKernel", + "B12xTensorFP8ScaledMMLinearKernel", + "PerTensorTorchFP8ScaledMMLinearKernel", + ), + ( + _POSSIBLE_FP8_BLOCK_KERNELS[PlatformEnum.CUDA], + "CutlassFp8BlockScaledMMKernel", + "B12xFp8BlockScaledMMKernel", + "MarlinFP8ScaledMMLinearKernel", + ), + ( + _POSSIBLE_MXFP8_KERNELS[PlatformEnum.CUDA], + "MarlinMxfp8LinearKernel", + "B12xMxfp8LinearKernel", + "EmulationMxfp8LinearKernel", + ), + ], +) +def test_b12x_fp8_fallback_priority( + kernels: list[type], + before: str, + b12x: str, + after: str, +) -> None: + names = [kernel.__name__ for kernel in kernels] + + assert names.index(before) < names.index(b12x) < names.index(after) + + +@torch.inference_mode() +def test_b12x_backend_does_not_intercept_unquantized_bf16( + default_vllm_config, + dist_init, +) -> None: + default_vllm_config.kernel_config.linear_backend = "b12x" + layer = ReplicatedLinear( + 128, + 64, + bias=False, + params_dtype=torch.bfloat16, + quant_config=None, + prefix="bf16_linear", + ).cuda() + layer.weight.data.normal_() + x = torch.randn(8, 128, device="cuda", dtype=torch.bfloat16) + + output, output_bias = layer(x) + expected = torch.nn.functional.linear(x, layer.weight) + + assert isinstance(layer.quant_method, UnquantizedLinearMethod) + assert output_bias is None + torch.testing.assert_close(output, expected) + + +def test_b12x_explicit_backend_selects_per_tensor_fp8( + monkeypatch, + default_vllm_config, +) -> None: + import vllm.model_executor.kernels.linear as linear_mod + + monkeypatch.setattr(linear_mod.current_platform, "_enum", PlatformEnum.CUDA) + monkeypatch.setattr(linear_mod, "_get_linear_backend", lambda: "b12x") + monkeypatch.setattr( + B12xTensorFP8ScaledMMLinearKernel, + "is_supported", + classmethod(lambda cls, compute_capability=None: (True, None)), + ) + monkeypatch.setattr( + B12xTensorFP8ScaledMMLinearKernel, + "can_implement", + classmethod(lambda cls, config: (True, None)), + ) + + kernel = init_fp8_linear_kernel( + activation_quant_key=kFp8StaticTensorSym, + weight_quant_key=kFp8StaticTensorSym, + input_dtype=torch.bfloat16, + out_dtype=torch.bfloat16, + weight_shape=(2048, 2048), + ) + + assert isinstance(kernel, B12xTensorFP8ScaledMMLinearKernel) + + +def test_b12x_tensor_fp8_can_implement_supported_config() -> None: + config = FP8ScaledMMLinearLayerConfig( + activation_quant_key=kFp8StaticTensorSym, + weight_quant_key=kFp8StaticTensorSym, + weight_shape=(64, 128), + input_dtype=torch.bfloat16, + out_dtype=torch.bfloat16, + ) + + can_implement, reason = B12xTensorFP8ScaledMMLinearKernel.can_implement(config) + + assert can_implement + assert reason is None + + +def test_b12x_explicit_backend_selects_block_fp8( + monkeypatch, + default_vllm_config, +) -> None: + import vllm.model_executor.kernels.linear as linear_mod + + monkeypatch.setattr(linear_mod.current_platform, "_enum", PlatformEnum.CUDA) + monkeypatch.setattr(linear_mod, "_get_linear_backend", lambda: "b12x") + monkeypatch.setattr( + B12xFp8BlockScaledMMKernel, + "is_supported", + classmethod(lambda cls, compute_capability=None: (True, None)), + ) + + kernel = init_fp8_linear_kernel( + activation_quant_key=kFp8Dynamic128Sym, + weight_quant_key=kFp8Static128BlockSym, + input_dtype=torch.bfloat16, + out_dtype=torch.bfloat16, + weight_shape=(2048, 2048), + ) + + assert isinstance(kernel, B12xFp8BlockScaledMMKernel) + + +def test_b12x_block_fp8_checks_runtime_support(monkeypatch) -> None: + import vllm.model_executor.kernels.linear.scaled_mm.b12x_block as b12x_mod + + platform = types.SimpleNamespace( + is_cuda=lambda: True, + is_device_capability_family=lambda family: family == 120, + ) + monkeypatch.setattr(b12x_mod, "current_platform", platform) + + monkeypatch.setattr( + b12x_mod, + "_import_b12x_blockscaled", + lambda: types.SimpleNamespace(is_supported=lambda: False), + ) + + supported, reason = B12xFp8BlockScaledMMKernel.is_supported() + + assert not supported + assert reason == "B12X regular block-FP8 GEMM is not supported" + + +def test_b12x_block_fp8_requires_matching_supported_dtypes() -> None: + def config(input_dtype: torch.dtype, out_dtype: torch.dtype): + return FP8ScaledMMLinearLayerConfig( + activation_quant_key=kFp8Dynamic128Sym, + weight_quant_key=kFp8Static128BlockSym, + weight_shape=(256, 128), + input_dtype=input_dtype, + out_dtype=out_dtype, + ) + + can_implement, reason = B12xFp8BlockScaledMMKernel.can_implement( + config(torch.float32, torch.float32) + ) + assert not can_implement + assert reason == "Supports only bf16/fp16 input dtype" + + can_implement, reason = B12xFp8BlockScaledMMKernel.can_implement( + config(torch.bfloat16, torch.float16) + ) + assert not can_implement + assert reason == "Input and output dtype must match" + + can_implement, reason = B12xFp8BlockScaledMMKernel.can_implement( + config(torch.float16, torch.float16) + ) + assert can_implement + assert reason is None + + +def test_b12x_block_fp8_requires_aligned_features() -> None: + def can_implement(weight_shape: tuple[int, int]): + config = FP8ScaledMMLinearLayerConfig( + activation_quant_key=kFp8Dynamic128Sym, + weight_quant_key=kFp8Static128BlockSym, + weight_shape=weight_shape, + input_dtype=torch.bfloat16, + out_dtype=torch.bfloat16, + ) + return B12xFp8BlockScaledMMKernel.can_implement(config) + + assert can_implement((256, 192)) == ( + False, + "Input features must be a positive multiple of 128", + ) + assert can_implement((192, 256)) == ( + False, + "Output features must be a positive multiple of 128", + ) + + +def test_b12x_warmup_token_counts_cover_serving_regimes() -> None: + assert b12x_warmup_token_counts( + max_tokens=2048, + cudagraph_capture_sizes=[1, 2, 8, 128], + ) == (1, 2, 8, 128, 2048) + + +def test_warmup_b12x_block_fp8_dedupes_weight_signatures(monkeypatch) -> None: + import vllm.model_executor.kernels.linear.scaled_mm.b12x_block as b12x_mod + + calls = [] + + def run(a, weight, a_scale, weight_scale, out_dtype): + calls.append((a.shape, weight, a_scale.shape, weight_scale, out_dtype)) + return torch.empty((a.shape[0], weight.shape[0]), dtype=out_dtype) + + platform = types.SimpleNamespace( + is_cuda=lambda: True, + is_device_capability_family=lambda family: family == 120, + ) + monkeypatch.setattr(b12x_mod, "current_platform", platform) + + monkeypatch.setattr( + b12x_mod, + "_import_b12x_blockscaled", + lambda: types.SimpleNamespace(), + ) + monkeypatch.setattr(b12x_mod, "_run_b12x_fp8_block_scaled_mm", run) + + def layer(in_features: int, out_features: int): + return types.SimpleNamespace( + b12x_block_fp8_linear=True, + weight=torch.empty((out_features, in_features), dtype=torch.float8_e4m3fn), + weight_scale_inv=torch.empty( + (out_features // 128, in_features // 128), dtype=torch.float32 + ), + ) + + layer_a = layer(128, 256) + layer_b = layer(256, 128) + modules = [ + layer_a, + layer_a, + layer_b, + types.SimpleNamespace(), + ] + model = types.SimpleNamespace(modules=lambda: iter(modules)) + + warmed = warmup_b12x_block_fp8_linear( + model, + max_tokens=32, + cudagraph_capture_sizes=[2, 8], + output_dtype=torch.bfloat16, + ) + + assert warmed == 8 + assert [call[0][0] for call in calls] == [1, 2, 8, 32] * 2 + assert [call[2][0] for call in calls] == [1, 2, 8, 32] * 2 + assert calls[0][1] is layer_a.weight + assert calls[4][1] is layer_b.weight + assert calls[0][3] is layer_a.weight_scale_inv + assert calls[4][3] is layer_b.weight_scale_inv + assert all(call[4] == torch.bfloat16 for call in calls) + + +def test_b12x_tensor_fp8_process_weights_packs_modelopt_layout( + monkeypatch, +) -> None: + import vllm.model_executor.kernels.linear.scaled_mm.b12x_tensor as b12x_mod + + calls = [] + packed = types.SimpleNamespace(out_features=64) + + def pack(weight: torch.Tensor, output_scale: torch.Tensor): + calls.append((weight, output_scale)) + return packed + + monkeypatch.setattr( + b12x_mod, + "_import_b12x_tensor_fp8", + lambda: types.SimpleNamespace(pack_weight=pack), + ) + layer = torch.nn.Module() + layer.prefix = "model.layers.0.self_attn.qkv_proj" + original_weight = ( + torch.randn((128, 64), dtype=torch.float32).clamp(-4, 4).to(torch.float8_e4m3fn) + ) + layer.weight = torch.nn.Parameter(original_weight, requires_grad=False) + layer.weight_scale = torch.nn.Parameter(torch.tensor(0.25), requires_grad=False) + layer.input_scale = torch.nn.Parameter(torch.tensor(0.5), requires_grad=False) + weight_loader = object() + scale_loader = object() + layer.weight.weight_loader = weight_loader + layer.weight_scale.weight_loader = scale_loader + kernel = object.__new__(B12xTensorFP8ScaledMMLinearKernel) + kernel.config = types.SimpleNamespace(weight_shape=(64, 128)) + kernel.layer_param_names = ( + "weight", + "weight_scale", + "input_scale", + "input_scale_ub", + ) + + kernel.process_weights_after_loading(layer) + + assert layer.b12x_tensor_fp8_packed_weight is packed + assert len(calls) == 1 + weight, output_scale = calls[0] + torch.testing.assert_close(weight, original_weight.T.contiguous()) + torch.testing.assert_close(output_scale, torch.tensor([0.125])) + assert layer.weight.numel() == 0 + assert layer.weight_scale.numel() == 0 + assert layer.weight.weight_loader is weight_loader + assert layer.weight_scale.weight_loader is scale_loader + torch.testing.assert_close(layer.input_scale, torch.tensor(0.5)) + + +def test_warmup_b12x_tensor_fp8_dedupes_weight_signatures(monkeypatch) -> None: + import vllm.model_executor.kernels.linear.scaled_mm.b12x_tensor as b12x_mod + + calls = [] + + def prewarm(packed_weight, token_counts, *, out_dtype, stream): + del stream + calls.append((packed_weight, tuple(token_counts), out_dtype)) + return len(tuple(token_counts)) + + platform = types.SimpleNamespace( + is_cuda=lambda: True, + is_device_capability_family=lambda family: family == 120, + ) + monkeypatch.setattr(b12x_mod, "current_platform", platform) + monkeypatch.setattr( + b12x_mod, + "_import_b12x_tensor_fp8", + lambda: types.SimpleNamespace(prewarm=prewarm), + ) + monkeypatch.setattr( + b12x_mod, + "current_stream", + lambda: types.SimpleNamespace(cuda_stream=object()), + ) + + def packed(in_features: int, padded_in_features: int, out_features: int): + return types.SimpleNamespace( + in_features=in_features, + padded_in_features=padded_in_features, + out_features=out_features, + values=torch.empty(1), + ) + + packed_a = packed(128, 128, 256) + packed_b = packed(160, 256, 512) + modules = [ + types.SimpleNamespace(b12x_tensor_fp8_packed_weight=packed_a), + types.SimpleNamespace(b12x_tensor_fp8_packed_weight=packed_a), + types.SimpleNamespace(b12x_tensor_fp8_packed_weight=packed_b), + types.SimpleNamespace(), + ] + model = types.SimpleNamespace(modules=lambda: iter(modules)) + + warmed = warmup_b12x_tensor_fp8_linear( + model, + max_tokens=2048, + cudagraph_capture_sizes=[1, 2], + ) + + assert warmed == 6 + assert calls == [ + (packed_a, (1, 2, 2048), torch.bfloat16), + (packed_b, (1, 2, 2048), torch.bfloat16), + ] + + +def test_b12x_tensor_fp8_apply_quantizes_and_uses_packed_weight( + monkeypatch, +) -> None: + import vllm.model_executor.kernels.linear.scaled_mm.b12x_tensor as b12x_mod + + calls = [] + + def mm( + source: torch.Tensor, + packed_weight, + *, + bias: torch.Tensor | None = None, + out_dtype: torch.dtype, + expected_m: int, + stream: object = None, + ) -> torch.Tensor: + del stream + calls.append((source, packed_weight, bias, out_dtype, expected_m)) + return torch.full( + (source.shape[0], packed_weight.out_features), + 3.0, + dtype=out_dtype, + ) + + monkeypatch.setattr( + b12x_mod, + "_import_b12x_tensor_fp8", + lambda: types.SimpleNamespace(mm=mm), + ) + monkeypatch.setattr( + b12x_mod, + "current_stream", + lambda: types.SimpleNamespace(cuda_stream=object()), + ) + monkeypatch.setattr(torch.compiler, "is_compiling", lambda: False) + + layer = torch.nn.Module() + packed = types.SimpleNamespace(out_features=48) + layer.b12x_tensor_fp8_packed_weight = packed + layer.weight = torch.nn.Parameter( + torch.empty((128, 48), dtype=torch.float8_e4m3fn), + requires_grad=False, + ) + layer.weight_scale = torch.nn.Parameter(torch.tensor(0.25), requires_grad=False) + layer.input_scale = torch.nn.Parameter(torch.tensor(0.5), requires_grad=False) + x = torch.empty((2, 3, 128), dtype=torch.bfloat16) + x_q = torch.empty((6, 128), dtype=torch.float8_e4m3fn) + bias = torch.empty((48,), dtype=torch.bfloat16) + kernel = object.__new__(B12xTensorFP8ScaledMMLinearKernel) + kernel.config = types.SimpleNamespace(out_dtype=torch.bfloat16) + kernel.layer_param_names = ( + "weight", + "weight_scale", + "input_scale", + "input_scale_ub", + ) + kernel.quant_fp8 = lambda source, scale, scale_ub: (x_q, scale) + + output = kernel.apply_weights(layer, x, bias) + + assert output.shape == (2, 3, 48) + assert output.dtype == torch.bfloat16 + assert len(calls) == 1 + source, called_packed, called_bias, out_dtype, expected_m = calls[0] + assert source.data_ptr() == x_q.data_ptr() + assert called_packed is packed + assert called_bias is bias + assert out_dtype == torch.bfloat16 + assert expected_m == 6 + + +def test_b12x_mxfp8_explicit_backend_selects_kernel(monkeypatch) -> None: + import vllm.model_executor.kernels.linear as linear_mod + + monkeypatch.setattr(linear_mod.current_platform, "_enum", PlatformEnum.CUDA) + monkeypatch.setattr(linear_mod, "_get_linear_backend", lambda: "b12x") + monkeypatch.setattr( + B12xMxfp8LinearKernel, + "is_supported", + classmethod(lambda cls, compute_capability=None: (True, None)), + ) + monkeypatch.setattr( + B12xMxfp8LinearKernel, + "can_implement", + classmethod(lambda cls, c: (True, None)), + ) + + kernel = init_mxfp8_linear_kernel() + + assert isinstance(kernel, B12xMxfp8LinearKernel) + + +def test_b12x_mxfp8_can_implement_supported_config() -> None: + can_implement, reason = B12xMxfp8LinearKernel.can_implement( + Mxfp8LinearLayerConfig() + ) + + assert can_implement + assert reason is None + + +def test_b12x_mxfp8_expected_m_uses_live_m() -> None: + assert _b12x_mxfp8_expected_m(0) == 1 + assert _b12x_mxfp8_expected_m(1) == 1 + assert _b12x_mxfp8_expected_m(2) == 2 + assert _b12x_mxfp8_expected_m(8) == 8 + assert _b12x_mxfp8_expected_m(9) == 9 + assert _b12x_mxfp8_expected_m(128) == 128 + assert _b12x_mxfp8_expected_m(129) == 129 + assert _b12x_mxfp8_expected_m(2048) == 2048 + + +def test_warmup_b12x_mxfp8_linear_dedupes_weight_signatures( + monkeypatch, +) -> None: + import vllm.model_executor.kernels.linear.mxfp8.b12x as b12x_mod + + calls = [] + + def mm( + source: torch.Tensor, + packed_weight, + *, + bias: torch.Tensor | None = None, + expected_m: int | None = None, + stream: object = None, + ) -> torch.Tensor: + del stream + calls.append((source.shape, packed_weight, bias, expected_m)) + return source.new_empty((source.shape[0], packed_weight.out_features)) + + platform = types.SimpleNamespace( + is_cuda=lambda: True, + is_device_capability_family=lambda family: family == 120, + ) + monkeypatch.setattr(b12x_mod, "current_platform", platform) + monkeypatch.setattr( + b12x_mod, + "_import_b12x_mxfp8", + lambda: types.SimpleNamespace(mm=mm), + ) + monkeypatch.setattr( + b12x_mod, + "current_stream", + lambda: types.SimpleNamespace(cuda_stream=object()), + ) + + def packed(in_features: int, padded_in_features: int, out_features: int): + return types.SimpleNamespace( + in_features=in_features, + padded_in_features=padded_in_features, + out_features=out_features, + weight=types.SimpleNamespace(values=torch.empty(1)), + ) + + packed_a = packed(128, 128, 256) + packed_b = packed(128, 128, 512) + modules = [ + types.SimpleNamespace(b12x_mxfp8_packed_weight=packed_a), + types.SimpleNamespace(b12x_mxfp8_packed_weight=packed_a), + types.SimpleNamespace(b12x_mxfp8_packed_weight=packed_b), + types.SimpleNamespace(), + ] + model = types.SimpleNamespace(modules=lambda: iter(modules)) + + warmed = warmup_b12x_mxfp8_linear( + model, + max_tokens=2048, + cudagraph_capture_sizes=[1, 2], + ) + + assert warmed == 6 + assert [call[0] for call in calls] == [ + torch.Size([1, 128]), + torch.Size([2, 128]), + torch.Size([2048, 128]), + torch.Size([1, 128]), + torch.Size([2, 128]), + torch.Size([2048, 128]), + ] + assert [call[3] for call in calls] == [1, 2, 2048, 1, 2, 2048] + assert calls[0][1] is packed_a + assert calls[3][1] is packed_b + + +def test_b12x_mxfp8_support_check_reports_missing_import(monkeypatch) -> None: + import vllm.model_executor.kernels.linear.mxfp8.b12x as b12x_mod + + monkeypatch.setattr(b12x_mod.current_platform, "is_cuda", lambda: True) + monkeypatch.setattr( + b12x_mod.current_platform, + "is_device_capability_family", + lambda family: family == 120, + ) + monkeypatch.setattr(b12x_mod, "_import_b12x_mxfp8", lambda: None) + + is_supported, reason = B12xMxfp8LinearKernel.is_supported() + + assert not is_supported + assert reason == "Install the B12X backend with `pip install vllm[b12x]`" + + +def test_b12x_mxfp8_support_respects_runtime_probe(monkeypatch) -> None: + import vllm.model_executor.kernels.linear.mxfp8.b12x as b12x_mod + + monkeypatch.setattr(b12x_mod.current_platform, "is_cuda", lambda: True) + monkeypatch.setattr( + b12x_mod.current_platform, + "is_device_capability_family", + lambda family: family == 120, + ) + monkeypatch.setattr( + b12x_mod, + "_import_b12x_mxfp8", + lambda: types.SimpleNamespace(is_supported=lambda: False), + ) + + is_supported, reason = B12xMxfp8LinearKernel.is_supported() + + assert not is_supported + assert reason == "b12x.gemm.mxfp8_linear is not supported" + + +def test_b12x_mxfp8_process_weights_packs_modelopt_layout(monkeypatch) -> None: + import vllm.model_executor.kernels.linear.mxfp8.b12x as b12x_mod + + calls = [] + packed = types.SimpleNamespace(out_features=48) + + def pack(weight: torch.Tensor, weight_scale: torch.Tensor): + calls.append((weight, weight_scale)) + return packed + + monkeypatch.setattr( + b12x_mod, + "_import_b12x_mxfp8", + lambda: types.SimpleNamespace(pack_weight=pack), + ) + + layer = torch.nn.Module() + layer.prefix = "model.layers.0.self_attn.qkv_proj" + layer.weight = torch.nn.Parameter( + torch.empty((48, 128), dtype=torch.float8_e4m3fn), + requires_grad=False, + ) + layer.weight_scale = torch.nn.Parameter( + torch.empty((64, 8), dtype=torch.uint8), + requires_grad=False, + ) + weight_loader = object() + scale_loader = object() + layer.weight.weight_loader = weight_loader + layer.weight_scale.weight_loader = scale_loader + kernel = object.__new__(B12xMxfp8LinearKernel) + + kernel.process_weights_after_loading(layer) + + assert layer.b12x_mxfp8_packed_weight is packed + assert len(calls) == 1 + weight, weight_scale = calls[0] + assert weight.shape == (48, 128) + assert weight_scale.shape == (48, 4) + assert weight.dtype == torch.float8_e4m3fn + assert weight_scale.dtype == torch.uint8 + assert layer.weight.numel() == 0 + assert layer.weight_scale.numel() == 0 + assert layer.weight.weight_loader is weight_loader + assert layer.weight_scale.weight_loader is scale_loader + + +def test_b12x_mxfp8_reload_reuses_packed_tensor_addresses(monkeypatch) -> None: + import vllm.model_executor.kernels.linear.mxfp8.b12x as b12x_mod + + @dataclass(frozen=True) + class PackedWeight: + values: torch.Tensor + scales: torch.Tensor + out_features: int + + def pack(weight: torch.Tensor, weight_scale: torch.Tensor) -> PackedWeight: + return PackedWeight( + values=weight.clone(), + scales=weight_scale.clone(), + out_features=int(weight.shape[0]), + ) + + monkeypatch.setattr( + b12x_mod, + "_import_b12x_mxfp8", + lambda: types.SimpleNamespace(pack_weight=pack), + ) + layer = torch.nn.Module() + layer.prefix = "model.layers.0.mlp.down_proj" + layer.weight = torch.nn.Parameter( + torch.zeros((48, 128), dtype=torch.float8_e4m3fn), + requires_grad=False, + ) + layer.weight_scale = torch.nn.Parameter( + torch.zeros((48, 4), dtype=torch.uint8), + requires_grad=False, + ) + kernel = object.__new__(B12xMxfp8LinearKernel) + + kernel.process_weights_after_loading(layer) + packed = layer.b12x_mxfp8_packed_weight + values_ptr = packed.values.data_ptr() + scales_ptr = packed.scales.data_ptr() + + layer.weight = torch.nn.Parameter( + torch.ones((48, 128), dtype=torch.float8_e4m3fn), + requires_grad=False, + ) + layer.weight_scale = torch.nn.Parameter( + torch.full((48, 4), 3, dtype=torch.uint8), + requires_grad=False, + ) + kernel.process_weights_after_loading(layer) + + assert layer.b12x_mxfp8_packed_weight is packed + assert packed.values.data_ptr() == values_ptr + assert packed.scales.data_ptr() == scales_ptr + torch.testing.assert_close( + packed.values, + torch.ones((48, 128), dtype=torch.float8_e4m3fn), + ) + torch.testing.assert_close( + packed.scales, + torch.full((48, 4), 3, dtype=torch.uint8), + ) + assert layer.weight.numel() == 0 + assert layer.weight_scale.numel() == 0 + + +def test_b12x_block_fp8_process_weights_keeps_native_block_layout() -> None: + layer = torch.nn.Module() + layer.weight = torch.nn.Parameter( + torch.empty((128, 128), dtype=torch.float8_e4m3fn), + requires_grad=False, + ) + layer.weight_scale_inv = torch.nn.Parameter( + torch.empty((1, 1), dtype=torch.float32), + requires_grad=False, + ) + layer.weight_block_size = [128, 128] + weight_loader = object() + scale_loader = object() + layer.weight.weight_loader = weight_loader + layer.weight_scale_inv.weight_loader = scale_loader + kernel = object.__new__(B12xFp8BlockScaledMMKernel) + + kernel.process_weights_after_loading(layer) + + assert layer.b12x_block_fp8_linear + assert layer.weight.shape == (128, 128) + assert layer.weight.dtype == torch.float8_e4m3fn + assert layer.weight_scale_inv.shape == (1, 1) + assert layer.weight_scale_inv.dtype == torch.float32 + assert layer.weight.weight_loader is weight_loader + assert layer.weight_scale_inv.weight_loader is scale_loader + + +@pytest.mark.parametrize("scale_dtype", [torch.float8_e8m0fnu, torch.uint8]) +def test_b12x_block_fp8_upcasts_e8m0_weight_scales(scale_dtype) -> None: + layer = torch.nn.Module() + layer.weight = torch.nn.Parameter( + torch.empty((128, 128), dtype=torch.float8_e4m3fn), + requires_grad=False, + ) + scale_bytes = torch.tensor([[125]], dtype=torch.uint8) + layer.weight_scale_inv = torch.nn.Parameter( + scale_bytes.view(scale_dtype), + requires_grad=False, + ) + layer.weight_block_size = [128, 128] + kernel = object.__new__(B12xFp8BlockScaledMMKernel) + + kernel.process_weights_after_loading(layer) + + assert layer.weight_scale_inv.dtype == torch.float32 + torch.testing.assert_close( + layer.weight_scale_inv, + torch.tensor([[0.25]], dtype=torch.float32), + ) + + +def test_b12x_mxfp8_apply_uses_packed_weight(monkeypatch) -> None: + import vllm.model_executor.kernels.linear.mxfp8.b12x as b12x_mod + + calls = [] + + def mxfp8_linear( + source: torch.Tensor, + packed_weight, + *, + bias: torch.Tensor | None = None, + expected_m: int | None = None, + stream: object = None, + ) -> torch.Tensor: + del stream + calls.append((source, packed_weight, bias, expected_m)) + return source.new_full((source.shape[0], packed_weight.out_features), 3.0) + + monkeypatch.setattr( + b12x_mod, + "_import_b12x_mxfp8", + lambda: types.SimpleNamespace(mm=mxfp8_linear), + ) + + layer = torch.nn.Module() + packed = types.SimpleNamespace(out_features=48) + layer.b12x_mxfp8_packed_weight = packed + x = torch.empty((2, 3, 128), dtype=torch.bfloat16) + bias = torch.empty((48,), dtype=torch.bfloat16) + kernel = object.__new__(B12xMxfp8LinearKernel) + + output = kernel.apply_weights(layer, x, bias) + + assert output.shape == (2, 3, 48) + assert output.dtype == x.dtype + assert len(calls) == 1 + source, called_packed, called_bias, expected_m = calls[0] + assert source.shape == (6, 128) + assert called_packed is packed + assert called_bias is bias + assert expected_m == 6 + + +def test_b12x_block_fp8_apply_uses_b12x_recipe_api(monkeypatch) -> None: + import vllm.model_executor.kernels.linear.scaled_mm.b12x_block as b12x_mod + + calls = [] + + def mm_block_fp8(*args, **kwargs): + calls.append((args, kwargs)) + return torch.full( + (args[0].shape[0], args[2].shape[0]), + 13.0, + dtype=kwargs["out_dtype"], + ) + + monkeypatch.setattr( + b12x_mod, + "_import_b12x_blockscaled", + lambda: types.SimpleNamespace(mm_block_fp8=mm_block_fp8), + ) + + a = torch.empty((6, 128), dtype=torch.float8_e4m3fn) + weight = torch.empty((256, 128), dtype=torch.float8_e4m3fn) + a_scale = torch.empty((6, 1), dtype=torch.float32) + weight_scale = torch.empty((2, 1), dtype=torch.float32) + kernel = object.__new__(B12xFp8BlockScaledMMKernel) + kernel.config = types.SimpleNamespace(out_dtype=torch.bfloat16) + + output = kernel.apply_block_scaled_mm(a, weight, a_scale, weight_scale) + + assert output.shape == (6, 256) + assert output.dtype == torch.bfloat16 + assert len(calls) == 1 + assert calls[0] == ( + (a, a_scale, weight, weight_scale), + {"out_dtype": torch.bfloat16}, + ) + torch.testing.assert_close(output, torch.full_like(output, 13.0)) + + +def test_b12x_block_fp8_helper_uses_regular_compact_scale_api(monkeypatch) -> None: + import vllm.model_executor.kernels.linear.scaled_mm.b12x_block as b12x_mod + + calls = [] + + def mm_block_fp8(*args, **kwargs): + calls.append((args, kwargs)) + return torch.full((6, 256), 17.0, dtype=torch.bfloat16) + + monkeypatch.setattr( + b12x_mod, + "_import_b12x_blockscaled", + lambda: types.SimpleNamespace(mm_block_fp8=mm_block_fp8), + ) + + a = torch.empty((6, 128), dtype=torch.float8_e4m3fn) + weight = torch.empty((256, 128), dtype=torch.float8_e4m3fn) + a_scale = torch.empty((6, 1), dtype=torch.float32) + weight_scale = torch.empty((2, 1), dtype=torch.float32) + output = _run_b12x_fp8_block_scaled_mm( + a, + weight, + a_scale, + weight_scale, + torch.bfloat16, + ) + + assert output.shape == (6, 256) + args, kwargs = calls[0] + assert args == (a, a_scale, weight, weight_scale) + assert kwargs == { + "out_dtype": torch.bfloat16, + } + torch.testing.assert_close(output, torch.full_like(output, 17.0)) diff --git a/tests/model_executor/kernels/test_b12x_nvfp4_linear.py b/tests/model_executor/kernels/test_b12x_nvfp4_linear.py new file mode 100644 index 0000000000..1e2717c4e0 --- /dev/null +++ b/tests/model_executor/kernels/test_b12x_nvfp4_linear.py @@ -0,0 +1,246 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +from __future__ import annotations + +import types + +import torch + +from vllm.model_executor.kernels.linear import ( + _LINEAR_BACKEND_KERNEL_MAP, + _POSSIBLE_NVFP4_KERNELS, + _resolve_backend_kernels, + init_nvfp4_linear_kernel, +) +from vllm.model_executor.kernels.linear.nvfp4.b12x import ( + B12xNvFp4LinearKernel, + warmup_b12x_nvfp4_linear, +) +from vllm.model_executor.kernels.linear.nvfp4.marlin import ( + MarlinNvFp4LinearKernel, +) +from vllm.platforms import PlatformEnum + + +def test_b12x_backend_maps_nvfp4_kernel() -> None: + assert B12xNvFp4LinearKernel in _LINEAR_BACKEND_KERNEL_MAP["b12x"] + assert B12xNvFp4LinearKernel in _POSSIBLE_NVFP4_KERNELS[PlatformEnum.CUDA] + + +def test_b12x_nvfp4_fallback_priority() -> None: + kernels = _POSSIBLE_NVFP4_KERNELS[PlatformEnum.CUDA] + names = [kernel.__name__ for kernel in kernels] + + assert ( + names.index("FbgemmNvFp4LinearKernel") + < names.index("B12xNvFp4LinearKernel") + < names.index("EmulationNvFp4LinearKernel") + ) + + +def test_b12x_nvfp4_explicit_backend_selects_native_kernel(monkeypatch) -> None: + import vllm.model_executor.kernels.linear as linear_mod + + monkeypatch.setattr(linear_mod.current_platform, "_enum", PlatformEnum.CUDA) + monkeypatch.setattr(linear_mod, "_get_linear_backend", lambda: "b12x") + monkeypatch.setattr( + B12xNvFp4LinearKernel, + "is_supported", + classmethod(lambda cls, compute_capability=None: (True, None)), + ) + monkeypatch.setattr( + B12xNvFp4LinearKernel, + "can_implement", + classmethod(lambda cls, config: (True, None)), + ) + + kernel = init_nvfp4_linear_kernel() + + assert isinstance(kernel, B12xNvFp4LinearKernel) + + +def test_b12x_nvfp4_can_implement_supported_config() -> None: + can_implement, reason = B12xNvFp4LinearKernel.can_implement(None) + + assert can_implement + assert reason is None + + +def test_b12x_backend_preserves_w4a16_fallback(monkeypatch) -> None: + import vllm.model_executor.kernels.linear as linear_mod + + monkeypatch.setattr(linear_mod.current_platform, "_enum", PlatformEnum.CUDA) + monkeypatch.setattr(linear_mod, "_get_linear_backend", lambda: "b12x") + monkeypatch.setattr( + MarlinNvFp4LinearKernel, + "is_supported", + classmethod(lambda cls, compute_capability=None: (True, None)), + ) + + kernel = init_nvfp4_linear_kernel(use_a16=True) + + assert isinstance(kernel, MarlinNvFp4LinearKernel) + + +def test_backend_without_w4a16_kernel_preserves_fallback(monkeypatch) -> None: + import vllm.model_executor.kernels.linear as linear_mod + + kernels = [MarlinNvFp4LinearKernel] + monkeypatch.setattr(linear_mod, "_get_linear_backend", lambda: "b12x") + assert _resolve_backend_kernels(kernels, "NVFP4") == kernels + + +def test_b12x_nvfp4_processes_scale_and_preserves_loader(monkeypatch) -> None: + import vllm.model_executor.kernels.linear.nvfp4.b12x as b12x_mod + + scale = torch.empty((48, 8), dtype=torch.float8_e4m3fn) + swizzled_scale = torch.empty((128, 8), dtype=torch.float8_e4m3fn) + intrinsics = types.SimpleNamespace(swizzle_block_scale=lambda value: swizzled_scale) + monkeypatch.setattr(b12x_mod, "_import_b12x_intrinsics", lambda: intrinsics) + + layer = torch.nn.Module() + layer.prefix = "model.layers.0.mlp.shared_expert.down_proj" + layer.weight_scale = torch.nn.Parameter(scale, requires_grad=False) + weight_loader = object() + layer.weight_scale.weight_loader = weight_loader + kernel = object.__new__(B12xNvFp4LinearKernel) + + kernel.process_weights_after_loading(layer) + + assert layer.weight_scale.data_ptr() == swizzled_scale.data_ptr() + assert layer.weight_scale.weight_loader is weight_loader + assert layer.b12x_nvfp4_linear + + +def test_b12x_nvfp4_apply_calls_native_blockscaled_gemm(monkeypatch) -> None: + import vllm.model_executor.kernels.linear.nvfp4.b12x as b12x_mod + + calls: list[tuple] = [] + quant_calls: list[tuple] = [] + x_packed = torch.empty((6, 64), dtype=torch.uint8) + x_scale_storage = torch.empty((128, 8), dtype=torch.float8_e4m3fn) + + def quant(*args, **kwargs): + quant_calls.append((args, kwargs)) + return x_packed, x_scale_storage + + def mm_nvfp4(*args, **kwargs): + calls.append((args, kwargs)) + return torch.full((6, 48), 3.0, dtype=torch.bfloat16) + + monkeypatch.setattr( + b12x_mod, + "scaled_fp4_quant", + quant, + ) + monkeypatch.setattr( + b12x_mod, + "_import_b12x_blockscaled", + lambda: types.SimpleNamespace(mm_nvfp4=mm_nvfp4), + ) + + layer = torch.nn.Module() + layer.output_size_per_partition = 48 + layer.weight = torch.empty((48, 64), dtype=torch.uint8) + layer.weight_scale = torch.empty((128, 8), dtype=torch.float8_e4m3fn) + layer.input_global_scale_inv = torch.tensor(2.0) + layer.alpha = torch.tensor(0.25) + x = torch.empty((2, 3, 256), dtype=torch.bfloat16)[..., ::2] + bias = torch.ones(48, dtype=torch.bfloat16) + kernel = object.__new__(B12xNvFp4LinearKernel) + + output = kernel.apply_weights(layer, x, bias) + + assert output.shape == (2, 3, 48) + torch.testing.assert_close(output, torch.full_like(output, 4.0)) + assert len(quant_calls) == 1 + quant_args, quant_kwargs = quant_calls[0] + assert quant_args[0].shape == (6, 128) + assert quant_args[0].data_ptr() == x.data_ptr() + assert quant_args[1] is layer.input_global_scale_inv + assert not quant_args[0].is_contiguous() + assert quant_kwargs == {"is_sf_swizzled_layout": True} + assert len(calls) == 1 + args, kwargs = calls[0] + assert args == ( + x_packed, + x_scale_storage, + layer.weight, + layer.weight_scale, + layer.alpha, + ) + assert kwargs == {"out_dtype": torch.bfloat16} + + +def test_warmup_b12x_nvfp4_dedupes_weight_signatures(monkeypatch) -> None: + import vllm.model_executor.kernels.linear.nvfp4.b12x as b12x_mod + + calls = [] + + def apply( + source, + weight, + weight_scale, + input_global_scale_inv, + alpha, + bias, + ): + calls.append( + ( + source.shape, + weight, + weight_scale, + input_global_scale_inv, + alpha, + bias, + ) + ) + return source.new_empty((source.shape[0], weight.shape[0])) + + platform = types.SimpleNamespace( + is_cuda=lambda: True, + is_device_capability_family=lambda family: family == 120, + ) + monkeypatch.setattr(b12x_mod, "current_platform", platform) + monkeypatch.setattr( + b12x_mod, + "_import_b12x_blockscaled", + lambda: types.SimpleNamespace(), + ) + monkeypatch.setattr(b12x_mod, "_apply_b12x_nvfp4_linear", apply) + + def layer(n: int): + return types.SimpleNamespace( + b12x_nvfp4_linear=True, + weight=torch.empty((n, 64), dtype=torch.uint8), + weight_scale=torch.empty((128, 8), dtype=torch.float8_e4m3fn), + input_global_scale_inv=torch.tensor(2.0), + alpha=torch.tensor(0.25), + ) + + layer_a = layer(48) + layer_b = layer(48) + layer_c = layer(96) + model = types.SimpleNamespace( + modules=lambda: iter([layer_a, layer_b, layer_c, types.SimpleNamespace()]) + ) + + warmed = warmup_b12x_nvfp4_linear( + model, + max_tokens=8, + cudagraph_capture_sizes=[1, 2], + ) + + assert warmed == 6 + assert [call[0] for call in calls] == [ + torch.Size([1, 128]), + torch.Size([2, 128]), + torch.Size([8, 128]), + torch.Size([1, 128]), + torch.Size([2, 128]), + torch.Size([8, 128]), + ] + assert calls[0][1] is layer_a.weight + assert calls[3][1] is layer_c.weight + assert all(call[5] is None for call in calls) diff --git a/tests/model_executor/test_b12x_warmup.py b/tests/model_executor/test_b12x_warmup.py new file mode 100644 index 0000000000..bd71f9bcd2 --- /dev/null +++ b/tests/model_executor/test_b12x_warmup.py @@ -0,0 +1,100 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +import importlib +from types import SimpleNamespace + +import pytest +import torch + +from vllm.model_executor.warmup.b12x_warmup import b12x_warmup + + +@pytest.mark.parametrize( + ("module_name", "warmup_name", "import_name"), + [ + ( + "vllm.model_executor.kernels.linear.scaled_mm.b12x_block", + "warmup_b12x_block_fp8_linear", + "_import_b12x_blockscaled", + ), + ( + "vllm.model_executor.kernels.linear.scaled_mm.b12x_tensor", + "warmup_b12x_tensor_fp8_linear", + "_import_b12x_tensor_fp8", + ), + ( + "vllm.model_executor.kernels.linear.mxfp8.b12x", + "warmup_b12x_mxfp8_linear", + "_import_b12x_mxfp8", + ), + ( + "vllm.model_executor.kernels.linear.mxfp4.b12x", + "warmup_b12x_mxfp4_linear", + "_import_b12x_blockscaled", + ), + ( + "vllm.model_executor.kernels.linear.nvfp4.b12x", + "warmup_b12x_nvfp4_linear", + "_import_b12x_blockscaled", + ), + ], +) +def test_b12x_linear_warmup_skips_unused_provider( + monkeypatch, + module_name: str, + warmup_name: str, + import_name: str, +) -> None: + module = importlib.import_module(module_name) + platform = SimpleNamespace( + is_cuda=lambda: True, + is_device_capability_family=lambda family: family == 120, + ) + monkeypatch.setattr(module, "current_platform", platform) + + def fail_import(): + pytest.fail("unused B12X provider was imported") + + monkeypatch.setattr(module, import_name, fail_import) + + warmup = getattr(module, warmup_name) + assert warmup(torch.nn.Module(), max_tokens=128) == 0 + + +def test_b12x_warmup_covers_linear_serving_shapes(monkeypatch) -> None: + import vllm.model_executor.warmup.b12x_warmup as warmup_mod + + model = torch.nn.Module() + linear_calls: list[tuple[torch.nn.Module, dict]] = [] + + def linear_warmup(model, **kwargs): + linear_calls.append((model, kwargs)) + return 0 + + monkeypatch.setattr(warmup_mod, "warmup_b12x_block_fp8_linear", linear_warmup) + monkeypatch.setattr(warmup_mod, "warmup_b12x_mxfp4_linear", linear_warmup) + monkeypatch.setattr(warmup_mod, "warmup_b12x_mxfp8_linear", linear_warmup) + monkeypatch.setattr(warmup_mod, "warmup_b12x_nvfp4_linear", linear_warmup) + monkeypatch.setattr(warmup_mod, "warmup_b12x_tensor_fp8_linear", linear_warmup) + + worker = SimpleNamespace( + get_model=lambda: model, + scheduler_config=SimpleNamespace( + max_num_batched_tokens=256, + max_num_scheduled_tokens=320, + ), + model_config=SimpleNamespace(dtype=torch.float16), + vllm_config=SimpleNamespace( + compilation_config=SimpleNamespace(compile_sizes=[32, "dynamic", 64]) + ), + ) + + b12x_warmup(worker, [8, 16]) + + expected_linear_kwargs = { + "max_tokens": 256, + "cudagraph_capture_sizes": [8, 16], + "output_dtype": torch.float16, + } + assert linear_calls == [(model, expected_linear_kwargs)] * 5 diff --git a/vllm/config/kernel.py b/vllm/config/kernel.py index 74e959f33a..7287c1ce92 100644 --- a/vllm/config/kernel.py +++ b/vllm/config/kernel.py @@ -147,6 +147,7 @@ LinearBackend = Literal[ "flashinfer_trtllm", "flashinfer_cudnn", "flashinfer_b12x", + "b12x", "marlin", "humming", "triton", @@ -223,6 +224,7 @@ class KernelConfig: - "flashinfer_trtllm": Use FlashInfer with TensorRT-LLM kernels - "flashinfer_cudnn": Use FlashInfer with cuDNN kernels - "flashinfer_b12x": Use FlashInfer b12x CuteDSL NVFP4 GEMM (SM120+) + - "b12x": Use native B12X FP8 and FP4 linear kernels on SM12x - "marlin": Use Marlin kernels - "triton": Use Triton-based kernels - "deep_gemm": Use DeepGEMM kernels diff --git a/vllm/model_executor/kernels/linear/__init__.py b/vllm/model_executor/kernels/linear/__init__.py index 9915255a84..3413d4a69f 100644 --- a/vllm/model_executor/kernels/linear/__init__.py +++ b/vllm/model_executor/kernels/linear/__init__.py @@ -77,6 +77,9 @@ from vllm.model_executor.kernels.linear.mxfp4 import ( from vllm.model_executor.kernels.linear.mxfp4.aiter import ( AiterMxfp4LinearKernel, ) +from vllm.model_executor.kernels.linear.mxfp4.b12x import ( + B12xMxFp4LinearKernel, +) from vllm.model_executor.kernels.linear.mxfp4.emulation import ( EmulationMxfp4LinearKernel, ) @@ -103,6 +106,9 @@ from vllm.model_executor.kernels.linear.mxfp8 import ( Mxfp8LinearKernel, Mxfp8LinearLayerConfig, ) +from vllm.model_executor.kernels.linear.mxfp8.b12x import ( + B12xMxfp8LinearKernel, +) from vllm.model_executor.kernels.linear.mxfp8.emulation import ( EmulationMxfp8LinearKernel, ) @@ -126,6 +132,9 @@ from vllm.model_executor.kernels.linear.nvfp4 import ( NvFp4LinearKernel, NvFp4LinearLayerConfig, ) +from vllm.model_executor.kernels.linear.nvfp4.b12x import ( + B12xNvFp4LinearKernel, +) from vllm.model_executor.kernels.linear.nvfp4.cutlass import ( CutlassNvFp4LinearKernel, ) @@ -163,6 +172,12 @@ from vllm.model_executor.kernels.linear.scaled_mm.aiter import ( AiterPerTokenFp8ScaledMMLinearKernel, AiterPreshuffledPerTokenFp8ScaledMMLinearKernel, ) +from vllm.model_executor.kernels.linear.scaled_mm.b12x_block import ( + B12xFp8BlockScaledMMKernel, +) +from vllm.model_executor.kernels.linear.scaled_mm.b12x_tensor import ( + B12xTensorFP8ScaledMMLinearKernel, +) from vllm.model_executor.kernels.linear.scaled_mm.cpu import ( CPUFp8BlockScaledMMKernel, CPUInt8ScaledMMLinearKernel, @@ -228,6 +243,13 @@ def _get_linear_backend() -> str: # set are considered candidates. If none can implement the layer config, # an error is raised to respect the user's explicit intent. _LINEAR_BACKEND_KERNEL_MAP: dict[str, set[type]] = { + "b12x": { + B12xFp8BlockScaledMMKernel, + B12xMxFp4LinearKernel, + B12xMxfp8LinearKernel, + B12xNvFp4LinearKernel, + B12xTensorFP8ScaledMMLinearKernel, + }, "cutlass": { CutlassInt8ScaledMMLinearKernel, CutlassFP8ScaledMMLinearKernel, @@ -377,6 +399,7 @@ _POSSIBLE_FP8_KERNELS: dict[PlatformEnum, list[type[FP8ScaledMMLinearKernel]]] = MarlinFP8ScaledMMLinearKernel, FlashInferFP8ScaledMMLinearKernel, CutlassFP8ScaledMMLinearKernel, + B12xTensorFP8ScaledMMLinearKernel, PerTensorTorchFP8ScaledMMLinearKernel, ChannelWiseTorchFP8ScaledMMLinearKernel, HummingFP8ScaledMMLinearKernel, @@ -411,6 +434,7 @@ _POSSIBLE_FP8_BLOCK_KERNELS: dict[ FlashInferFp8DeepGEMMDynamicBlockScaledKernel, DeepGemmFp8BlockScaledMMKernel, CutlassFp8BlockScaledMMKernel, + B12xFp8BlockScaledMMKernel, MarlinFP8ScaledMMLinearKernel, TritonFp8BlockScaledMMKernel, HummingFP8ScaledMMLinearKernel, @@ -482,6 +506,7 @@ _POSSIBLE_MXFP8_KERNELS: dict[PlatformEnum, list[type[Mxfp8LinearKernel]]] = { FlashInferCutedslMxfp8LinearKernel, FlashInferCutlassMxfp8LinearKernel, MarlinMxfp8LinearKernel, + B12xMxfp8LinearKernel, EmulationMxfp8LinearKernel, HummingMxfp8LinearKernel, ], @@ -507,6 +532,7 @@ _POSSIBLE_NVFP4_KERNELS: dict[PlatformEnum, list[type[NvFp4LinearKernel]]] = { FlashInferTrtllmNvFp4LinearKernel, FlashInferCudnnNvFp4LinearKernel, FbgemmNvFp4LinearKernel, + B12xNvFp4LinearKernel, EmulationNvFp4LinearKernel, HummingNvFp4LinearKernel, ], @@ -529,6 +555,7 @@ _POSSIBLE_MXFP4_KERNELS: dict[PlatformEnum, list[type[MxFp4LinearKernel]]] = { FlashInferMxFp4LinearKernel, MarlinMxFp4LinearKernel, HummingMxFp4LinearKernel, + B12xMxFp4LinearKernel, EmulationMxfp4LinearKernel, ], PlatformEnum.ROCM: [ @@ -1175,6 +1202,9 @@ __all__ = [ "init_mxfp8_linear_kernel", "Mxfp8LinearKernel", "Mxfp8LinearLayerConfig", + "B12xMxfp8LinearKernel", + "B12xMxFp4LinearKernel", + "B12xNvFp4LinearKernel", "init_mxfp4_linear_kernel", "MxFp4LinearKernel", "MxFp4LinearLayerConfig", @@ -1203,4 +1233,6 @@ __all__ = [ "_KernelT", "DeepGemmFp8BlockScaledMMKernel", "FlashInferFp8DeepGEMMDynamicBlockScaledKernel", + "B12xFp8BlockScaledMMKernel", + "B12xTensorFP8ScaledMMLinearKernel", ] diff --git a/vllm/model_executor/kernels/linear/mxfp4/b12x.py b/vllm/model_executor/kernels/linear/mxfp4/b12x.py new file mode 100644 index 0000000000..93e872c068 --- /dev/null +++ b/vllm/model_executor/kernels/linear/mxfp4/b12x.py @@ -0,0 +1,170 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +from __future__ import annotations + +from collections.abc import Iterable +from typing import Any + +import torch + +from vllm.model_executor.layers.quantization.utils.quant_utils import ( + kMxfp4Dynamic, +) +from vllm.model_executor.utils import replace_parameter +from vllm.platforms import current_platform +from vllm.utils.b12x import ( + b12x_warmup_token_counts, +) +from vllm.utils.b12x import ( + get_b12x_blockscaled as _import_b12x_blockscaled, +) +from vllm.utils.b12x import get_b12x_intrinsics as _import_b12x_intrinsics + +from .base import MxFp4LinearKernel, MxFp4LinearLayerConfig + + +def _apply_b12x_mxfp4_linear( + x: torch.Tensor, + weight: torch.Tensor, + weight_scale_storage: torch.Tensor, + bias: torch.Tensor | None, +) -> torch.Tensor: + from vllm.utils.flashinfer import flashinfer_mxfp4_quantize + + blockscaled = _import_b12x_blockscaled() + assert blockscaled is not None + + output_size = int(weight.shape[0]) + output_shape = [*x.shape[:-1], output_size] + x_2d = x.reshape(-1, x.shape[-1]).contiguous() + x_packed, x_scale_swizzled = flashinfer_mxfp4_quantize(x_2d, backend="cute-dsl") + output = blockscaled.mm_mxfp4( + x_packed, + x_scale_swizzled, + weight, + weight_scale_storage, + out_dtype=x.dtype, + ) + if bias is not None: + output = output + bias + return output.view(*output_shape) + + +def warmup_b12x_mxfp4_linear( + model: torch.nn.Module, + *, + max_tokens: int, + cudagraph_capture_sizes: Iterable[int] = (), + output_dtype: torch.dtype = torch.bfloat16, +) -> int: + if not current_platform.is_cuda(): + return 0 + if not current_platform.is_device_capability_family(120): + return 0 + if output_dtype not in (torch.bfloat16, torch.float16): + output_dtype = torch.bfloat16 + layer_map: dict[tuple[Any, ...], torch.nn.Module] = {} + for layer in model.modules(): + if not getattr(layer, "b12x_mxfp4_linear", False): + continue + weight = layer.weight + weight_scale = layer.weight_scale + n, packed_k = map(int, weight.shape) + signature = ( + weight.device, + n, + packed_k * 2, + weight.dtype, + weight_scale.dtype, + output_dtype, + ) + layer_map.setdefault(signature, layer) + if not layer_map: + return 0 + if _import_b12x_blockscaled() is None: + return 0 + + token_counts = b12x_warmup_token_counts( + max_tokens=max_tokens, + cudagraph_capture_sizes=cudagraph_capture_sizes, + ) + warmed = 0 + last_device: torch.device | None = None + + with torch.inference_mode(): + for signature, layer in layer_map.items(): + weight = layer.weight + weight_scale = layer.weight_scale + k = signature[2] + last_device = weight.device + for tokens in token_counts: + source = torch.zeros( + (tokens, k), + dtype=output_dtype, + device=weight.device, + ) + _apply_b12x_mxfp4_linear( + source, + weight, + weight_scale, + None, + ) + warmed += 1 + + if warmed > 0 and last_device is not None and last_device.type == "cuda": + torch.accelerator.synchronize(last_device) + + return warmed + + +class B12xMxFp4LinearKernel(MxFp4LinearKernel): + """MXFP4 linear through the native B12X SM120 dense GEMM.""" + + @classmethod + def is_supported( + cls, compute_capability: int | None = None + ) -> tuple[bool, str | None]: + del compute_capability + if not current_platform.is_cuda(): + return False, "B12X MXFP4 kernels are only available on CUDA" + if not current_platform.is_device_capability_family(120): + return False, "B12X MXFP4 kernels require a Blackwell 12x device" + blockscaled = _import_b12x_blockscaled() + if blockscaled is None or _import_b12x_intrinsics() is None: + return False, "Install the B12X backend with `pip install vllm[b12x]`" + if not blockscaled.is_supported(): + return False, "b12x native MXFP4 GEMM is not supported" + return True, None + + @classmethod + def can_implement(cls, config: MxFp4LinearLayerConfig) -> tuple[bool, str | None]: + if config.activation_quant_key != kMxfp4Dynamic: + return False, "B12X MXFP4 GEMM requires dynamic MXFP4 activations" + return True, None + + def process_weights_after_loading(self, layer: torch.nn.Module) -> None: + intrinsics = _import_b12x_intrinsics() + assert intrinsics is not None + replace_parameter( + layer, + "weight_scale", + intrinsics.swizzle_block_scale(layer.weight_scale.data), + ) + layer.b12x_mxfp4_linear = True + + def apply_weights( + self, + layer: torch.nn.Module, + x: torch.Tensor, + bias: torch.Tensor | None = None, + ) -> torch.Tensor: + return _apply_b12x_mxfp4_linear( + x, + layer.weight, + layer.weight_scale, + bias, + ) + + +__all__ = ["B12xMxFp4LinearKernel", "warmup_b12x_mxfp4_linear"] diff --git a/vllm/model_executor/kernels/linear/mxfp8/b12x.py b/vllm/model_executor/kernels/linear/mxfp8/b12x.py new file mode 100644 index 0000000000..4dd77dd6c0 --- /dev/null +++ b/vllm/model_executor/kernels/linear/mxfp8/b12x.py @@ -0,0 +1,193 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +from __future__ import annotations + +from collections.abc import Iterable +from typing import Any + +import torch + +from vllm.model_executor.layers.quantization.utils.mxfp8_utils import ( + MXFP8_BLOCK_SIZE, + MXFP8_SCALE_DTYPE, + MXFP8_VALUE_DTYPE, +) +from vllm.model_executor.utils import replace_parameter +from vllm.platforms import current_platform +from vllm.utils.b12x import ( + b12x_warmup_token_counts, + reuse_packed_weight_storage, +) +from vllm.utils.b12x import ( + get_b12x_mxfp8_linear as _import_b12x_mxfp8, +) +from vllm.utils.torch_utils import current_stream + +from .Mxfp8LinearKernel import Mxfp8LinearKernel, Mxfp8LinearLayerConfig + + +def _b12x_mxfp8_expected_m(tokens: int) -> int: + return max(1, int(tokens)) + + +def _apply_b12x_mxfp8_packed_linear( + layer: torch.nn.Module, + x: torch.Tensor, + bias: torch.Tensor | None, +) -> torch.Tensor: + packed_weight = getattr(layer, "b12x_mxfp8_packed_weight", None) + if packed_weight is None: + raise RuntimeError( + "b12x MXFP8 packed weights are missing; " + "process_weights_after_loading did not run for this layer" + ) + + input_2d = x.reshape(-1, x.shape[-1]).contiguous() + output_shape = [*x.shape[:-1], int(packed_weight.out_features)] + + mxfp8 = _import_b12x_mxfp8() + assert mxfp8 is not None + output = mxfp8.mm( + input_2d, + packed_weight, + bias=bias, + expected_m=_b12x_mxfp8_expected_m(int(input_2d.shape[0])), + ) + return output.view(*output_shape) + + +def warmup_b12x_mxfp8_linear( + model: torch.nn.Module, + *, + max_tokens: int, + cudagraph_capture_sizes: Iterable[int] = (), + output_dtype: torch.dtype = torch.bfloat16, +) -> int: + if not current_platform.is_cuda(): + return 0 + if not current_platform.is_device_capability_family(120): + return 0 + if output_dtype not in (torch.bfloat16, torch.float16): + output_dtype = torch.bfloat16 + + layer_map: dict[tuple[Any, ...], Any] = {} + for layer in model.modules(): + packed_weight = getattr(layer, "b12x_mxfp8_packed_weight", None) + if packed_weight is None: + continue + device = torch.device(packed_weight.weight.values.device) + signature = ( + device, + int(packed_weight.in_features), + int(packed_weight.padded_in_features), + int(packed_weight.out_features), + output_dtype, + ) + layer_map.setdefault(signature, packed_weight) + if not layer_map: + return 0 + + mxfp8 = _import_b12x_mxfp8() + if mxfp8 is None: + return 0 + + token_counts = b12x_warmup_token_counts( + max_tokens=max_tokens, + cudagraph_capture_sizes=cudagraph_capture_sizes, + ) + warmed = 0 + last_device: torch.device | None = None + + with torch.inference_mode(): + for signature, packed_weight in layer_map.items(): + device = signature[0] + last_device = device + for tokens in token_counts: + source = torch.zeros( + (tokens, int(packed_weight.in_features)), + dtype=output_dtype, + device=device, + ) + mxfp8.mm( + source, + packed_weight, + expected_m=_b12x_mxfp8_expected_m(tokens), + stream=current_stream().cuda_stream, + ) + warmed += 1 + + if warmed > 0 and last_device is not None and last_device.type == "cuda": + torch.accelerator.synchronize(last_device) + + return warmed + + +class B12xMxfp8LinearKernel(Mxfp8LinearKernel): + """ModelOpt MXFP8 linear through the native b12x SM120 dense GEMM path.""" + + @classmethod + def is_supported( + cls, + compute_capability: int | None = None, + ) -> tuple[bool, str | None]: + del compute_capability + if not current_platform.is_cuda(): + return False, "b12x MXFP8 kernels are only available on CUDA" + if not current_platform.is_device_capability_family(120): + return False, "b12x MXFP8 kernels require a Blackwell 12x device" + mxfp8 = _import_b12x_mxfp8() + if mxfp8 is None: + return False, "Install the B12X backend with `pip install vllm[b12x]`" + if not mxfp8.is_supported(): + return False, "b12x.gemm.mxfp8_linear is not supported" + return True, None + + @classmethod + def can_implement(cls, c: Mxfp8LinearLayerConfig) -> tuple[bool, str | None]: + del c + return True, None + + def process_weights_after_loading(self, layer: torch.nn.Module) -> None: + weight = layer.weight.data + assert weight.dtype == MXFP8_VALUE_DTYPE, ( + f"b12x MXFP8 requires {MXFP8_VALUE_DTYPE}, got {weight.dtype}" + ) + assert weight.ndim == 2, f"b12x MXFP8 weight must be 2D, got {weight.ndim}D" + assert hasattr(layer, "weight_scale"), "b12x MXFP8 linear requires weight_scale" + + out_features, in_features = map(int, weight.shape) + assert in_features % MXFP8_BLOCK_SIZE == 0, ( + "b12x MXFP8 requires input features divisible by " + f"{MXFP8_BLOCK_SIZE}, got {in_features}" + ) + weight_scale = layer.weight_scale.data + assert weight_scale.dtype == MXFP8_SCALE_DTYPE, ( + f"b12x MXFP8 requires {MXFP8_SCALE_DTYPE} weight_scale, " + f"got {weight_scale.dtype}" + ) + assert weight_scale.ndim == 2, ( + f"b12x MXFP8 weight_scale must be 2D, got {weight_scale.ndim}D" + ) + + mxfp8 = _import_b12x_mxfp8() + assert mxfp8 is not None + scale_k = in_features // MXFP8_BLOCK_SIZE + packed_weight = mxfp8.pack_weight( + weight[:out_features, :in_features].detach(), + weight_scale[:out_features, :scale_k].detach(), + ) + layer.b12x_mxfp8_packed_weight = reuse_packed_weight_storage( + getattr(layer, "b12x_mxfp8_packed_weight", None), + packed_weight, + ) + replace_parameter(layer, "weight", weight.new_empty((0,))) + replace_parameter(layer, "weight_scale", weight_scale.new_empty((0,))) + + def apply_weights( + self, + layer: torch.nn.Module, + x: torch.Tensor, + bias: torch.Tensor | None = None, + ) -> torch.Tensor: + return _apply_b12x_mxfp8_packed_linear(layer, x, bias) diff --git a/vllm/model_executor/kernels/linear/nvfp4/b12x.py b/vllm/model_executor/kernels/linear/nvfp4/b12x.py new file mode 100644 index 0000000000..a9e5a69283 --- /dev/null +++ b/vllm/model_executor/kernels/linear/nvfp4/b12x.py @@ -0,0 +1,176 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +from __future__ import annotations + +from collections.abc import Iterable +from typing import Any + +import torch + +from vllm._custom_ops import scaled_fp4_quant +from vllm.model_executor.utils import replace_parameter +from vllm.platforms import current_platform +from vllm.utils.b12x import ( + b12x_warmup_token_counts, +) +from vllm.utils.b12x import ( + get_b12x_blockscaled as _import_b12x_blockscaled, +) +from vllm.utils.b12x import get_b12x_intrinsics as _import_b12x_intrinsics + +from .base import NvFp4LinearKernel, NvFp4LinearLayerConfig + + +def _apply_b12x_nvfp4_linear( + x: torch.Tensor, + weight: torch.Tensor, + weight_scale_storage: torch.Tensor, + input_global_scale_inv: torch.Tensor, + alpha: torch.Tensor, + bias: torch.Tensor | None, +) -> torch.Tensor: + blockscaled = _import_b12x_blockscaled() + assert blockscaled is not None + + output_size = int(weight.shape[0]) + output_shape = [*x.shape[:-1], output_size] + x_2d = x.reshape(-1, x.shape[-1]) + x_packed, x_scale_swizzled = scaled_fp4_quant( + x_2d, + input_global_scale_inv, + is_sf_swizzled_layout=True, + ) + output = blockscaled.mm_nvfp4( + x_packed, + x_scale_swizzled, + weight, + weight_scale_storage, + alpha, + out_dtype=x.dtype, + ) + if bias is not None: + output = output + bias + return output.view(*output_shape) + + +def warmup_b12x_nvfp4_linear( + model: torch.nn.Module, + *, + max_tokens: int, + cudagraph_capture_sizes: Iterable[int] = (), + output_dtype: torch.dtype = torch.bfloat16, +) -> int: + if not current_platform.is_cuda(): + return 0 + if not current_platform.is_device_capability_family(120): + return 0 + if output_dtype not in (torch.bfloat16, torch.float16): + output_dtype = torch.bfloat16 + layer_map: dict[tuple[Any, ...], torch.nn.Module] = {} + for layer in model.modules(): + if not getattr(layer, "b12x_nvfp4_linear", False): + continue + weight = layer.weight + weight_scale = layer.weight_scale + n, packed_k = map(int, weight.shape) + signature = ( + weight.device, + n, + packed_k * 2, + weight.dtype, + weight_scale.dtype, + output_dtype, + ) + layer_map.setdefault(signature, layer) + if not layer_map: + return 0 + if _import_b12x_blockscaled() is None: + return 0 + + token_counts = b12x_warmup_token_counts( + max_tokens=max_tokens, + cudagraph_capture_sizes=cudagraph_capture_sizes, + ) + warmed = 0 + last_device: torch.device | None = None + + with torch.inference_mode(): + for signature, layer in layer_map.items(): + weight = layer.weight + weight_scale = layer.weight_scale + k = signature[2] + last_device = weight.device + for tokens in token_counts: + source = torch.zeros( + (tokens, k), + dtype=output_dtype, + device=weight.device, + ) + _apply_b12x_nvfp4_linear( + source, + weight, + weight_scale, + layer.input_global_scale_inv, + layer.alpha, + None, + ) + warmed += 1 + + if warmed > 0 and last_device is not None and last_device.type == "cuda": + torch.accelerator.synchronize(last_device) + + return warmed + + +class B12xNvFp4LinearKernel(NvFp4LinearKernel): + """ModelOpt NVFP4 linear through the native B12X SM120 dense GEMM.""" + + @classmethod + def is_supported( + cls, compute_capability: int | None = None + ) -> tuple[bool, str | None]: + del compute_capability + if not current_platform.is_cuda(): + return False, "B12X NVFP4 kernels are only available on CUDA" + if not current_platform.is_device_capability_family(120): + return False, "B12X NVFP4 kernels require a Blackwell 12x device" + blockscaled = _import_b12x_blockscaled() + if blockscaled is None or _import_b12x_intrinsics() is None: + return False, "Install the B12X backend with `pip install vllm[b12x]`" + if not blockscaled.is_supported(): + return False, "b12x native NVFP4 GEMM is not supported" + return True, None + + @classmethod + def can_implement(cls, config: NvFp4LinearLayerConfig) -> tuple[bool, str | None]: + del config + return True, None + + def process_weights_after_loading(self, layer: torch.nn.Module) -> None: + intrinsics = _import_b12x_intrinsics() + assert intrinsics is not None + replace_parameter( + layer, + "weight_scale", + intrinsics.swizzle_block_scale(layer.weight_scale.data), + ) + layer.b12x_nvfp4_linear = True + + def apply_weights( + self, + layer: torch.nn.Module, + x: torch.Tensor, + bias: torch.Tensor | None = None, + ) -> torch.Tensor: + return _apply_b12x_nvfp4_linear( + x, + layer.weight, + layer.weight_scale, + layer.input_global_scale_inv, + layer.alpha, + bias, + ) + + +__all__ = ["B12xNvFp4LinearKernel", "warmup_b12x_nvfp4_linear"] diff --git a/vllm/model_executor/kernels/linear/scaled_mm/b12x_block.py b/vllm/model_executor/kernels/linear/scaled_mm/b12x_block.py new file mode 100644 index 0000000000..c2d12549fb --- /dev/null +++ b/vllm/model_executor/kernels/linear/scaled_mm/b12x_block.py @@ -0,0 +1,214 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +from __future__ import annotations + +from collections.abc import Iterable +from typing import Any + +import torch + +from vllm.model_executor.layers.quantization.utils.fp8_utils import ( + _upcast_e8m0_to_fp32, +) +from vllm.model_executor.layers.quantization.utils.quant_utils import GroupShape +from vllm.model_executor.utils import replace_parameter +from vllm.platforms import current_platform +from vllm.utils.b12x import ( + b12x_warmup_token_counts, +) +from vllm.utils.b12x import ( + get_b12x_blockscaled as _import_b12x_blockscaled, +) + +from .BlockScaledMMLinearKernel import ( + Fp8BlockScaledMMLinearKernel, + FP8ScaledMMLinearLayerConfig, +) + + +def _run_b12x_fp8_block_scaled_mm( + a: torch.Tensor, + weight: torch.Tensor, + a_scale: torch.Tensor, + weight_scale: torch.Tensor, + out_dtype: torch.dtype, +) -> torch.Tensor: + blockscaled = _import_b12x_blockscaled() + assert blockscaled is not None + + return blockscaled.mm_block_fp8( + a, + a_scale, + weight, + weight_scale, + out_dtype=out_dtype, + ) + + +def warmup_b12x_block_fp8_linear( + model: torch.nn.Module, + *, + max_tokens: int, + cudagraph_capture_sizes: Iterable[int] = (), + output_dtype: torch.dtype = torch.bfloat16, +) -> int: + if not current_platform.is_cuda(): + return 0 + if not current_platform.is_device_capability_family(120): + return 0 + if output_dtype not in (torch.bfloat16, torch.float16): + output_dtype = torch.bfloat16 + + layer_map: dict[tuple[Any, ...], torch.nn.Module] = {} + for layer in model.modules(): + if not getattr(layer, "b12x_block_fp8_linear", False): + continue + weight = layer.weight + weight_scale = getattr(layer, "weight_scale_inv", None) + if weight_scale is None: + weight_scale = layer.weight_scale + n, k = map(int, weight.shape) + signature = ( + weight.device, + n, + k, + weight.dtype, + weight_scale.dtype, + output_dtype, + ) + layer_map.setdefault(signature, layer) + if not layer_map: + return 0 + + blockscaled = _import_b12x_blockscaled() + if blockscaled is None: + return 0 + token_counts = b12x_warmup_token_counts( + max_tokens=max_tokens, + cudagraph_capture_sizes=cudagraph_capture_sizes, + ) + warmed = 0 + + with torch.inference_mode(): + for signature, layer in layer_map.items(): + weight = layer.weight + weight_scale = getattr(layer, "weight_scale_inv", None) + if weight_scale is None: + weight_scale = layer.weight_scale + k = signature[2] + for tokens in token_counts: + a = torch.empty( + (tokens, k), + dtype=weight.dtype, + device=weight.device, + ) + a_scale = torch.empty( + (tokens, k // 128), + dtype=torch.float32, + device=weight.device, + ) + _run_b12x_fp8_block_scaled_mm( + a, + weight, + a_scale, + weight_scale, + output_dtype, + ) + warmed += 1 + return warmed + + +class B12xFp8BlockScaledMMKernel(Fp8BlockScaledMMLinearKernel): + """K128 block-FP8 linear through the native B12X SM120 dense GEMM.""" + + @classmethod + def is_supported( + cls, + compute_capability: int | None = None, + ) -> tuple[bool, str | None]: + del compute_capability + if not current_platform.is_cuda(): + return False, "B12X FP8 kernels are only available on CUDA" + if not current_platform.is_device_capability_family(120): + return False, "B12X FP8 kernels require a Blackwell 12x device" + blockscaled = _import_b12x_blockscaled() + if blockscaled is None: + return False, "Install the B12X backend with `pip install vllm[b12x]`" + if not blockscaled.is_supported(): + return False, "B12X regular block-FP8 GEMM is not supported" + return True, None + + @classmethod + def can_implement( + cls, + config: FP8ScaledMMLinearLayerConfig, + ) -> tuple[bool, str | None]: + can_implement_base, reason = super().can_implement(config) + if not can_implement_base: + return can_implement_base, reason + + if config.input_dtype not in (torch.bfloat16, torch.float16): + return False, "Supports only bf16/fp16 input dtype" + if config.input_dtype != config.out_dtype: + return False, "Input and output dtype must match" + + act_group_shape = config.activation_quant_key.scale.group_shape + if act_group_shape != GroupShape(1, 128): + return ( + False, + "Supports only dynamic per-token group activation quantization " + "with group_shape=(1,128)", + ) + weight_group_shape = config.weight_quant_key.scale.group_shape + if weight_group_shape != GroupShape(128, 128): + return False, "Supports only 128x128 block-scaled FP8 weights" + + out_features, in_features = config.weight_shape + if in_features <= 0 or in_features % 128 != 0: + return False, "Input features must be a positive multiple of 128" + if out_features <= 0 or out_features % 128 != 0: + return False, "Output features must be a positive multiple of 128" + return True, None + + def process_weights_after_loading(self, layer: torch.nn.Module) -> None: + super().process_weights_after_loading(layer) + params = self._get_layer_params(layer) + if params.weight_scale_inv is not None: + weight_scale = params.weight_scale_inv + scale_attr = params.WEIGHT_SCALE_INV + else: + weight_scale = params.weight_scale + scale_attr = params.WEIGHT_SCALE + if weight_scale is not None and weight_scale.dtype in ( + torch.float8_e8m0fnu, + torch.uint8, + ): + # TODO: Remove once B12X supports 128x128 UE8M0 block scales. + replace_parameter( + layer, + scale_attr, + _upcast_e8m0_to_fp32(weight_scale).contiguous(), + ) + layer.b12x_block_fp8_linear = True + + def apply_block_scaled_mm( + self, + A: torch.Tensor, + B: torch.Tensor, + As: torch.Tensor, + Bs: torch.Tensor, + ) -> torch.Tensor: + return _run_b12x_fp8_block_scaled_mm( + A, + B, + As, + Bs, + self.config.out_dtype, + ) + + +__all__ = [ + "B12xFp8BlockScaledMMKernel", + "warmup_b12x_block_fp8_linear", +] diff --git a/vllm/model_executor/kernels/linear/scaled_mm/b12x_tensor.py b/vllm/model_executor/kernels/linear/scaled_mm/b12x_tensor.py new file mode 100644 index 0000000000..46b27a7d4b --- /dev/null +++ b/vllm/model_executor/kernels/linear/scaled_mm/b12x_tensor.py @@ -0,0 +1,238 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project + +from __future__ import annotations + +from collections.abc import Iterable +from typing import Any + +import torch + +from vllm.model_executor.utils import replace_parameter +from vllm.platforms import current_platform +from vllm.utils.b12x import ( + b12x_warmup_token_counts, + reuse_packed_weight_storage, +) +from vllm.utils.b12x import ( + get_b12x_tensor_fp8_linear as _import_b12x_tensor_fp8, +) +from vllm.utils.torch_utils import current_stream + +from .ScaledMMLinearKernel import ( + FP8ScaledMMLinearKernel, + FP8ScaledMMLinearLayerConfig, +) + + +def _apply_b12x_tensor_fp8_packed_linear( + layer: torch.nn.Module, + x_q: torch.Tensor, + bias: torch.Tensor | None, + out_dtype: torch.dtype, +) -> torch.Tensor: + packed_weight = getattr(layer, "b12x_tensor_fp8_packed_weight", None) + if packed_weight is None: + raise RuntimeError( + "b12x tensor FP8 packed weights are missing; " + "process_weights_after_loading did not run for this layer" + ) + + tensor_fp8 = _import_b12x_tensor_fp8() + assert tensor_fp8 is not None + + input_2d = x_q.reshape(-1, x_q.shape[-1]).contiguous() + output_shape = [*x_q.shape[:-1], int(packed_weight.out_features)] + output = tensor_fp8.mm( + input_2d, + packed_weight, + bias=bias, + out_dtype=out_dtype, + expected_m=max(1, int(input_2d.shape[0])), + ) + return output.view(*output_shape) + + +def warmup_b12x_tensor_fp8_linear( + model: torch.nn.Module, + *, + max_tokens: int, + cudagraph_capture_sizes: Iterable[int] = (), + output_dtype: torch.dtype = torch.bfloat16, +) -> int: + if not current_platform.is_cuda(): + return 0 + if not current_platform.is_device_capability_family(120): + return 0 + + if output_dtype not in (torch.bfloat16, torch.float16): + output_dtype = torch.bfloat16 + + layer_map: dict[tuple[Any, ...], Any] = {} + for layer in model.modules(): + packed_weight = getattr( + layer, + "b12x_tensor_fp8_packed_weight", + None, + ) + if packed_weight is None: + continue + device = torch.device(packed_weight.values.device) + signature = ( + device, + int(packed_weight.in_features), + int(packed_weight.padded_in_features), + int(packed_weight.out_features), + output_dtype, + ) + layer_map.setdefault(signature, packed_weight) + if not layer_map: + return 0 + + tensor_fp8 = _import_b12x_tensor_fp8() + if tensor_fp8 is None: + return 0 + + token_counts = b12x_warmup_token_counts( + max_tokens=max_tokens, + cudagraph_capture_sizes=cudagraph_capture_sizes, + ) + warmed = 0 + last_device: torch.device | None = None + + with torch.inference_mode(): + for signature, packed_weight in layer_map.items(): + last_device = signature[0] + warmed += int( + tensor_fp8.prewarm( + packed_weight, + token_counts, + out_dtype=output_dtype, + stream=current_stream().cuda_stream, + ) + ) + + if warmed > 0 and last_device is not None and last_device.type == "cuda": + torch.accelerator.synchronize(last_device) + + return warmed + + +class B12xTensorFP8ScaledMMLinearKernel(FP8ScaledMMLinearKernel): + """Static per-tensor FP8 linear through the B12X SM12x dense GEMM.""" + + @classmethod + def is_supported( + cls, + compute_capability: int | None = None, + ) -> tuple[bool, str | None]: + del compute_capability + if not current_platform.is_cuda(): + return False, "b12x tensor FP8 kernels are only available on CUDA" + if not current_platform.is_device_capability_family(120): + return False, "b12x tensor FP8 kernels require a Blackwell 12x device" + tensor_fp8 = _import_b12x_tensor_fp8() + if tensor_fp8 is None: + return False, "Install the B12X backend with `pip install vllm[b12x]`" + if not tensor_fp8.is_supported(): + return False, "b12x.gemm.tensor_fp8_linear is not supported" + return True, None + + @classmethod + def can_implement( + cls, + config: FP8ScaledMMLinearLayerConfig, + ) -> tuple[bool, str | None]: + activation_scale = config.activation_quant_key.scale + weight_scale = config.weight_quant_key.scale + if ( + not activation_scale.static + or not activation_scale.group_shape.is_per_tensor() + ): + return False, "requires static per-tensor activation scales" + if not weight_scale.static or not weight_scale.group_shape.is_per_tensor(): + return False, "requires static per-tensor weight scales" + if config.input_dtype not in (torch.bfloat16, torch.float16): + return False, "supports only bf16/fp16 input dtype" + if config.out_dtype not in (torch.bfloat16, torch.float16): + return False, "supports only bf16/fp16 output dtype" + out_features, in_features = config.weight_shape + if out_features <= 0 or in_features <= 0 or in_features % 32 != 0: + return False, "weight dimensions must be positive with K divisible by 32" + return True, None + + def process_weights_after_loading(self, layer: torch.nn.Module) -> None: + weight, weight_scale, input_scale, _ = self._get_layer_params(layer) + if weight.dtype != torch.float8_e4m3fn: + raise ValueError( + f"b12x tensor FP8 requires float8_e4m3fn weight, got {weight.dtype}" + ) + if weight_scale.numel() != 1 or input_scale is None or input_scale.numel() != 1: + raise ValueError( + "b12x tensor FP8 requires scalar weight and activation scales" + ) + + out_features, in_features = map(int, self.config.weight_shape) + if tuple(weight.shape) != (in_features, out_features): + raise ValueError( + "b12x tensor FP8 expects the processed weight in [K,N] layout, " + f"got {tuple(weight.shape)} for N={out_features}, K={in_features}" + ) + + tensor_fp8 = _import_b12x_tensor_fp8() + assert tensor_fp8 is not None + output_scale = ( + input_scale.detach().to(torch.float32).reshape(1) + * weight_scale.detach().to(torch.float32).reshape(1) + ).contiguous() + packed_weight = tensor_fp8.pack_weight( + weight.detach().T.contiguous(), + output_scale, + ) + layer.b12x_tensor_fp8_packed_weight = reuse_packed_weight_storage( + getattr(layer, "b12x_tensor_fp8_packed_weight", None), + packed_weight, + ) + weight_name, weight_scale_name, _, _ = self.layer_param_names + replace_parameter(layer, weight_name, weight.new_empty((0,))) + replace_parameter(layer, weight_scale_name, weight_scale.new_empty((0,))) + + def apply_weights( + self, + layer: torch.nn.Module, + x: torch.Tensor, + bias: torch.Tensor | None = None, + ) -> torch.Tensor: + if not isinstance(x, torch.Tensor): + raise TypeError("b12x tensor FP8 linear requires a Tensor input") + _, _, input_scale, input_scale_ub = self._get_layer_params(layer) + input_2d = x.reshape(-1, x.shape[-1]) + x_q, _ = self.quant_fp8(input_2d, input_scale, input_scale_ub) + out_dtype = self.config.out_dtype + output = _apply_b12x_tensor_fp8_packed_linear( + layer, + x_q, + bias, + out_dtype, + ) + return output.view(*x.shape[:-1], output.shape[-1]) + + def apply_scaled_mm( + self, + *, + A: torch.Tensor, + B: torch.Tensor, + out_dtype: torch.dtype, + As: torch.Tensor, + Bs: torch.Tensor, + bias: torch.Tensor | None, + output_shape: list, + ) -> torch.Tensor: + del A, B, out_dtype, As, Bs, bias, output_shape + raise NotImplementedError("b12x tensor FP8 linear overrides apply_weights") + + +__all__ = [ + "B12xTensorFP8ScaledMMLinearKernel", + "warmup_b12x_tensor_fp8_linear", +] diff --git a/vllm/model_executor/warmup/b12x_warmup.py b/vllm/model_executor/warmup/b12x_warmup.py new file mode 100644 index 0000000000..daaa078628 --- /dev/null +++ b/vllm/model_executor/warmup/b12x_warmup.py @@ -0,0 +1,60 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Warm B12X JIT kernels used by a loaded model.""" + +from typing import TYPE_CHECKING + +import torch + +from vllm.logger import init_logger +from vllm.model_executor.kernels.linear.mxfp4.b12x import ( + warmup_b12x_mxfp4_linear, +) +from vllm.model_executor.kernels.linear.mxfp8.b12x import ( + warmup_b12x_mxfp8_linear, +) +from vllm.model_executor.kernels.linear.nvfp4.b12x import ( + warmup_b12x_nvfp4_linear, +) +from vllm.model_executor.kernels.linear.scaled_mm.b12x_block import ( + warmup_b12x_block_fp8_linear, +) +from vllm.model_executor.kernels.linear.scaled_mm.b12x_tensor import ( + warmup_b12x_tensor_fp8_linear, +) + +if TYPE_CHECKING: + from vllm.v1.worker.gpu_worker import Worker + +logger = init_logger(__name__) + + +def b12x_warmup(worker: "Worker", cudagraph_capture_sizes: list[int]) -> None: + model = worker.get_model() + max_tokens = worker.scheduler_config.max_num_batched_tokens + output_dtype = getattr( + getattr(worker, "model_config", None), + "dtype", + torch.bfloat16, + ) + + warmup_kwargs = { + "max_tokens": max_tokens, + "cudagraph_capture_sizes": cudagraph_capture_sizes, + "output_dtype": output_dtype, + } + providers = ( + ("block-FP8", warmup_b12x_block_fp8_linear), + ("MXFP8", warmup_b12x_mxfp8_linear), + ("tensor FP8", warmup_b12x_tensor_fp8_linear), + ("MXFP4", warmup_b12x_mxfp4_linear), + ("NVFP4", warmup_b12x_nvfp4_linear), + ) + for name, warmup in providers: + warmed = warmup(model, **warmup_kwargs) + if warmed: + logger.info_once( + "Warmed up %d B12X %s linear GEMM signatures.", + warmed, + name, + ) diff --git a/vllm/model_executor/warmup/kernel_warmup.py b/vllm/model_executor/warmup/kernel_warmup.py index c35e1ac30c..cd16c63b58 100644 --- a/vllm/model_executor/warmup/kernel_warmup.py +++ b/vllm/model_executor/warmup/kernel_warmup.py @@ -12,6 +12,7 @@ import torch import vllm.envs as envs from vllm.logger import init_logger +from vllm.model_executor.warmup.b12x_warmup import b12x_warmup from vllm.model_executor.warmup.cutedsl_warmup import cutedsl_warmup from vllm.model_executor.warmup.deep_gemm_warmup import deep_gemm_warmup from vllm.model_executor.warmup.deepseek_v4_mhc_warmup import ( @@ -113,15 +114,16 @@ def kernel_warmup(worker: "Worker", *, process_local_only: bool = False): qwen_triton_warmup(worker.model_runner, worker.vllm_config.model_config) + compilation_config = worker.vllm_config.compilation_config + cudagraph_capture_sizes = list(compilation_config.cudagraph_capture_sizes or []) + # DSv4 mHC TileLang kernels (hc_pre/hc_post/hc_head_op) run every decoder # layer per token; warm them across token sizes first so the first real # request doesn't pay JIT cost. No-op for non-DSv4 models (gated inside). deepseek_v4_mhc_warmup( worker.get_model(), max_tokens=worker.scheduler_config.max_num_batched_tokens, - cudagraph_capture_sizes=( - worker.vllm_config.compilation_config.cudagraph_capture_sizes or [] - ), + cudagraph_capture_sizes=cudagraph_capture_sizes, ) # Run next so input-prep kernels JIT against pristine runner state. @@ -156,6 +158,8 @@ def kernel_warmup(worker: "Worker", *, process_local_only: bool = False): max_tokens = worker.scheduler_config.max_num_batched_tokens deep_gemm_warmup(model, max_tokens) + b12x_warmup(worker, cudagraph_capture_sizes) + minimax_m3_msa_warmup(worker) enable_flashinfer_autotune = ( diff --git a/vllm/utils/b12x.py b/vllm/utils/b12x.py new file mode 100644 index 0000000000..55afa35f09 --- /dev/null +++ b/vllm/utils/b12x.py @@ -0,0 +1,101 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Lazy accessors for the optional ``b12x`` package.""" + +import functools +import importlib +import importlib.util +from collections.abc import Iterable +from dataclasses import fields, is_dataclass +from types import ModuleType +from typing import Any + +import torch + + +@functools.cache +def has_b12x() -> bool: + """Return whether the B12X package is installed.""" + return importlib.util.find_spec("b12x") is not None + + +@functools.cache +def _get_submodule(module_name: str) -> ModuleType | None: + if not has_b12x(): + return None + try: + return importlib.import_module(module_name) + except (ImportError, ModuleNotFoundError): + return None + + +def get_b12x_blockscaled() -> ModuleType | None: + return _get_submodule("b12x.gemm.blockscaled") + + +def get_b12x_intrinsics() -> ModuleType | None: + return _get_submodule("b12x._lib.intrinsics") + + +def get_b12x_mxfp8_linear() -> ModuleType | None: + return _get_submodule("b12x.gemm.mxfp8_linear") + + +def get_b12x_tensor_fp8_linear() -> ModuleType | None: + return _get_submodule("b12x.gemm.tensor_fp8_linear") + + +def b12x_warmup_token_counts( + *, + max_tokens: int, + cudagraph_capture_sizes: Iterable[int] = (), +) -> tuple[int, ...]: + # B12X deduplicates shapes that select the same internal kernel policy. + # Keep the complete serving shape set here rather than duplicating its + # policy-selection heuristics in vLLM. + counts = {1} + counts.update(int(size) for size in cudagraph_capture_sizes if int(size) > 0) + if int(max_tokens) > 0: + counts.add(int(max_tokens)) + return tuple(sorted(counts)) + + +def _same_packed_layout(current: Any, replacement: Any) -> bool: + if type(current) is not type(replacement): + return False + if isinstance(current, torch.Tensor): + return ( + current.shape == replacement.shape + and current.stride() == replacement.stride() + and current.dtype == replacement.dtype + and current.device == replacement.device + ) + if is_dataclass(current): + return all( + _same_packed_layout( + getattr(current, field.name), + getattr(replacement, field.name), + ) + for field in fields(current) + ) + return bool(current == replacement) + + +def _copy_packed_tensors(current: Any, replacement: Any) -> None: + if isinstance(current, torch.Tensor): + current.copy_(replacement) + elif is_dataclass(current): + for field in fields(current): + _copy_packed_tensors( + getattr(current, field.name), + getattr(replacement, field.name), + ) + + +@torch.no_grad() +def reuse_packed_weight_storage(current: Any, replacement: Any) -> Any: + """Reuse packed tensor addresses when a compatible weight is reloaded.""" + if current is None or not _same_packed_layout(current, replacement): + return replacement + _copy_packed_tensors(current, replacement) + return current