[MRV2][Spec Decode] Quantized draft lm_head for drafters that share the target head (#59973)
Signed-off-by: Stefano Castagnetta <scastagnetta@nvidia.com> Co-authored-by: Kevin H. Luu <khluu000@gmail.com>
This commit is contained in:
co-authored by
Kevin H. Luu
parent
d92a4f25f2
commit
784d1fff0c
@@ -5,7 +5,13 @@ import pytest
|
||||
|
||||
from tests.utils import single_gpu_only
|
||||
from vllm import SamplingParams
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
from ...utils import (
|
||||
assert_request_outputs_match,
|
||||
compute_acceptance_len,
|
||||
get_test_prompts,
|
||||
)
|
||||
from .._correctness import check_mtp_correctness
|
||||
|
||||
|
||||
@@ -37,3 +43,107 @@ def test_mtp_correctness(
|
||||
expected_accuracy_threshold,
|
||||
vllm_runner,
|
||||
)
|
||||
|
||||
|
||||
@single_gpu_only
|
||||
def test_mtp_draft_lm_head_quantization(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
sampling_config: SamplingParams,
|
||||
vllm_runner,
|
||||
):
|
||||
"""A quantized draft copy of the shared lm_head only changes drafting:
|
||||
greedy outputs match stock MTP and acceptance stays within 10%."""
|
||||
monkeypatch.setenv("VLLM_USE_V2_MODEL_RUNNER", "1")
|
||||
prompts = get_test_prompts(mm_enabled=False)
|
||||
results = {}
|
||||
# NVFP4 needs a CUDA W4A16 kernel.
|
||||
quants = (None, "fp8", "nvfp4") if current_platform.is_cuda() else (None, "fp8")
|
||||
for quant in quants:
|
||||
with vllm_runner(
|
||||
"Qwen/Qwen3.5-0.8B-Base",
|
||||
block_size=None,
|
||||
enable_chunked_prefill=None,
|
||||
max_model_len=2048,
|
||||
limit_mm_per_prompt={"image": 0, "video": 0},
|
||||
speculative_config={
|
||||
"method": "mtp",
|
||||
"num_speculative_tokens": 3,
|
||||
"draft_lm_head_quantization": quant,
|
||||
},
|
||||
disable_log_stats=False,
|
||||
) as runner:
|
||||
outputs = runner.llm.chat(prompts, sampling_config)
|
||||
results[quant] = (outputs, compute_acceptance_len(runner.llm.get_metrics()))
|
||||
|
||||
ref_outputs, ref_al = results.pop(None)
|
||||
for quant, (outputs, al) in results.items():
|
||||
assert_request_outputs_match(
|
||||
ref_outputs,
|
||||
outputs,
|
||||
# Not bit-exact: a different acceptance length changes the target's
|
||||
# verify batch shapes, which can flip a near-tied greedy token.
|
||||
required_matches=int(0.8 * len(ref_outputs)) + 1,
|
||||
context=f"draft_lm_head_quantization={quant}",
|
||||
)
|
||||
assert al >= 0.9 * ref_al, (
|
||||
f"{quant}: acceptance length {al:.3f} vs {ref_al:.3f}"
|
||||
)
|
||||
|
||||
|
||||
@single_gpu_only
|
||||
@pytest.mark.skipif(
|
||||
not current_platform.is_cuda(), reason="nvfp4 needs a CUDA W4A16 kernel"
|
||||
)
|
||||
def test_mtp_draft_lm_head_quantization_survives_sleep_and_reload(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
sampling_config: SamplingParams,
|
||||
vllm_runner,
|
||||
):
|
||||
"""The quantized draft head is derived from the target head: it must come
|
||||
back intact after a level 1 sleep and be re-derived after a target weight
|
||||
reload, so outputs and acceptance match the run before."""
|
||||
monkeypatch.setenv("VLLM_USE_V2_MODEL_RUNNER", "1")
|
||||
prompts = get_test_prompts(mm_enabled=False)
|
||||
with vllm_runner(
|
||||
"Qwen/Qwen3.5-0.8B-Base",
|
||||
block_size=None,
|
||||
enable_chunked_prefill=None,
|
||||
max_model_len=2048,
|
||||
limit_mm_per_prompt={"image": 0, "video": 0},
|
||||
speculative_config={
|
||||
"method": "mtp",
|
||||
"num_speculative_tokens": 3,
|
||||
"draft_lm_head_quantization": "nvfp4",
|
||||
},
|
||||
enable_sleep_mode=True,
|
||||
disable_log_stats=False,
|
||||
) as runner:
|
||||
llm = runner.llm
|
||||
|
||||
def run():
|
||||
before = llm.get_metrics()
|
||||
outputs = llm.chat(prompts, sampling_config)
|
||||
return outputs, compute_acceptance_len(llm.get_metrics(), before)
|
||||
|
||||
ref_outputs, ref_al = run()
|
||||
|
||||
llm.sleep(level=1)
|
||||
llm.wake_up()
|
||||
outputs, al = run()
|
||||
assert_request_outputs_match(
|
||||
ref_outputs,
|
||||
outputs,
|
||||
required_matches=int(0.8 * len(ref_outputs)) + 1,
|
||||
context="after level 1 sleep",
|
||||
)
|
||||
assert al == pytest.approx(ref_al, rel=0.03)
|
||||
|
||||
llm.collective_rpc("reload_weights")
|
||||
outputs, al = run()
|
||||
assert_request_outputs_match(
|
||||
ref_outputs,
|
||||
outputs,
|
||||
required_matches=int(0.8 * len(ref_outputs)) + 1,
|
||||
context="after weight reload",
|
||||
)
|
||||
assert al == pytest.approx(ref_al, rel=0.03)
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import gc
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.model_executor.layers.logits_processor import LogitsProcessor
|
||||
from vllm.model_executor.layers.quantization.online.lm_head import (
|
||||
quantized_lm_head_copy,
|
||||
refresh_quantized_lm_heads,
|
||||
)
|
||||
from vllm.model_executor.layers.vocab_parallel_embedding import ParallelLMHead
|
||||
from vllm.model_executor.model_loader.reload import (
|
||||
finalize_layerwise_reload,
|
||||
initialize_layerwise_reload,
|
||||
record_metadata_for_reloading,
|
||||
)
|
||||
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.v1.worker.gpu_worker import Worker
|
||||
|
||||
# Not a multiple of the vocab padding, so the head has padded rows.
|
||||
VOCAB, HIDDEN = 4000, 512
|
||||
requires_cuda = pytest.mark.skipif(
|
||||
not torch.cuda.is_available(), reason="Marlin needs CUDA"
|
||||
)
|
||||
# NVFP4 needs a CUDA W4A16 kernel; ROCm only runs the fp8 cases.
|
||||
requires_nvfp4 = pytest.mark.skipif(
|
||||
not current_platform.is_cuda(), reason="nvfp4 needs a CUDA W4A16 kernel"
|
||||
)
|
||||
NVFP4 = pytest.param("nvfp4", marks=requires_nvfp4)
|
||||
|
||||
|
||||
def _target_head(monkeypatch, seed: int = 0) -> ParallelLMHead:
|
||||
# Online methods read the model dtype from the current config.
|
||||
model_config = SimpleNamespace(dtype=torch.bfloat16)
|
||||
monkeypatch.setattr(
|
||||
"vllm.model_executor.layers.quantization.online.fp8.get_current_vllm_config",
|
||||
lambda: SimpleNamespace(model_config=model_config),
|
||||
)
|
||||
head = ParallelLMHead(VOCAB, HIDDEN, disable_tp=True)
|
||||
gen = torch.Generator().manual_seed(seed)
|
||||
head.weight.data.copy_(torch.randn(head.weight.shape, generator=gen) * 0.02)
|
||||
return head.to("cuda", torch.bfloat16)
|
||||
|
||||
|
||||
def _tensors(module: torch.nn.Module) -> dict[str, torch.Tensor]:
|
||||
return dict(module.named_parameters()) | dict(module.named_buffers())
|
||||
|
||||
|
||||
@requires_cuda
|
||||
@pytest.mark.parametrize(
|
||||
("quantization", "max_rel_err", "min_top1"),
|
||||
[("fp8", 0.05, 0.9), pytest.param("nvfp4", 0.15, 0.75, marks=requires_nvfp4)],
|
||||
)
|
||||
def test_tracks_bf16_head_through_logits_processor(
|
||||
default_vllm_config, dist_init, monkeypatch, quantization, max_rel_err, min_top1
|
||||
):
|
||||
head = _target_head(monkeypatch)
|
||||
target_weight = head.weight.detach().clone()
|
||||
draft_head = quantized_lm_head_copy(head, quantization)
|
||||
|
||||
assert isinstance(draft_head, ParallelLMHead)
|
||||
# The source head keeps its bf16 weight, and no bf16 copy is kept around.
|
||||
assert torch.equal(head.weight, target_weight)
|
||||
assert draft_head.weight.dtype != torch.bfloat16
|
||||
|
||||
logits_processor = LogitsProcessor(VOCAB)
|
||||
hidden = torch.randn(2048, HIDDEN, device="cuda", dtype=torch.bfloat16)
|
||||
ref = logits_processor(head, hidden).float()
|
||||
out = logits_processor(draft_head, hidden).float()
|
||||
assert out.shape == ref.shape == (2048, VOCAB)
|
||||
rel_err = ((out - ref).norm() / ref.norm()).item()
|
||||
top1 = (out.argmax(-1) == ref.argmax(-1)).float().mean().item()
|
||||
assert rel_err < max_rel_err
|
||||
assert top1 > min_top1
|
||||
|
||||
|
||||
@requires_cuda
|
||||
@pytest.mark.parametrize("quantization", ["fp8", NVFP4])
|
||||
def test_refresh_follows_target_update(
|
||||
default_vllm_config, dist_init, monkeypatch, quantization
|
||||
):
|
||||
"""After the target's weights change, the copy is re-derived in place: it
|
||||
equals a fresh quantization of the new target, keeps its storage, and
|
||||
frees the temporary copy without waiting for the cycle collector."""
|
||||
head = _target_head(monkeypatch)
|
||||
drafter = torch.nn.Module()
|
||||
drafter.lm_head = quantized_lm_head_copy(head, quantization)
|
||||
ptrs = {k: t.data_ptr() for k, t in _tensors(drafter.lm_head).items()}
|
||||
|
||||
new_weight = _target_head(monkeypatch, seed=1).weight.detach()
|
||||
head.weight.data.copy_(new_weight)
|
||||
gc.disable()
|
||||
try:
|
||||
allocated = torch.accelerator.memory_allocated()
|
||||
refresh_quantized_lm_heads(drafter)
|
||||
assert torch.accelerator.memory_allocated() == allocated
|
||||
finally:
|
||||
gc.enable()
|
||||
|
||||
expected = _tensors(quantized_lm_head_copy(head, quantization))
|
||||
for name, tensor in _tensors(drafter.lm_head).items():
|
||||
assert tensor.data_ptr() == ptrs[name]
|
||||
if name != "workspace":
|
||||
assert torch.equal(tensor, expected[name]), name
|
||||
assert torch.equal(head.weight, new_weight)
|
||||
|
||||
|
||||
def _draft_update_worker(vllm_config, drafter: torch.nn.Module, **engine) -> Worker:
|
||||
worker = object.__new__(Worker)
|
||||
worker.vllm_config = vllm_config
|
||||
worker.weight_transfer_engine = SimpleNamespace(
|
||||
supports_draft_weight_update=True,
|
||||
reset_weight_update_target=lambda: None,
|
||||
**engine,
|
||||
)
|
||||
worker.model_runner = SimpleNamespace(get_draft_model=lambda: drafter)
|
||||
worker._weight_update_active = False
|
||||
worker._set_draft_weight_update_target = lambda: None
|
||||
return worker
|
||||
|
||||
|
||||
@requires_cuda
|
||||
def test_draft_weight_update_refreshes_copy(
|
||||
default_vllm_config, dist_init, monkeypatch
|
||||
):
|
||||
"""A draft weight update can write a target weight the drafter shares, such
|
||||
as an embedding tied to the lm_head; the copy must follow it."""
|
||||
head = _target_head(monkeypatch)
|
||||
drafter = torch.nn.Module()
|
||||
drafter.lm_head = quantized_lm_head_copy(head, "fp8")
|
||||
worker = _draft_update_worker(
|
||||
default_vllm_config,
|
||||
drafter,
|
||||
start_weight_update=lambda: None,
|
||||
finish_weight_update=lambda: None,
|
||||
)
|
||||
|
||||
worker.start_draft_weight_update()
|
||||
head.weight.data.copy_(_target_head(monkeypatch, seed=1).weight)
|
||||
worker.finish_weight_update()
|
||||
|
||||
expected = _tensors(quantized_lm_head_copy(head, "fp8"))
|
||||
for name, tensor in _tensors(drafter.lm_head).items():
|
||||
assert torch.equal(tensor, expected[name]), name
|
||||
|
||||
|
||||
@requires_cuda
|
||||
@pytest.mark.parametrize("quantization", ["fp8", NVFP4])
|
||||
def test_draft_weight_update_loads_lm_head(
|
||||
default_vllm_config, dist_init, monkeypatch, quantization
|
||||
):
|
||||
"""A draft update carrying lm_head.weight loads the shared target head, as
|
||||
without quantization, and the copy is re-derived from it in place."""
|
||||
head = _target_head(monkeypatch)
|
||||
record_metadata_for_reloading(head)
|
||||
drafter = torch.nn.Module()
|
||||
draft_head = quantized_lm_head_copy(head, quantization)
|
||||
drafter.lm_head = draft_head
|
||||
ptrs = {k: t.data_ptr() for k, t in _tensors(draft_head).items()}
|
||||
new_weight = torch.randn(VOCAB, HIDDEN, device="cuda", dtype=torch.bfloat16)
|
||||
|
||||
def load(update_info):
|
||||
param = drafter.get_parameter("lm_head.weight")
|
||||
getattr(param, "weight_loader", default_weight_loader)(param, new_weight)
|
||||
|
||||
worker = _draft_update_worker(
|
||||
default_vllm_config,
|
||||
drafter,
|
||||
start_weight_update=lambda: initialize_layerwise_reload(drafter),
|
||||
update_weights=load,
|
||||
finish_weight_update=lambda: finalize_layerwise_reload(drafter, None),
|
||||
)
|
||||
worker.start_draft_weight_update()
|
||||
worker.update_weights({})
|
||||
worker.finish_weight_update()
|
||||
|
||||
assert drafter.lm_head is draft_head
|
||||
assert torch.equal(head.weight[:VOCAB], new_weight)
|
||||
expected = _tensors(quantized_lm_head_copy(head, quantization))
|
||||
for name, tensor in _tensors(draft_head).items():
|
||||
assert tensor.data_ptr() == ptrs[name]
|
||||
if name != "workspace":
|
||||
assert torch.equal(tensor, expected[name]), name
|
||||
hidden = torch.randn(64, HIDDEN, device="cuda", dtype=torch.bfloat16)
|
||||
assert LogitsProcessor(VOCAB)(draft_head, hidden).isfinite().all()
|
||||
|
||||
|
||||
@requires_cuda
|
||||
@requires_nvfp4
|
||||
def test_layerwise_reload_of_drafter_keeps_copy(
|
||||
default_vllm_config, dist_init, monkeypatch
|
||||
):
|
||||
"""A drafter weight update reloads the drafter layerwise; the derived copy
|
||||
must come back unchanged, not be re-quantized."""
|
||||
head = _target_head(monkeypatch)
|
||||
drafter = torch.nn.Module()
|
||||
record_metadata_for_reloading(drafter)
|
||||
drafter.lm_head = quantized_lm_head_copy(head, "nvfp4")
|
||||
before = {k: t.clone() for k, t in _tensors(drafter.lm_head).items()}
|
||||
|
||||
def fail(*args, **kwargs):
|
||||
raise AssertionError("the copy was re-quantized")
|
||||
|
||||
monkeypatch.setattr(
|
||||
drafter.lm_head.quant_method, "process_weights_after_loading", fail
|
||||
)
|
||||
initialize_layerwise_reload(drafter)
|
||||
finalize_layerwise_reload(drafter, None)
|
||||
|
||||
after = _tensors(drafter.lm_head)
|
||||
assert after.keys() == before.keys()
|
||||
for name, tensor in before.items():
|
||||
assert torch.equal(after[name], tensor), name
|
||||
@@ -65,6 +65,9 @@ class _RecordingModelRunner:
|
||||
def reset_lora_state(self) -> None:
|
||||
self.reset_lora_calls += 1
|
||||
|
||||
def get_draft_model(self) -> nn.Module | None:
|
||||
return None
|
||||
|
||||
|
||||
def _make_worker(engine: _RecordingEngine | None) -> Worker:
|
||||
worker = object.__new__(Worker)
|
||||
|
||||
Reference in New Issue
Block a user