diff --git a/tests/quantization/test_lm_head.py b/tests/quantization/test_lm_head.py index 16f8fd8d38..b89be3d055 100644 --- a/tests/quantization/test_lm_head.py +++ b/tests/quantization/test_lm_head.py @@ -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) diff --git a/tests/quantization/test_modelopt.py b/tests/quantization/test_modelopt.py index ae8548c370..d7b52723cb 100644 --- a/tests/quantization/test_modelopt.py +++ b/tests/quantization/test_modelopt.py @@ -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", [ diff --git a/vllm/model_executor/layers/quantization/compressed_tensors/schemes/compressed_tensors_wNa16.py b/vllm/model_executor/layers/quantization/compressed_tensors/schemes/compressed_tensors_wNa16.py index 8cfce07544..bf14f8a60b 100644 --- a/vllm/model_executor/layers/quantization/compressed_tensors/schemes/compressed_tensors_wNa16.py +++ b/vllm/model_executor/layers/quantization/compressed_tensors/schemes/compressed_tensors_wNa16.py @@ -119,8 +119,6 @@ class CompressedTensorsWNA16(CompressedTensorsScheme): layer.output_size_per_partition = output_size_per_partition layer.output_partition_sizes = output_partition_sizes layer.params_dtype = params_dtype - if not hasattr(layer, "has_bias"): - layer.has_bias = False mp_linear_kernel_config = MPLinearLayerConfig( full_weight_shape=(input_size, output_size), diff --git a/vllm/model_executor/layers/quantization/compressed_tensors/schemes/compressed_tensors_wNa4.py b/vllm/model_executor/layers/quantization/compressed_tensors/schemes/compressed_tensors_wNa4.py index acd4a96701..465f21a827 100644 --- a/vllm/model_executor/layers/quantization/compressed_tensors/schemes/compressed_tensors_wNa4.py +++ b/vllm/model_executor/layers/quantization/compressed_tensors/schemes/compressed_tensors_wNa4.py @@ -147,8 +147,6 @@ class CompressedTensorsWNA4Int(CompressedTensorsScheme): layer.output_size_per_partition = output_size_per_partition layer.output_partition_sizes = output_partition_sizes layer.params_dtype = params_dtype - if not hasattr(layer, "has_bias"): - layer.has_bias = False mp_config = MPLinearLayerConfig( full_weight_shape=(input_size, output_size), diff --git a/vllm/model_executor/layers/quantization/compressed_tensors/schemes/compressed_tensors_wNa8.py b/vllm/model_executor/layers/quantization/compressed_tensors/schemes/compressed_tensors_wNa8.py index 156f29908d..8c6a2c84ff 100644 --- a/vllm/model_executor/layers/quantization/compressed_tensors/schemes/compressed_tensors_wNa8.py +++ b/vllm/model_executor/layers/quantization/compressed_tensors/schemes/compressed_tensors_wNa8.py @@ -147,8 +147,6 @@ class CompressedTensorsWNA8Int(CompressedTensorsScheme): layer.output_size_per_partition = output_size_per_partition layer.output_partition_sizes = output_partition_sizes layer.params_dtype = params_dtype - if not hasattr(layer, "has_bias"): - layer.has_bias = False mp_config = MPLinearLayerConfig( full_weight_shape=(input_size, output_size), diff --git a/vllm/model_executor/layers/quantization/compressed_tensors/schemes/compressed_tensors_wNa8o8.py b/vllm/model_executor/layers/quantization/compressed_tensors/schemes/compressed_tensors_wNa8o8.py index 187b6438ab..dd1b986dc3 100644 --- a/vllm/model_executor/layers/quantization/compressed_tensors/schemes/compressed_tensors_wNa8o8.py +++ b/vllm/model_executor/layers/quantization/compressed_tensors/schemes/compressed_tensors_wNa8o8.py @@ -97,12 +97,8 @@ class CompressedTensorsWNA8O8Int(CompressedTensorsScheme): output_size_per_partition = sum(output_partition_sizes) layer.input_size_per_partition = input_size_per_partition layer.output_size_per_partition = output_size_per_partition - # Set for kernels' weight prep; also covers ParallelLMHead, which does - # not set these in __init__. layer.output_partition_sizes = output_partition_sizes layer.params_dtype = params_dtype - if not hasattr(layer, "has_bias"): - layer.has_bias = False mp_config = MPLinearLayerConfig( full_weight_shape=(input_size, output_size), diff --git a/vllm/model_executor/layers/quantization/modelopt.py b/vllm/model_executor/layers/quantization/modelopt.py index a9ac307159..7c06a23325 100644 --- a/vllm/model_executor/layers/quantization/modelopt.py +++ b/vllm/model_executor/layers/quantization/modelopt.py @@ -2508,12 +2508,6 @@ class ModelOptLinearMethod(LinearMethodBase): layer.logical_widths = output_partition_sizes layer.input_size_per_partition = input_size_per_partition layer.output_size_per_partition = sum(output_partition_sizes) - # Humming reads both off the layer in - # prepare_humming_linear_layer_config. LinearBase sets them itself; - # ParallelLMHead does not, so supply them here. - layer.output_partition_sizes = output_partition_sizes - if not hasattr(layer, "has_bias"): - layer.has_bias = getattr(layer, "bias", None) is not None shapes = Shapes(output_partition_sizes, input_size_per_partition, params_dtype) self.wkey.create_weights(layer, WEIGHT, self.ctx, shapes, weight_loader) diff --git a/vllm/model_executor/layers/vocab_parallel_embedding.py b/vllm/model_executor/layers/vocab_parallel_embedding.py index 72cafceb25..be20c41243 100644 --- a/vllm/model_executor/layers/vocab_parallel_embedding.py +++ b/vllm/model_executor/layers/vocab_parallel_embedding.py @@ -278,12 +278,12 @@ class VocabParallelEmbedding(PluggableLayer): self.num_embeddings = num_embeddings self.padding_size = padding_size self.org_vocab_size = org_num_embeddings or num_embeddings - num_added_embeddings = num_embeddings - self.org_vocab_size + self.num_added_embeddings = num_embeddings - self.org_vocab_size self.org_vocab_size_padded = pad_vocab_size( self.org_vocab_size, self.padding_size ) self.num_embeddings_padded = pad_vocab_size( - self.org_vocab_size_padded + num_added_embeddings, self.padding_size + self.org_vocab_size_padded + self.num_added_embeddings, self.padding_size ) assert self.org_vocab_size_padded <= self.num_embeddings_padded @@ -296,6 +296,18 @@ class VocabParallelEmbedding(PluggableLayer): self.tp_size, ) self.embedding_dim = embedding_dim + # Divide the weight matrix along the vocabulary dimension. + self.num_embeddings_per_partition = divide( + self.num_embeddings_padded, self.tp_size + ) + + # Quantization methods share the same weight factory as linear layers, + # so setup standard linear metadata. + self.input_size = self.input_size_per_partition = embedding_dim + self.output_size = self.num_embeddings_padded + self.output_size_per_partition = self.num_embeddings_per_partition + self.output_partition_sizes = [self.output_size_per_partition] + self.prefix = prefix # Avoid overriding a preselected model-specific method with generic # config-based dispatch. @@ -322,11 +334,6 @@ class VocabParallelEmbedding(PluggableLayer): if params_dtype is None: params_dtype = torch.get_default_dtype() self.params_dtype = params_dtype - # Divide the weight matrix along the vocabulary dimension. - self.num_added_embeddings = self.num_embeddings - self.org_vocab_size - self.num_embeddings_per_partition = divide( - self.num_embeddings_padded, self.tp_size - ) assert ( self.shard_indices.num_elements_padded == self.num_embeddings_per_partition ) @@ -349,10 +356,10 @@ class VocabParallelEmbedding(PluggableLayer): self.quant_method.create_weights( self, - self.embedding_dim, - [self.num_embeddings_per_partition], - self.embedding_dim, - self.num_embeddings_padded, + self.input_size_per_partition, + self.output_partition_sizes, + self.input_size, + self.output_size, params_dtype=params_dtype, weight_loader=self.weight_loader, ) @@ -600,6 +607,7 @@ class ParallelLMHead(VocabParallelEmbedding): *, disable_tp: bool = False, ): + self.has_bias = bias super().__init__( num_embeddings, embedding_dim,