[Bugfix][Quantization] Give LM heads standard linear metadata (#58444)
Signed-off-by: mgoin <mgoin64@gmail.com>
This commit is contained in:
@@ -5,14 +5,26 @@
|
||||
Run `pytest tests/quantization/test_quant_lm_head_true.py --forked`.
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from compressed_tensors.quantization import preset_name_to_scheme
|
||||
|
||||
from tests.quantization.utils import load_model_without_vllm_runner
|
||||
from vllm.model_executor.layers.linear import ColumnParallelLinear
|
||||
from vllm.model_executor.layers.logits_processor import LogitsProcessor
|
||||
from vllm.model_executor.layers.quantization.auto_gptq import AutoGPTQLinearMethod
|
||||
from vllm.model_executor.layers.quantization.compressed_tensors.compressed_tensors import ( # noqa: E501
|
||||
CompressedTensorsConfig,
|
||||
)
|
||||
from vllm.model_executor.layers.quantization.modelopt import ModelOptNvFp4Config
|
||||
from vllm.model_executor.layers.vocab_parallel_embedding import (
|
||||
ParallelLMHead,
|
||||
UnquantizedEmbeddingMethod,
|
||||
)
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.utils.import_utils import has_humming
|
||||
|
||||
PROMPT = "On the surface of Mars, we found"
|
||||
|
||||
@@ -44,3 +56,65 @@ def test_lm_head(
|
||||
assert isinstance(lm_head_layer.quant_method, AutoGPTQLinearMethod)
|
||||
else:
|
||||
assert isinstance(lm_head_layer.quant_method, UnquantizedEmbeddingMethod)
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
not current_platform.is_cuda() or not has_humming(), reason="requires Humming/CUDA"
|
||||
)
|
||||
@pytest.mark.parametrize(
|
||||
"preset,quant_format",
|
||||
[
|
||||
("FP8_DYNAMIC", "float-quantized"),
|
||||
("NVFP4A16", "nvfp4-pack-quantized"),
|
||||
("W4A16", "pack-quantized"),
|
||||
("W4A16_NVFP4", None),
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize("bias", [False, True])
|
||||
@torch.inference_mode()
|
||||
def test_quantized_lm_head_matches_linear(
|
||||
dist_init, default_vllm_config, preset, quant_format, bias
|
||||
):
|
||||
"""An explicitly quantized head must produce the same logits as a linear layer."""
|
||||
default_vllm_config.model_config = SimpleNamespace(
|
||||
dtype=torch.bfloat16, head_dtype=None
|
||||
)
|
||||
default_vllm_config.kernel_config.linear_backend = "humming"
|
||||
if quant_format is None:
|
||||
quant_config = ModelOptNvFp4Config(
|
||||
quant_method=preset,
|
||||
is_checkpoint_nvfp4_serialized=True,
|
||||
kv_cache_quant_algo=None,
|
||||
exclude_modules=[],
|
||||
)
|
||||
else:
|
||||
scheme = preset_name_to_scheme(preset, targets=["Linear", "lm_head"])
|
||||
quant_config = CompressedTensorsConfig.from_config(
|
||||
{"config_groups": {"group_0": scheme.model_dump()}, "format": quant_format}
|
||||
)
|
||||
with torch.device("cuda"):
|
||||
kwargs = dict(
|
||||
bias=bias,
|
||||
params_dtype=torch.bfloat16,
|
||||
quant_config=quant_config,
|
||||
disable_tp=True,
|
||||
)
|
||||
head = ParallelLMHead(500, 256, prefix="lm_head", **kwargs)
|
||||
linear = ColumnParallelLinear(256, 512, prefix="proj", **kwargs)
|
||||
for name, param in linear.named_parameters():
|
||||
if "scale" in name:
|
||||
param.fill_(1.0)
|
||||
elif name == "weight_shape":
|
||||
param.copy_(torch.tensor([512, 256]))
|
||||
elif param.is_floating_point():
|
||||
param.copy_(torch.randn(param.shape, dtype=torch.float32))
|
||||
else:
|
||||
param.random_(0, 127)
|
||||
head.load_state_dict(linear.state_dict())
|
||||
for layer in (head, linear):
|
||||
layer.quant_method.process_weights_after_loading(layer)
|
||||
x = torch.randn(8, 256, dtype=torch.bfloat16)
|
||||
expected, _ = linear(x)
|
||||
actual = LogitsProcessor(500)(head, x, head.bias)
|
||||
assert torch.isfinite(actual).all()
|
||||
torch.testing.assert_close(actual, expected[:, :500], rtol=0, atol=0)
|
||||
|
||||
@@ -718,49 +718,6 @@ def test_modelopt_w4a16_respects_linear_backend(linear_backend, kernel_cls):
|
||||
assert isinstance(kernel, kernel_cls)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not current_platform.is_cuda(), reason="CUDA only")
|
||||
def test_modelopt_linear_exposes_humming_layer_attrs(dist_init, monkeypatch):
|
||||
"""``prepare_humming_linear_layer_config`` reads ``output_partition_sizes``
|
||||
and ``has_bias`` straight off the layer, so ``--linear-backend=humming``
|
||||
needs create_weights to leave both there. Nothing else sets
|
||||
``output_partition_sizes``; ``LinearBase`` sets ``has_bias`` but
|
||||
``ParallelLMHead`` does not.
|
||||
"""
|
||||
from vllm.config.quantization import QuantSpec
|
||||
from vllm.model_executor.layers.quantization import modelopt as mo
|
||||
|
||||
monkeypatch.setattr(
|
||||
mo, "select_linear_kernel", lambda spec, layer, rt, **kwargs: Mock()
|
||||
)
|
||||
monkeypatch.setattr(mo, "expose_input_quant_key", lambda layer, kernel: None)
|
||||
|
||||
def build(layer):
|
||||
method = ModelOptLinearMethod.__new__(ModelOptLinearMethod)
|
||||
method.spec = QuantSpec(weight=kNvfp4Static, activation=None)
|
||||
method.ctx = mo.CkptCtx(group_size=16)
|
||||
method.fmt = mo.FormatScheme()
|
||||
method.wkey = mo.SCHEME_FOR[kNvfp4Static]
|
||||
method.akey = None
|
||||
method.input_dtype = method.out_dtype = torch.bfloat16
|
||||
method.marlin_input_dtype = None
|
||||
method.create_weights(
|
||||
layer, 64, [32, 32], 64, 64, torch.bfloat16, weight_loader=Mock()
|
||||
)
|
||||
|
||||
# ParallelLMHead-style: a bias slot but no has_bias attribute.
|
||||
lm_head = torch.nn.Module()
|
||||
lm_head.register_parameter("bias", None)
|
||||
build(lm_head)
|
||||
assert lm_head.output_partition_sizes == [32, 32]
|
||||
assert lm_head.has_bias is False
|
||||
|
||||
# LinearBase already decided has_bias; we must not overwrite it.
|
||||
linear = torch.nn.Module()
|
||||
linear.has_bias = True
|
||||
build(linear)
|
||||
assert linear.has_bias is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"quant_method, expected_use_a16, act_key_is_none",
|
||||
[
|
||||
|
||||
Reference in New Issue
Block a user