[CPU][Whisper] Support W4A16 quantized Whisper on the CPU WNA16 kernel (#58268)

Signed-off-by: Harshal Adhav <harshal.adhav@amd.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Li, Jiang <jiang1.li@intel.com>
This commit is contained in:
Harshal Adhav
2026-09-30 13:52:53 +08:00
committed by GitHub
co-authored by Cursor Li, Jiang <jiang1.li@intel.com>
parent fcf4750466
commit 5faf81a429
5 changed files with 144 additions and 15 deletions
+5 -4
View File
@@ -203,7 +203,7 @@ class TestInt4ScaledMmCpu:
print(f" [PASS] INT4 GEMM with bias: M={M}")
def test_gemm_3d_input(self):
"""apply() reshapes 3D input [B, S, K] -> [B*S, K] -> back to 3D."""
"""int4_scaled_mm_cpu flattens 3D [B, S, K] to 2D and reshapes back."""
K, N, group_size = 256, 128, 128
(packed_qweight, packed_qzeros, scales, float_ref, _, _) = (
make_awq_checkpoint_data(K, N, group_size)
@@ -220,12 +220,13 @@ class TestInt4ScaledMmCpu:
x_3d = torch.randn(B, S, K, dtype=torch.bfloat16)
x_2d = x_3d.reshape(-1, K)
out_3d = int4_scaled_mm_cpu(x_3d, blocked_w, blocked_zp, blocked_s, None)
out_2d = int4_scaled_mm_cpu(x_2d, blocked_w, blocked_zp, blocked_s, None)
out_3d = out_2d.reshape(B, S, N)
ref_out = torch.mm(x_2d.float(), float_ref).reshape(B, S, N)
assert out_3d.shape == (B, S, N)
torch.testing.assert_close(out_3d.reshape(-1, N), out_2d)
ref_out = torch.mm(x_2d.float(), float_ref).reshape(B, S, N)
abs_diff = (out_3d.float() - ref_out).abs()
mean_abs = abs_diff.mean().item()
ref_mag = ref_out.abs().mean().item() + 1e-6
@@ -5,6 +5,7 @@ from collections.abc import Sequence
from typing import Any
import pytest
import torch
from transformers import AutoModelForSpeechSeq2Seq
from vllm.assets.audio import AudioAsset
@@ -264,6 +265,49 @@ def test_parse_language_detection_output():
cls.parse_language_detection_output([], make_tokenizer("anything"))
def test_create_fake_bias_for_k_proj_injects_out_features():
"""Packed k_proj weights get a zeros bias of length ``out_features``."""
from vllm.model_executor.models.whisper import _create_fake_bias_for_k_proj
packed = torch.ones(2, 16)
result = dict(
_create_fake_bias_for_k_proj(
[("model.encoder.layers.0.self_attn.k_proj.weight_packed", packed)],
".k_proj.weight_packed",
out_features=8,
)
)
bias_name = "model.encoder.layers.0.self_attn.k_proj.bias"
assert bias_name in result
assert "model.encoder.layers.0.self_attn.k_proj.bias_packed" not in result
assert tuple(result[bias_name].shape) == (8,)
assert torch.equal(result[bias_name], torch.zeros(8))
def test_create_fake_bias_for_k_proj_forwards_real_bias():
"""A checkpoint bias is forwarded and no extra fake bias is emitted."""
from vllm.model_executor.models.whisper import _create_fake_bias_for_k_proj
weight = torch.ones(8, 16)
real_bias = torch.ones(8)
items = list(
_create_fake_bias_for_k_proj(
[
("layers.0.self_attn.k_proj.weight", weight),
("layers.0.self_attn.k_proj.bias", real_bias),
],
".k_proj.weight",
out_features=8,
)
)
names = [n for n, _ in items]
assert names == [
"layers.0.self_attn.k_proj.weight",
"layers.0.self_attn.k_proj.bias",
]
assert items[1][1] is real_bias
@pytest.mark.core_model
@pytest.mark.cpu_model
@pytest.mark.parametrize("model", ["openai/whisper-large-v3-turbo"])
+45
View File
@@ -1,12 +1,57 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import pytest
import torch
from vllm.platforms import current_platform
if not current_platform.is_cpu():
pytest.skip("skipping CPU-only tests", allow_module_level=True)
from vllm._custom_ops import cpu_gemm_wna16 # noqa: E402
from vllm.model_executor.kernels.linear.mixed_precision.cpu import ( # noqa: E402
_get_isa_hint,
)
# Isolated runs of cpu_gemm_wna16 can hang unless AMX tiles are initialized.
# Guard so non-AMX hosts still take the vec/rvv path.
if torch.cpu._is_amx_tile_supported():
torch.cpu._init_amx()
@pytest.mark.cpu_test
def test_cpu_gemm_wna16_3d_input():
"""cpu_gemm_wna16 flattens 3D [B, T, K] to 2D and reshapes the output back."""
if not hasattr(torch.ops._C, "cpu_gemm_wna16"):
pytest.skip("cpu_gemm_wna16 op is not available")
B, T, K, N = 2, 5, 64, 64
pack_factor = 8
group_size = 32
dtype = torch.bfloat16
q_weight = torch.zeros(N // 16, K * 16 // pack_factor, dtype=torch.int32)
scales = torch.ones(K // group_size, N, dtype=dtype)
x_3d = torch.randn(B, T, K, dtype=dtype)
x_2d = x_3d.reshape(-1, K)
isa_hint = _get_isa_hint(dtype)
kwargs = dict(
q_weight=q_weight,
scales=scales,
zeros=None,
bias=None,
pack_factor=pack_factor,
isa_hint=isa_hint,
)
out_3d = cpu_gemm_wna16(input=x_3d, **kwargs)
out_2d = cpu_gemm_wna16(input=x_2d, **kwargs)
assert out_3d.shape == (B, T, N)
assert out_2d.shape == (B * T, N)
torch.testing.assert_close(out_3d.reshape(-1, N), out_2d)
MODELS = [
"TheBloke/TinyLlama-1.1B-Chat-v1.0-AWQ",
"Qwen/Qwen1.5-0.5B-Chat-GPTQ-Int4",
+9 -4
View File
@@ -4434,18 +4434,23 @@ def cpu_gemm_wna16(
pack_factor: int,
isa_hint: str,
) -> torch.Tensor:
output = torch.empty((input.size(0), scales.size(1)), dtype=input.dtype)
# Match int4_scaled_mm_cpu: flatten >2-D activations to [M, K] for the
# C++ kernel, then restore the original leading dims on the output.
x_shape = input.shape
x_2d = input.reshape(-1, x_shape[-1]) if len(x_shape) > 2 else input
out = torch.empty((x_2d.size(0), scales.size(1)), dtype=input.dtype)
torch.ops._C.cpu_gemm_wna16(
input,
x_2d,
q_weight,
output,
out,
scales,
zeros,
bias,
pack_factor,
isa_hint,
)
return output
out = out.reshape(x_shape[:-1] + (out.size(-1),)) if len(x_shape) > 2 else out
return out
def cpu_activation_lut_bf16(input: torch.Tensor, activation: str) -> torch.Tensor:
+41 -7
View File
@@ -1039,20 +1039,54 @@ class WhisperForConditionalGeneration(
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
loader = AutoWeightsLoader(self)
# add fake zeros bias for k_proj to state_dict
weights = _create_fake_bias_for_k_proj(weights, ".k_proj.weight")
# add fake zeros bias for k_proj to state_dict. Covers the
# ``.k_proj.weight`` and the compressed-tensors packed
# ``.k_proj.weight_packed`` checkpoints.
k_proj_weight_suffixes = (".k_proj.weight", ".k_proj.weight_packed")
for suffix in k_proj_weight_suffixes:
weights = _create_fake_bias_for_k_proj(
weights, suffix, out_features=self.config.d_model
)
return loader.load_weights(weights, mapper=self.hf_to_vllm_mapper)
def _create_fake_bias_for_k_proj(
weights: Iterable[tuple[str, torch.Tensor]], fake_bias_key_name: str
weights: Iterable[tuple[str, torch.Tensor]],
fake_bias_key_name: str,
out_features: int | None = None,
) -> Iterable[tuple[str, torch.Tensor]]:
"""Create full zeros bias for k_proj weight in self-attn and x-attn layers.
So that the bias for k_proj in qkv_proj can be initialized with zeros.
So that the bias for k_proj in qkv_proj or kv_proj can be initialized with
zeros.
If the checkpoint already provides a real ``.bias`` entry for the given
weight, it is forwarded as-is and no fake bias is injected for that layer.
"""
# Map the weight-name suffix to the corresponding bias-name suffix, e.g.
# ".k_proj.weight_packed" / ".k_proj.weight" -> ".k_proj.bias",
# ".wk.weight" -> ".wk.bias". ``.weight_packed`` is stripped first so the
# longer suffix wins.
bias_key_name = (
fake_bias_key_name.removesuffix(".weight_packed").removesuffix(".weight")
+ ".bias"
)
real_bias_names: set[str] = set()
pending: dict[str, torch.Tensor] = {}
for name, weight in weights:
yield name, weight
if name.endswith(bias_key_name):
real_bias_names.add(name)
pending.pop(name, None)
continue
if name.endswith(fake_bias_key_name):
bias = torch.zeros(weight.size(0))
bias_name = name.replace("weight", "bias")
yield bias_name, bias
bias_name = name[: -len(fake_bias_key_name)] + bias_key_name
if bias_name not in real_bias_names:
pending[bias_name] = torch.zeros(
out_features if out_features is not None else weight.size(0)
)
for bias_name, bias in pending.items():
yield bias_name, bias