A high-throughput and memory-efficient inference and serving engine for LLMs
Mirrored from https://github.com/tduncan-lum/Nvidia-Optimization-Stack---VLLM.git
Synced Nov 14, 05:30 UTC
[Performance] Move apply_w8a8_block_fp8_linear to an op class (#24666)
Signed-off-by: ElizaWszola <ewszola@redhat.com> Signed-off-by: ElizaWszola <elizaw.9289@gmail.com> Signed-off-by: Luka Govedič <lgovedic@redhat.com> Signed-off-by: Luka Govedič <ProExpertProg@users.noreply.github.com> Co-authored-by: Luka Govedič <ProExpertProg@users.noreply.github.com> Co-authored-by: Michael Goin <mgoin64@gmail.com> Co-authored-by: Luka Govedič <lgovedic@redhat.com>
ElizaWszola committed
Sep 23, 2025 at 21:03 UTC
63400259d05485330fb23635af892b3fce160dea
14 files changed
+345
-205
benchmarks/cutlass_benchmarks/w8a8_benchmarks.py
+2
-2
@@ -17,7 +17,7 @@ from weight_shapes import WEIGHT_SHAPES
17
18
from vllm import _custom_ops as ops
19
from vllm.model_executor.layers.quantization.utils.fp8_utils import (
20
- w8a8_block_fp8_matmul,
20
+ w8a8_triton_block_scaled_mm,
21
)
22
from vllm.utils import FlexibleArgumentParser, cdiv
23
@@ -158,7 +158,7 @@ def bench_fp8(
158
"cutlass_fp8_fp8_fp16_scaled_mm_bias": lambda: ops.cutlass_scaled_mm(
159
a, b, scale_a, scale_b, torch.float16, bias.to(dtype=torch.float16)
160
),
161
- "triton_fp8_fp8_fp16_scaled_mm_blockwise": lambda: w8a8_block_fp8_matmul(
161
+ "triton_fp8_fp8_fp16_scaled_mm_blockwise": lambda: w8a8_triton_block_scaled_mm(
162
a_cont, b.t(), block_scale_a, block_scale_b.t(), (128, 128)
163
),
164
"cutlass_fp8_fp8_fp16_scaled_mm_blockwise": lambda: ops.cutlass_scaled_mm(
benchmarks/kernels/deepgemm/benchmark_fp8_block_dense_gemm.py
+2
-2
@@ -10,7 +10,7 @@ from vllm import _custom_ops as ops
10
from vllm.model_executor.layers.quantization.utils.fp8_utils import (
11
get_col_major_tma_aligned_tensor,
12
per_token_group_quant_fp8,
13
- w8a8_block_fp8_matmul,
13
+ w8a8_triton_block_scaled_mm,
14
)
15
from vllm.triton_utils import triton
16
from vllm.utils.deep_gemm import calc_diff, fp8_gemm_nt, per_block_cast_to_fp8
@@ -59,7 +59,7 @@ def benchmark_shape(m: int,
59
60
# === vLLM Triton Implementation ===
61
def vllm_triton_gemm():
62
- return w8a8_block_fp8_matmul(A_vllm,
62
+ return w8a8_triton_block_scaled_mm(A_vllm,
63
B_vllm,
64
A_scale_vllm,
65
B_scale_vllm,
tests/kernels/quantization/test_block_fp8.py
+3
-2
@@ -12,7 +12,7 @@ from tests.kernels.quant_utils import (native_per_token_group_quant_fp8,
12
from vllm.config import VllmConfig
13
from vllm.model_executor.layers.quantization.utils.fp8_utils import (
14
cutlass_scaled_mm, get_col_major_tma_aligned_tensor,
15
- per_token_group_quant_fp8, w8a8_block_fp8_matmul)
15
+ per_token_group_quant_fp8, w8a8_triton_block_scaled_mm)
16
from vllm.platforms import current_platform
17
from vllm.utils import has_deep_gemm
18
from vllm.utils.deep_gemm import fp8_gemm_nt, per_block_cast_to_fp8
@@ -90,7 +90,8 @@ def test_w8a8_block_fp8_matmul(M, N, K, block_size, out_dtype, seed):
90
91
ref_out = native_w8a8_block_matmul(A_fp8, B_fp8, As, Bs, block_size,
92
out_dtype)
93
- out = w8a8_block_fp8_matmul(A_fp8, B_fp8, As, Bs, block_size, out_dtype)
93
+ out = w8a8_triton_block_scaled_mm(A_fp8, B_fp8, As, Bs, block_size,
94
+ out_dtype)
95
96
rel_diff = (torch.mean(
97
torch.abs(out.to(torch.float32) - ref_out.to(torch.float32))) /
tests/kernels/quantization/test_fp8_quant_group.py
+19
-7
@@ -20,9 +20,11 @@ from vllm.platforms import current_platform
20
(8, 513, 64), # Non-divisible (native only)
21
])
22
@pytest.mark.parametrize("seed", [42])
23
+@pytest.mark.parametrize("use_ue8m0", [True, False])
24
@torch.inference_mode()
25
def test_quantfp8_group_functionality(batch_size: int, hidden_dim: int,
25
- group_size: int, seed: int) -> None:
26
+ group_size: int, seed: int,
27
+ use_ue8m0: bool) -> None:
28
"""Test QuantFP8 group quantization with various configurations.
29
30
Tests both CUDA and native implementations, column-major scales,
@@ -38,7 +40,8 @@ def test_quantfp8_group_functionality(batch_size: int, hidden_dim: int,
40
group_shape = GroupShape(1, group_size)
41
quant_op = QuantFP8(static=False,
42
group_shape=group_shape,
41
- column_major_scales=False)
43
+ column_major_scales=False,
44
+ use_ue8m0=use_ue8m0)
45
46
# 1. Test native implementation (always available)
47
x_quant_native, scales_native = quant_op.forward_native(x.clone())
@@ -48,9 +51,15 @@ def test_quantfp8_group_functionality(batch_size: int, hidden_dim: int,
51
# 2. Test column-major scales configuration
52
quant_op_col = QuantFP8(static=False,
53
group_shape=group_shape,
51
- column_major_scales=True)
54
+ column_major_scales=True,
55
+ use_ue8m0=use_ue8m0)
56
_, scales_col = quant_op_col.forward_native(x.clone())
53
- assert scales_col.shape == (expected_num_groups, batch_size)
57
+ assert scales_col.shape == (batch_size, expected_num_groups)
58
+ assert scales_col.stride(0) == 1
59
+ assert scales_col.stride(1) == batch_size
60
+
61
+ # Test column-major scales consistency
62
+ assert torch.allclose(scales_col, scales_native, rtol=1e-9, atol=1e-8)
63
64
# 3. Test CUDA implementation (only for divisible dimensions)
65
if is_divisible:
@@ -68,8 +77,9 @@ def test_quantfp8_group_functionality(batch_size: int, hidden_dim: int,
77
78
79
@pytest.mark.parametrize("seed", [42])
80
+@pytest.mark.parametrize("use_ue8m0", [True, False])
81
@torch.inference_mode()
72
-def test_quantfp8_group_multidimensional(seed: int) -> None:
82
+def test_quantfp8_group_multidimensional(seed: int, use_ue8m0: bool) -> None:
83
current_platform.seed_everything(seed)
84
85
group_size = 64
@@ -82,7 +92,8 @@ def test_quantfp8_group_multidimensional(seed: int) -> None:
92
group_shape = GroupShape(1, group_size)
93
quant_op = QuantFP8(static=False,
94
group_shape=group_shape,
85
- column_major_scales=False)
95
+ column_major_scales=False,
96
+ use_ue8m0=use_ue8m0)
97
98
x_quant, scales = quant_op.forward_native(x_3d.clone())
99
assert x_quant.shape == x_3d.shape
@@ -91,7 +102,8 @@ def test_quantfp8_group_multidimensional(seed: int) -> None:
102
# Test column_major_scales with multi-dim
103
quant_op_col = QuantFP8(static=False,
104
group_shape=group_shape,
94
- column_major_scales=True)
105
+ column_major_scales=True,
106
+ use_ue8m0=use_ue8m0)
107
_, scales_col = quant_op_col.forward_native(x_3d.clone())
108
assert scales_col.shape == (batch1, hidden_dim // group_size, batch2)
109
tests/model_executor/test_enabled_custom_ops.py
-30
@@ -17,8 +17,6 @@ from vllm.model_executor.layers.fused_moe.rocm_aiter_fused_moe import (
17
from vllm.model_executor.layers.layernorm import (RMSNorm,
18
dispatch_rocm_rmsnorm_func,
19
fused_add_rms_norm, rms_norm)
20
-from vllm.model_executor.layers.quantization.utils.fp8_utils import (
21
- cutlass_scaled_mm, dispatch_w8a8_blockscale_func, w8a8_block_fp8_matmul)
20
from vllm.platforms import current_platform
21
22
RMS_NORM_SUPPORTED_DTYPES = [torch.float16, torch.bfloat16]
@@ -111,34 +109,6 @@ def test_enabled_ops_invalid(env: str):
109
RMSNorm(1024).enabled()
110
111
114
-@pytest.mark.skipif(
115
- not current_platform.is_rocm() or not current_platform.is_fp8_fnuz(),
116
- reason="AITER is a feature exclusive for ROCm and FP8_FNUZ")
117
-@pytest.mark.parametrize("use_cutlass", [True, False])
118
-@pytest.mark.parametrize("use_rocm_aiter", ["0", "1"])
119
-@pytest.mark.parametrize("use_rocm_aiter_gemm_w8a8_blockscale", ["0", "1"])
120
-def test_w8a8_blockscale_dispatch(use_cutlass: bool, use_rocm_aiter: str,
121
- use_rocm_aiter_gemm_w8a8_blockscale: str,
122
- monkeypatch):
123
-
124
- monkeypatch.setenv("VLLM_ROCM_USE_AITER", use_rocm_aiter)
125
- monkeypatch.setenv("VLLM_ROCM_USE_AITER_LINEAR",
126
- use_rocm_aiter_gemm_w8a8_blockscale)
127
-
128
- use_aiter_and_is_supported = (bool(int(use_rocm_aiter)) and bool(
129
- int(use_rocm_aiter_gemm_w8a8_blockscale)))
130
- block_scale_func = dispatch_w8a8_blockscale_func(
131
- use_cutlass, use_aiter_and_is_supported=use_aiter_and_is_supported)
132
- if use_cutlass:
133
- assert block_scale_func == cutlass_scaled_mm
134
- elif current_platform.is_rocm() and int(use_rocm_aiter) and int(
135
- use_rocm_aiter_gemm_w8a8_blockscale):
136
- assert block_scale_func == (
137
- torch.ops.vllm.rocm_aiter_gemm_w8a8_blockscale)
138
- else:
139
- assert block_scale_func == w8a8_block_fp8_matmul
140
-
141
-
112
@pytest.mark.parametrize("use_rocm_aiter", ["0", "1"])
113
def test_topk_dispatch(use_rocm_aiter: str, monkeypatch):
114
monkeypatch.setenv("VLLM_ROCM_USE_AITER", use_rocm_aiter)
tests/quantization/test_compressed_tensors.py
+35
@@ -18,6 +18,9 @@ from vllm.model_executor.layers.quantization.compressed_tensors.compressed_tenso
18
CompressedTensorsW4A16Fp4, CompressedTensorsW4A16Sparse24,
19
CompressedTensorsW8A8Fp8, CompressedTensorsW8A8Int8,
20
CompressedTensorsW8A16Fp8, CompressedTensorsWNA16)
21
+from vllm.model_executor.layers.quantization.input_quant_fp8 import QuantFP8
22
+from vllm.model_executor.layers.quantization.utils.fp8_utils import (
23
+ W8A8BlockFp8LinearOp)
24
from vllm.model_executor.layers.quantization.utils.quant_utils import (
25
cutlass_fp4_supported)
26
from vllm.model_executor.layers.quantization.utils.w8a8_utils import (
@@ -742,3 +745,35 @@ def test_compressed_tensors_transforms_perplexity(vllm_runner, model, prompt,
745
perplexity = llm.generate_prompt_perplexity([prompt])[0]
746
print(perplexity)
747
assert perplexity <= exp_perplexity
748
+
749
+
750
+def test_compressed_tensors_fp8_block_enabled(vllm_runner):
751
+ model_path = "RedHatAI/Qwen3-0.6B-FP8-BLOCK"
752
+ with vllm_runner(model_path) as llm:
753
+
754
+ fp8_dtype = current_platform.fp8_dtype()
755
+
756
+ def check_model(model):
757
+ layer = model.model.layers[0]
758
+
759
+ qkv_proj = layer.self_attn.qkv_proj
760
+ assert isinstance(qkv_proj.quant_method,
761
+ CompressedTensorsLinearMethod)
762
+ assert isinstance(qkv_proj.scheme, CompressedTensorsW8A8Fp8)
763
+ assert isinstance(qkv_proj.scheme.w8a8_block_fp8_linear,
764
+ W8A8BlockFp8LinearOp)
765
+
766
+ assert qkv_proj.weight.dtype is fp8_dtype
767
+ assert qkv_proj.weight_scale.dtype is torch.float32
768
+ assert len(qkv_proj.weight.shape) == 2
769
+ assert len(qkv_proj.weight_scale.shape) == 2
770
+
771
+ input_quant_op = \
772
+ qkv_proj.scheme.w8a8_block_fp8_linear.input_quant_op
773
+ assert isinstance(input_quant_op, QuantFP8)
774
+ assert input_quant_op._forward_method == input_quant_op.forward_cuda
775
+
776
+ llm.apply_model(check_model)
777
+
778
+ output = llm.generate_greedy("Hello my name is", max_tokens=20)
779
+ assert output
vllm/config/__init__.py
+17
@@ -687,6 +687,23 @@ class VllmConfig:
687
# local attention.
688
self.scheduler_config.disable_hybrid_kv_cache_manager = True
689
690
+ def has_blocked_weights():
691
+ if self.quant_config is not None:
692
+ if hasattr(self.quant_config, "weight_block_size"):
693
+ return self.quant_config.weight_block_size is not None
694
+ elif hasattr(self.quant_config, "has_blocked_weights"):
695
+ return self.quant_config.has_blocked_weights()
696
+ return False
697
+
698
+ # Enable quant_fp8 CUDA ops (TODO disable in follow up)
699
+ # On H100 the CUDA kernel is faster than
700
+ # native implementation
701
+ # https://github.com/vllm-project/vllm/issues/25094
702
+ if has_blocked_weights():
703
+ custom_ops = self.compilation_config.custom_ops
704
+ if "none" not in custom_ops and "-quant_fp8" not in custom_ops:
705
+ custom_ops.append("+quant_fp8")
706
+
707
def update_sizes_for_sequence_parallelism(self,
708
possible_sizes: list) -> list:
709
# remove the sizes that not multiple of tp_size when
vllm/model_executor/layers/quantization/compressed_tensors/compressed_tensors.py
+8
@@ -644,6 +644,14 @@ class CompressedTensorsConfig(QuantizationConfig):
644
# If no matches, return None
645
return None
646
647
+ def has_blocked_weights(self) -> bool:
648
+ for scheme in self.target_scheme_map.values():
649
+ weight_quant = scheme.get("weights")
650
+ if (weight_quant is not None
651
+ and weight_quant.strategy == QuantizationStrategy.BLOCK):
652
+ return True
653
+ return False
654
+
655
@staticmethod
656
def supports_cutlass_24(
657
weight_quant: Optional[QuantizationArgs],
vllm/model_executor/layers/quantization/compressed_tensors/schemes/compressed_tensors_w8a8_fp8.py
+26
-11
@@ -11,7 +11,7 @@ from torch.nn import Parameter
11
from vllm.model_executor.layers.quantization.compressed_tensors.schemes import (
12
CompressedTensorsScheme)
13
from vllm.model_executor.layers.quantization.utils.fp8_utils import (
14
- apply_fp8_block_linear, check_aiter_fp8_linear_support,
14
+ W8A8BlockFp8LinearOp, check_aiter_fp8_linear_support,
15
create_fp8_input_scale, create_fp8_scale_parameter,
16
create_fp8_weight_parameter, maybe_post_process_fp8_weight_block,
17
process_fp8_weight_block_strategy, process_fp8_weight_channel_strategy,
@@ -41,16 +41,30 @@ class CompressedTensorsW8A8Fp8(CompressedTensorsScheme):
41
self.strategy = weight_quant.strategy
42
self.out_dtype = torch.get_default_dtype()
43
self.is_static_input_scheme = is_static_input_scheme
44
- self.act_q_group_shape = GroupShape.PER_TENSOR \
45
- if is_static_input_scheme else GroupShape.PER_TOKEN
46
- self.fp8_linear = Fp8LinearOp(
47
- act_quant_static=self.is_static_input_scheme,
48
- act_quant_group_shape=self.act_q_group_shape)
44
45
self.weight_block_size = self.weight_quant.block_structure
46
+ if self.weight_block_size is not None:
47
+ self.act_q_group_shape = GroupShape(1, self.weight_block_size[0])
48
+ else:
49
+ self.act_q_group_shape = GroupShape.PER_TENSOR \
50
+ if is_static_input_scheme else GroupShape.PER_TOKEN
51
+
52
self.cutlass_block_fp8_supported = cutlass_block_fp8_supported()
53
self.use_aiter_and_is_supported = check_aiter_fp8_linear_support()
54
55
+ if self.weight_block_size is not None:
56
+ assert not self.is_static_input_scheme
57
+ self.w8a8_block_fp8_linear = W8A8BlockFp8LinearOp(
58
+ weight_group_shape=GroupShape(*self.weight_block_size),
59
+ act_quant_group_shape=self.act_q_group_shape,
60
+ cutlass_block_fp8_supported=self.cutlass_block_fp8_supported,
61
+ use_aiter_and_is_supported=self.use_aiter_and_is_supported,
62
+ )
63
+ else:
64
+ self.fp8_linear = Fp8LinearOp(
65
+ act_quant_static=self.is_static_input_scheme,
66
+ act_quant_group_shape=self.act_q_group_shape)
67
+
68
@classmethod
69
def get_min_capability(cls) -> int:
70
# lovelace and up
@@ -141,13 +155,14 @@ class CompressedTensorsW8A8Fp8(CompressedTensorsScheme):
155
x: torch.Tensor,
156
bias: Optional[torch.Tensor] = None) -> torch.Tensor:
157
144
- if layer.weight_block_size is not None:
145
- return apply_fp8_block_linear(
146
- layer,
158
+ if self.weight_block_size is not None:
159
+ return self.w8a8_block_fp8_linear.apply(
160
input=x,
161
+ weight=layer.weight,
162
+ weight_scale=layer.weight_scale,
163
+ input_scale=layer.input_scale,
164
bias=bias,
149
- cutlass_block_fp8_supported=self.cutlass_block_fp8_supported,
150
- use_aiter_and_is_supported=self.use_aiter_and_is_supported)
165
+ )
166
167
return self.fp8_linear.apply(input=x,
168
weight=layer.weight,
vllm/model_executor/layers/quantization/deepgemm.py
+5
-5
@@ -43,7 +43,7 @@ def prepare_block_fp8_matmul_inputs(
43
return M, N, K, C
44
45
46
-def w8a8_block_fp8_matmul_deepgemm(
46
+def w8a8_deepgemm_block_scaled_mm(
47
A: torch.Tensor,
48
B: torch.Tensor,
49
As: torch.Tensor,
@@ -59,7 +59,7 @@ def w8a8_block_fp8_matmul_deepgemm(
59
return C
60
61
62
-def w8a8_block_fp8_matmul_deepgemm_fake(
62
+def w8a8_deepgemm_block_scaled_mm_fake(
63
A: torch.Tensor,
64
B: torch.Tensor,
65
As: torch.Tensor,
@@ -73,9 +73,9 @@ def w8a8_block_fp8_matmul_deepgemm_fake(
73
74
75
direct_register_custom_op(
76
- op_name="w8a8_block_fp8_matmul_deepgemm",
77
- op_func=w8a8_block_fp8_matmul_deepgemm,
76
+ op_name="w8a8_deepgemm_block_scaled_mm",
77
+ op_func=w8a8_deepgemm_block_scaled_mm,
78
mutates_args=[],
79
- fake_impl=w8a8_block_fp8_matmul_deepgemm_fake,
79
+ fake_impl=w8a8_deepgemm_block_scaled_mm_fake,
80
dispatch_key=current_platform.dispatch_key,
81
)
vllm/model_executor/layers/quantization/fp8.py
+28
-12
@@ -31,7 +31,7 @@ from vllm.model_executor.layers.quantization.utils.flashinfer_utils import (
31
register_moe_scaling_factors, rotate_flashinfer_fp8_moe_weights,
32
select_cutlass_fp8_gemm_impl, swap_w13_to_w31)
33
from vllm.model_executor.layers.quantization.utils.fp8_utils import (
34
- apply_fp8_block_linear, check_aiter_fp8_linear_support,
34
+ W8A8BlockFp8LinearOp, check_aiter_fp8_linear_support,
35
create_fp8_input_scale, create_fp8_scale_parameter,
36
create_fp8_weight_parameter, expert_weight_is_col_major,
37
get_col_major_tma_aligned_tensor, maybe_post_process_fp8_weight_block,
@@ -234,15 +234,28 @@ class Fp8LinearMethod(LinearMethodBase):
234
self.weight_block_size = self.quant_config.weight_block_size
235
self.block_quant = self.weight_block_size is not None
236
self.act_q_static = self.quant_config.activation_scheme == "static"
237
- # Use per-token quantization for better perf if dynamic and cutlass
238
- if not self.act_q_static and cutlass_fp8_supported():
239
- self.act_q_group_shape = GroupShape.PER_TOKEN
237
+ if self.weight_block_size:
238
+ self.act_q_group_shape = GroupShape(1, self.weight_block_size[0])
239
else:
241
- self.act_q_group_shape = GroupShape.PER_TENSOR
240
+ # Use per-token quantization for better perf if dynamic and cutlass
241
+ if not self.act_q_static and cutlass_fp8_supported():
242
+ self.act_q_group_shape = GroupShape.PER_TOKEN
243
+ else:
244
+ self.act_q_group_shape = GroupShape.PER_TENSOR
245
243
- self.fp8_linear = Fp8LinearOp(
244
- act_quant_static=self.act_q_static,
245
- act_quant_group_shape=self.act_q_group_shape)
246
+ if self.block_quant:
247
+ assert not self.act_q_static
248
+ assert self.weight_block_size is not None
249
+ self.w8a8_block_fp8_linear = W8A8BlockFp8LinearOp(
250
+ weight_group_shape=GroupShape(*self.weight_block_size),
251
+ act_quant_group_shape=self.act_q_group_shape,
252
+ cutlass_block_fp8_supported=self.cutlass_block_fp8_supported,
253
+ use_aiter_and_is_supported=self.use_aiter_and_is_supported,
254
+ )
255
+ else:
256
+ self.fp8_linear = Fp8LinearOp(
257
+ act_quant_static=self.act_q_static,
258
+ act_quant_group_shape=self.act_q_group_shape)
259
260
def create_weights(
261
self,
@@ -391,12 +404,15 @@ class Fp8LinearMethod(LinearMethodBase):
404
bias=bias)
405
406
if self.block_quant:
394
- return apply_fp8_block_linear(
395
- layer,
407
+ assert self.weight_block_size is not None
408
+
409
+ return self.w8a8_block_fp8_linear.apply(
410
input=x,
411
+ weight=layer.weight,
412
+ weight_scale=layer.weight_scale,
413
+ input_scale=layer.input_scale,
414
bias=bias,
398
- cutlass_block_fp8_supported=self.cutlass_block_fp8_supported,
399
- use_aiter_and_is_supported=self.use_aiter_and_is_supported)
415
+ )
416
417
return self.fp8_linear.apply(input=x,
418
weight=layer.weight,
vllm/model_executor/layers/quantization/input_quant_fp8.py
+16
-8
@@ -27,11 +27,14 @@ class QuantFP8(CustomOp):
27
This CustomOp supports both static and dynamic quantization.
28
"""
29
30
- def __init__(self,
31
- static: bool,
32
- group_shape: GroupShape,
33
- num_token_padding: Optional[int] = None,
34
- column_major_scales: bool = False):
30
+ def __init__(
31
+ self,
32
+ static: bool,
33
+ group_shape: GroupShape,
34
+ num_token_padding: Optional[int] = None,
35
+ column_major_scales: bool = False,
36
+ use_ue8m0: Optional[bool] = None, # for Torch compile
37
+ ):
38
"""
39
:param static: static or dynamic quantization
40
:param group_shape: quantization group shape (PER_TOKEN, PER_TENSOR,
@@ -46,6 +49,7 @@ class QuantFP8(CustomOp):
49
self.group_shape = group_shape
50
self.num_token_padding = num_token_padding
51
self.column_major_scales = column_major_scales
52
+ self.use_ue8m0 = use_ue8m0
53
54
self.is_group_quant = group_shape.is_per_group()
55
if self.is_group_quant:
@@ -70,7 +74,8 @@ class QuantFP8(CustomOp):
74
x,
75
group_size=self.group_size,
76
column_major_scales=self.column_major_scales,
73
- dtype=_FP8_DTYPE)
77
+ dtype=_FP8_DTYPE,
78
+ use_ue8m0=self.use_ue8m0)
79
80
assert (scale is not None) == self.static
81
assert scale_ub is None or (not self.static and self.group_shape
@@ -137,7 +142,10 @@ class QuantFP8(CustomOp):
142
143
x_grouped = x.view(-1, num_groups, self.group_size)
144
absmax = x_grouped.abs().max(dim=-1, keepdim=True)[0].float()
140
- scales = (absmax / _FP8_MAX).clamp(min=_FP8_MIN_SCALING_FACTOR)
145
+ scales_raw = absmax / _FP8_MAX
146
+ if self.use_ue8m0:
147
+ scales_raw = torch.exp2(torch.ceil(torch.log2(scales_raw)))
148
+ scales = (scales_raw).clamp(min=_FP8_MIN_SCALING_FACTOR)
149
150
x_scaled = x_grouped / scales
151
x_quant = x_scaled.clamp(_FP8_MIN, _FP8_MAX).to(_FP8_DTYPE)
@@ -151,6 +159,6 @@ class QuantFP8(CustomOp):
159
scales = scales.reshape(orig_shape[:-1] + (num_groups, ))
160
161
if self.column_major_scales:
154
- scales = scales.transpose(-2, -1).contiguous()
162
+ scales = scales.transpose(-2, -1).contiguous().transpose(-1, -2)
163
164
return x_quant, scales
vllm/model_executor/layers/quantization/utils/fp8_utils.py
+176
-122
@@ -13,8 +13,9 @@ import torch
13
import vllm.envs as envs
14
from vllm import _custom_ops as ops
15
from vllm.logger import init_logger
16
+from vllm.model_executor.layers.quantization.input_quant_fp8 import QuantFP8
17
from vllm.model_executor.layers.quantization.utils.quant_utils import (
17
- group_broadcast)
18
+ GroupShape, group_broadcast)
19
from vllm.model_executor.layers.quantization.utils.w8a8_utils import (
20
CUTLASS_BLOCK_FP8_SUPPORTED)
21
from vllm.model_executor.parameter import (BlockQuantScaleParameter,
@@ -24,6 +25,7 @@ from vllm.platforms import current_platform
25
from vllm.triton_utils import tl, triton
26
from vllm.utils import cdiv, direct_register_custom_op
27
from vllm.utils.deep_gemm import (is_deep_gemm_e8m0_used,
28
+ is_deep_gemm_supported,
29
should_use_deepgemm_for_fp8_linear)
30
31
logger = init_logger(__name__)
@@ -35,6 +37,8 @@ def is_fp8(x: Union[torch.dtype, torch.Tensor]) -> bool:
37
return x == torch.float8_e4m3fn or x == torch.float8_e4m3fnuz
38
39
40
+# We need to pass in the is_hopper flag as argument because the function
41
+# current_platform.is_device_capability() is not supported by Torch compiler.
42
def cutlass_scaled_mm(
43
A: torch.Tensor,
44
B: torch.Tensor,
@@ -42,15 +46,17 @@ def cutlass_scaled_mm(
46
Bs: torch.Tensor,
47
block_size: list[int],
48
output_dtype: torch.dtype = torch.float16,
49
+ is_hopper: Optional[bool] = None,
50
) -> torch.Tensor:
51
+ if is_hopper is None:
52
+ is_hopper = current_platform.is_device_capability(90)
53
return ops.cutlass_scaled_mm(
54
A,
55
B.T,
56
out_dtype=output_dtype,
57
scale_a=As,
58
# SM90 block FP8 requires row-major scale_b, which we do ahead of time
52
- scale_b=Bs if block_size is not None
53
- and current_platform.is_device_capability(90) else Bs.T)
59
+ scale_b=Bs if block_size is not None and is_hopper else Bs.T)
60
61
62
def rocm_aiter_gemm_w8a8_blockscale_impl(
@@ -98,122 +104,189 @@ if current_platform.is_rocm():
104
aiter_per1x128_quant = get_hip_quant(rocm_aiter.QuantType.per_1x128)
105
106
101
-def dispatch_w8a8_blockscale_func(
102
- use_cutlass: bool, use_aiter_and_is_supported: bool
103
-) -> Callable[[
104
- torch.Tensor,
105
- torch.Tensor,
106
- torch.Tensor,
107
- torch.Tensor,
108
- list[int],
109
- torch.dtype,
110
-], torch.Tensor]:
111
- if use_cutlass:
112
- return cutlass_scaled_mm
113
- if (use_aiter_and_is_supported):
114
- return torch.ops.vllm.rocm_aiter_gemm_w8a8_blockscale
115
- return w8a8_block_fp8_matmul
107
+# TODO we should be able to change the type of block_size to GroupShape
108
+# after we resolve GroupShape compilation issue
109
+# https://github.com/vllm-project/vllm/issues/25270
110
+def _w8a8_triton_block_scaled_mm_func(
111
+ qx: torch.Tensor,
112
+ weight: torch.Tensor,
113
+ x_scale: torch.Tensor,
114
+ weight_scale: torch.Tensor,
115
+ block_size: list[int],
116
+ output_dtype: torch.dtype,
117
+) -> torch.Tensor:
118
+ return w8a8_triton_block_scaled_mm(qx, weight, x_scale, weight_scale,
119
+ block_size, output_dtype)
120
121
118
-# TODO fix ROCm->Triton custom path:
119
-# https://github.com/vllm-project/vllm/issues/14397
120
-def apply_w8a8_block_fp8_linear(
121
- input: torch.Tensor,
122
+def _w8a8_triton_block_scaled_mm_fake(
123
+ qx: torch.Tensor,
124
weight: torch.Tensor,
123
- block_size: list[int],
125
+ x_scale: torch.Tensor,
126
weight_scale: torch.Tensor,
125
- input_scale: Optional[torch.Tensor] = None,
126
- bias: Optional[torch.Tensor] = None,
127
- cutlass_block_fp8_supported: bool = CUTLASS_BLOCK_FP8_SUPPORTED,
128
- use_aiter_and_is_supported: bool = False,
127
+ block_size: list[int],
128
+ output_dtype: torch.dtype,
129
) -> torch.Tensor:
130
- assert input_scale is None
131
- # View input as 2D matrix for fp8 methods
132
- input_2d = input.view(-1, input.shape[-1])
133
- output_shape = [*input.shape[:-1], weight.shape[0]]
134
- output_dtype = input.dtype
130
+ return torch.empty((qx.size(0), weight.size(0)),
131
+ dtype=output_dtype,
132
+ device=qx.device)
133
+
134
136
- if should_use_deepgemm_for_fp8_linear(output_dtype, weight):
135
+direct_register_custom_op(
136
+ "w8a8_triton_block_scaled_mm_func",
137
+ _w8a8_triton_block_scaled_mm_func,
138
+ mutates_args=[],
139
+ fake_impl=_w8a8_triton_block_scaled_mm_fake,
140
+ dispatch_key="CUDA",
141
+)
142
143
+
144
+# TODO fix ROCm->Triton custom path:
145
+# https://github.com/vllm-project/vllm/issues/14397
146
+class W8A8BlockFp8LinearOp:
147
+ """
148
+ This class executes a Blocked FP8 linear layer using cutlass if supported
149
+ and torch.scaled_mm otherwise.
150
+ """
151
+
152
+ def __init__(
153
+ self,
154
+ weight_group_shape: GroupShape,
155
+ act_quant_group_shape: GroupShape,
156
+ cutlass_block_fp8_supported: bool = CUTLASS_BLOCK_FP8_SUPPORTED,
157
+ use_aiter_and_is_supported: bool = False,
158
+ ):
159
+ self.weight_group_shape = weight_group_shape
160
+ self.act_quant_group_shape = act_quant_group_shape
161
+ self.is_deep_gemm_supported = is_deep_gemm_supported()
162
+ self.is_hopper = current_platform.is_device_capability(90)
163
+
164
+ # Get the correct blockscale mul and input quant operations.
165
+ # We can't use _dispatch_w8a8_blockscale_op to figure out if we want
166
+ # to use deepgemm because we don't know the shape of weights (and
167
+ # whether deepgemm supports it) at the init time.
168
+ self.w8a8_blockscale_op, self.input_quant_op = \
169
+ self._dispatch_w8a8_blockscale_op(
170
+ cutlass_block_fp8_supported, use_aiter_and_is_supported)
171
+ self.deepgemm_input_quant_op = (QuantFP8(
172
+ False,
173
+ self.act_quant_group_shape,
174
+ column_major_scales=True,
175
+ use_ue8m0=is_deep_gemm_e8m0_used()) if self.is_deep_gemm_supported
176
+ else None)
177
+
178
+ def apply(
179
+ self,
180
+ input: torch.Tensor,
181
+ weight: torch.Tensor,
182
+ weight_scale: torch.Tensor,
183
+ input_scale: Optional[torch.Tensor] = None,
184
+ bias: Optional[torch.Tensor] = None,
185
+ ) -> torch.Tensor:
186
+ assert input_scale is None
187
+ # View input as 2D matrix for fp8 methods
188
input_2d = input.view(-1, input.shape[-1])
189
output_shape = [*input.shape[:-1], weight.shape[0]]
190
+ output_dtype = input.dtype
191
141
- q_input, x_scale = per_token_group_quant_fp8(
142
- input_2d,
143
- block_size[1],
144
- column_major_scales=True,
145
- )
192
+ if should_use_deepgemm_for_fp8_linear(output_dtype, weight,
193
+ self.is_deep_gemm_supported):
194
+ output = self._run_deepgemm(input, weight, weight_scale)
195
+ if bias is not None:
196
+ output = output + bias
197
+ return output.to(dtype=input.dtype).view(*output_shape)
198
199
+ output = self.w8a8_blockscale_op(input_2d, weight, weight_scale)
200
+ if bias is not None:
201
+ output = output + bias
202
+ return output.to(dtype=input.dtype).view(*output_shape)
203
+
204
+ def _run_deepgemm(
205
+ self,
206
+ input_2d: torch.Tensor,
207
+ weight: torch.Tensor,
208
+ weight_scale: torch.Tensor,
209
+ ) -> torch.Tensor:
210
# ensure DeepGEMM-backed custom op is registered before use
211
import vllm.model_executor.layers.quantization.deepgemm # noqa: F401
212
150
- output = torch.ops.vllm.w8a8_block_fp8_matmul_deepgemm(
213
+ assert self.deepgemm_input_quant_op is not None
214
+ q_input, x_scale = self.deepgemm_input_quant_op(input_2d)
215
+ return torch.ops.vllm.w8a8_deepgemm_block_scaled_mm(
216
q_input,
217
weight,
218
x_scale,
219
weight_scale,
155
- block_size,
156
- output_dtype=output_dtype)
157
- if bias is not None:
158
- output += bias
159
- return output.to(dtype=output_dtype).view(*output_shape)
160
-
161
- w8a8_blockscale_func = dispatch_w8a8_blockscale_func(
162
- cutlass_block_fp8_supported, use_aiter_and_is_supported)
163
- if cutlass_block_fp8_supported:
164
- num_pad = 0
165
- if current_platform.is_device_capability(90):
166
- # pad first dimension to be divisible by 4 due to
167
- # cutlass blockwise gemm limitation for hopper
168
- num_pad = 4 - (input_2d.shape[0] % 4)
169
- if num_pad > 0:
170
- input_2d = torch.nn.functional.pad(input_2d,
171
- (0, 0, 0, num_pad),
172
- "constant", 0)
173
- q_input, x_scale = per_token_group_quant_fp8(input_2d,
174
- block_size[1],
175
- column_major_scales=True)
176
- output = w8a8_blockscale_func(q_input, weight, x_scale, weight_scale,
177
- block_size, input.dtype)
178
- if num_pad > 0:
179
- output = output[:-num_pad]
180
- else:
181
- if use_aiter_and_is_supported:
182
- q_input, x_scale = aiter_per1x128_quant(
183
- input_2d.contiguous(), quant_dtype=rocm_aiter.dtypes.fp8)
184
- else:
185
- q_input, x_scale = per_token_group_quant_fp8(
186
- input_2d, block_size[1], column_major_scales=False)
187
-
188
- output = w8a8_blockscale_func(q_input, weight, x_scale, weight_scale,
189
- block_size, input.dtype)
190
-
191
- if bias is not None:
192
- output = output + bias
193
- return output.to(dtype=input.dtype).view(*output_shape)
194
-
195
-
196
-def apply_w8a8_block_fp8_linear_fake(
197
- input: torch.Tensor,
198
- weight: torch.Tensor,
199
- block_size: list[int],
200
- weight_scale: torch.Tensor,
201
- input_scale: Optional[torch.Tensor] = None,
202
- bias: Optional[torch.Tensor] = None,
203
- cutlass_block_fp8_supported: bool = CUTLASS_BLOCK_FP8_SUPPORTED,
204
- use_aiter_and_is_supported: bool = False,
205
-) -> torch.Tensor:
206
- output_shape = [*input.shape[:-1], weight.shape[0]]
207
- return torch.empty(output_shape, dtype=input.dtype, device=input.device)
208
-
220
+ self.weight_group_shape,
221
+ output_dtype=input_2d.dtype)
222
210
-if not current_platform.is_cpu():
211
- direct_register_custom_op(
212
- op_name="apply_w8a8_block_fp8_linear",
213
- op_func=apply_w8a8_block_fp8_linear,
214
- mutates_args=[],
215
- fake_impl=apply_w8a8_block_fp8_linear_fake,
216
- )
223
+ def _run_cutlass(
224
+ self,
225
+ input_2d: torch.Tensor,
226
+ weight: torch.Tensor,
227
+ weight_scale: torch.Tensor,
228
+ ) -> torch.Tensor:
229
+ assert self.input_quant_op is not None
230
+ if self.is_hopper:
231
+ # We pad unconditionally (even if shape is already divisible by 4)
232
+ # to support dynamic shape for input_2d.shape[0] in torch.compile
233
+ x = torch.nn.functional.pad(input_2d,
234
+ (0, 0, 0, -input_2d.shape[0] % 4))
235
+ else:
236
+ x = input_2d
237
+
238
+ q_input, x_scale = self.input_quant_op(x)
239
+ output = cutlass_scaled_mm(q_input, weight, x_scale, weight_scale,
240
+ list(self.weight_group_shape),
241
+ input_2d.dtype, self.is_hopper)
242
+ output = output[0:input_2d.shape[0], ...]
243
+ return output
244
+
245
+ def _run_aiter(
246
+ self,
247
+ input_2d: torch.Tensor,
248
+ weight: torch.Tensor,
249
+ weight_scale: torch.Tensor,
250
+ ) -> torch.Tensor:
251
+ assert self.act_quant_group_shape == GroupShape(1, 128)
252
+ q_input, x_scale = aiter_per1x128_quant(
253
+ input_2d.contiguous(), quant_dtype=rocm_aiter.dtypes.fp8)
254
+ return torch.ops.vllm.rocm_aiter_gemm_w8a8_blockscale(
255
+ q_input, weight, x_scale, weight_scale, self.weight_group_shape,
256
+ input_2d.dtype)
257
+
258
+ def _run_triton(
259
+ self,
260
+ input_2d: torch.Tensor,
261
+ weight: torch.Tensor,
262
+ weight_scale: torch.Tensor,
263
+ ) -> torch.Tensor:
264
+ assert self.input_quant_op is not None
265
+ q_input, x_scale = self.input_quant_op(input_2d)
266
+ return torch.ops.vllm.w8a8_triton_block_scaled_mm_func(
267
+ q_input, weight, x_scale, weight_scale, self.weight_group_shape,
268
+ input_2d.dtype)
269
+
270
+ def _dispatch_w8a8_blockscale_op(
271
+ self,
272
+ use_cutlass: bool,
273
+ use_aiter_and_is_supported: bool,
274
+ ) -> tuple[Callable[[
275
+ torch.Tensor,
276
+ torch.Tensor,
277
+ torch.Tensor,
278
+ ], torch.Tensor], Optional[QuantFP8]]:
279
+ if use_cutlass:
280
+ return self._run_cutlass, (QuantFP8(False,
281
+ self.act_quant_group_shape,
282
+ column_major_scales=True,
283
+ use_ue8m0=False))
284
+ if use_aiter_and_is_supported:
285
+ return self._run_aiter, None
286
+ return self._run_triton, (QuantFP8(False,
287
+ self.act_quant_group_shape,
288
+ column_major_scales=False,
289
+ use_ue8m0=False))
290
291
292
def input_to_float8(
@@ -465,7 +538,7 @@ def per_token_group_quant_fp8(
538
539
540
@triton.jit
468
-def _w8a8_block_fp8_matmul(
541
+def _w8a8_triton_block_scaled_mm(
542
# Pointers to inputs and output
543
A,
544
B,
@@ -590,7 +663,7 @@ def get_w8a8_block_fp8_configs(N: int, K: int, block_n: int,
663
return None
664
665
593
-def w8a8_block_fp8_matmul(
666
+def w8a8_triton_block_scaled_mm(
667
A: torch.Tensor,
668
B: torch.Tensor,
669
As: torch.Tensor,
@@ -650,7 +723,7 @@ def w8a8_block_fp8_matmul(
723
return (triton.cdiv(M, META["BLOCK_SIZE_M"]) *
724
triton.cdiv(N, META["BLOCK_SIZE_N"]), )
725
653
- _w8a8_block_fp8_matmul[grid](
726
+ _w8a8_triton_block_scaled_mm[grid](
727
A,
728
B,
729
C,
@@ -997,25 +1070,6 @@ def maybe_post_process_fp8_weight_block(layer: torch.nn.Module,
1070
layer.weight_scale.data.T.contiguous(), requires_grad=False)
1071
1072
1000
-def apply_fp8_block_linear(layer: torch.nn.Module, input: torch.Tensor,
1001
- bias: Optional[torch.Tensor],
1002
- cutlass_block_fp8_supported: bool,
1003
- use_aiter_and_is_supported: bool) -> torch.Tensor:
1004
- """Apply block-wise FP8 linear operation."""
1005
- assert layer.weight_block_size is not None
1006
-
1007
- return torch.ops.vllm.apply_w8a8_block_fp8_linear(
1008
- input=input,
1009
- weight=layer.weight,
1010
- block_size=layer.weight_block_size,
1011
- weight_scale=layer.weight_scale,
1012
- input_scale=layer.input_scale,
1013
- bias=bias,
1014
- cutlass_block_fp8_supported=cutlass_block_fp8_supported,
1015
- use_aiter_and_is_supported=use_aiter_and_is_supported,
1016
- )
1017
-
1018
-
1073
def expert_weight_is_col_major(x: torch.Tensor) -> bool:
1074
assert x.dim() == 3
1075
b, m, n = x.shape
vllm/utils/deep_gemm.py
+8
-4
@@ -9,7 +9,7 @@ from __future__ import annotations
9
import functools
10
import importlib
11
import os
12
-from typing import Any, Callable, NoReturn
12
+from typing import Any, Callable, NoReturn, Optional
13
14
import torch
15
@@ -172,9 +172,13 @@ def calc_diff(x: torch.Tensor, y: torch.Tensor):
172
return 1 - sim
173
174
175
-def should_use_deepgemm_for_fp8_linear(output_dtype: torch.dtype,
176
- weight: torch.Tensor):
177
- return (is_deep_gemm_supported() and output_dtype == torch.bfloat16
175
+def should_use_deepgemm_for_fp8_linear(
176
+ output_dtype: torch.dtype,
177
+ weight: torch.Tensor,
178
+ supports_deep_gemm: Optional[bool] = None):
179
+ if supports_deep_gemm is None:
180
+ supports_deep_gemm = is_deep_gemm_supported()
181
+ return (supports_deep_gemm and output_dtype == torch.bfloat16
182
and weight.shape[0] % 128 == 0 and weight.shape[1] % 128 == 0)
183
184